MAC_py_1
MAC_py_1
Python is a high-level programming language that has become one of the world's most popular
languages today. Its syntax is simple and minimalistic, allowing developers to write clean and elegant
code. Python also offers several advantages over other high-level languages, which we will explore in
due course. Python has proven to be an exceptionally versatile language, with wide-ranging
applications in basic science, engineering, data science, data management, machine learning(ML),
deep learning, networking, web development, and more. A vast number of scientific modules and
libraries have been developed for Python.As an open-source language, it enjoys strong community
support worldwide.
Unlike FORTRAN, C, or C++, Python is an interpreted language. This means that code is executed line-
by-line directly in the Python interpreter or shell, rather than requiring the entire program to be
compiled first. However, when programs become longer and more complex, they are typically written
in files (known as Python scripts) and then executed as complete programs. Python supports both
functional programming and object-oriented programming (OOP) paradigms, making it highly flexible
for various types of software development.
Variables
A variable name (or any identifier such as a class, function, module, or object name) in Python can
consist of letters, numbers, and the underscore (_) symbol. However, special characters such as @, $,
%, *, and mathematical operators like +, -, /, etc., cannot be used in variable names.
Variable names must begin with a letter (either uppercase or lowercase, A–Z) and cannot start with a
number. Additionally, variable names are case-sensitive—for example, Xy, xy, and xY are all considered
different variables.
Importantly, variable names cannot be Python reserved words (also called keywords), which are
special words reserved for system commands and functions. These keywords are written in lowercase
and must not be used as variable names.
and, assert, break, class, continue, def, del, elif, except, exec,
finally, for, from, global, if, import, in, is, lambda, not, or, pass,
print, raise, return, try, while, with, yield
Numbers
There are three different kinds of numbers that a computer program usually handles: integer, float
(real numbers with decimal part) and complex (a+ bj, j=√−1). Python supports all three kinds. Integers
in Python 3 are of unlimited size. Python 2 has two integer types: - int and long. There is no 'long
integer' type in Python 3 anymore. In addition, Booleans are a subtype of plain integers.
Integer [Examples: 236, -123] Float (or floating point numbers)[Examples: 13.25, 0.0, -13.23] Complex [Examples: 5j, 9.8j, 3+2j, 1.2e-10j] Long
[Examples: Any integer that ends with ‘l’ or ‘L’. 123L will be treated as long in Python 2.] Boolean: True, False
In [ ]: # Mathematical Operators
#Consider two variables a and b. The following operations are with
# a=20, b=4
# Addition a+b=24
# Subtraction a-b=16
# Multiplication a*b=80
# Division a/b=5.0
# Modulo a%b=0
# Power or exponent (**) a**b=160000
#--------------------------------------------------------------
# Apart from math operators we have other kinds of operators too.
# Comparison Operators
# == Equal to
# != Not equal to
# <> Less than and Greater than < Less than
# > Greater than
# >= Greater than equal to <= Less than equal to
In [5]: print(x,y,z)
15 12.6 -10
In [7]: # Style no 2
x, y, z = 15, 12.6, -10 # [Multiple inputs in one line]
print(x,y,z)
15 12.6 -10
In [52]: # Style no 3
a = eval(input("Enter value")) # output after entering 12
# The built-in function eval() is used to evaluate the input string.
# Thus, we get back the number from a string of number.
In [53]: b= eval(input("Enter value \t")) # output after entering 10, \t for tab space
In [55]: a = eval(input("Enter value \n")) # output after entering 12, \n for a new line
Output Styles
‘ \n’)The syntax: print(values, sep = ‘ ’, end =‘ \n’) It prints values with gap (if no separation is mentioned and the cursor stops on the new line
due to ‘\n’ as default.)
In [56]: x, y = 2, 3
print(x, y)
2 3
values = ,2,3
In [62]: print( x, y, sep = ',', end = ' ')
2,3
Formatted Output
Formatting is to write output strings/ data in predefined styles or formats. We can give any number of
spaces in between two elements, create new lines etc. as we represent the output data in a way we
wish. The formatting is done with strings and so it is called string formatting.
In [63]: x, y = 4, 5
print(x, y) # Unformatted
4 5
4 and 5
5 and 4
3.142
3.1416,2.71828
2.7183,3.14159
Commenting
As we write standard Python scripts, we take care of the readability to others and, we make it easier
for our own reading later. For this purpose, we write documentation, title etc. inside a script.
Comment a Single Line We can comment a line if we put a # (hash) symbol in front of line. This means, the compiler will ignore this line, yet we
can keep this in a code.Comment a Block of Lines Also, we can comment a block of text or code with triple quotes. (On IDLE interpreter or
Python shells, this usually makes a change of text color of that block, to be identified easily.)
In [ ]:
Typing on Python Interpretor
Let us begin to type on Python IDLE interpreter (>>>) or command line [IDLE = Integrated
Development and Learning Environment]. We type some line or some instruction on the interpreter
and then‘Enter’ key to execute. The line that appears below is the output or some message that it
returns. Sometimes, nothing returns as output which indicates that the instruction is accepted
without error. Else, we may get an error message.] We must type anything from the start (from the
first column) on interpreter or inside any Python shell. We are not allowed to press ‘space bar’ before
we write. In the latter case, it will raise error. Each line is an instruction. A set of Python instructions
will form a Python code. We can write the lines in a file which is usually called Python script. Python
scripts (programs or codes) are automatically saved with extension .py. Example: somefile.py
In [1]: dir(list)
Out[1]: ['__add__',
'__class__',
'__class_getitem__',
'__contains__',
'__delattr__',
'__delitem__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__getitem__',
'__getstate__',
'__gt__',
'__hash__',
'__iadd__',
'__imul__',
'__init__',
'__init_subclass__',
'__iter__',
'__le__',
'__len__',
'__lt__',
'__mul__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__reversed__',
'__rmul__',
'__setattr__',
'__setitem__',
'__sizeof__',
'__str__',
'__subclasshook__',
'append',
'clear',
'copy',
'count',
'extend',
'index',
'insert',
'pop',
'remove',
'reverse',
'sort']
In [2]: help(list.pop)
Help on method_descriptor:
pop(self, index=-1, /)
Remove and return item at index (default last).
In [17]: a=[3,34,64,12,-234,35,-24,0,245]
b =[3, 4,6 ,1 ,-234,35,-2 ,0,25,'a']
#print(type(a))
type(a)
print(a)
print(b)
In [23]: print(list(range(5)))
print(list())
[0, 1, 2, 3, 4]
[]
In [25]: print(a)
Python as Calculator
Python interpreter or Python shell can be used as a calculator.
Out[3]: 8.4
In [5]: 19 - 6 # Subtraction
Out[5]: 13
In [6]: 2 * 9 # Multiplication
Out[6]: 18
Out[10]: 29.0
Out[11]: 6.0
Out[12]: 63.475
Out[13]: 16
Out[14]: 3
Out[16]: (3+9j)
In [18]: (3+9j)+(3+2.4j)
Out[18]: (6+11.4j)
Out[19]: (2+23j)
Note: Python computes in the mixed mode. For mathematical operations involving integer, float, and
complex numbers, Python returns the output in complex. We can think of complex as broader than a
float and a float as broader than an integer. Python will return in the broadest of all.
Out[20]: 2
Out[21]: 1
Out[22]: 1
Out[23]: 0
Comparison of Numbers
In [24]: 2 > 3
Out[24]: False
In [25]: 3 < 9
Out[25]: True
In [26]: 5 == 6
Out[26]: False
Out[27]: True
Out[28]: True
In [29]: 10%3 == 1
Out[29]: True
Type()
The built-in function type() determines the type of an object.
Out[31]: int
Out[32]: float
Out[33]: complex
In [34]: type('Python')
Out[34]: str
In [35]: type(True)
Out[35]: bool
In [37]: type(False)
Out[37]: bool
Out[38]: 23.0
Out[39]: 23
Out[40]: (2+0j)
In [41]: complex(2, 3)
Out[41]: (2+3j)
Absolute values
In [42]: abs(-23.56) # Absolute value 23.56
Out[42]: 23.56
In [43]: int(abs(-23.56))
Out[43]: 23
Out[44]: 5.0
Out[45]: 16
Out[46]: -2
Out[47]: 10
Rounding off
In [48]: round(13.145) # [Rounding off to nearest integer]
Out[48]: 13
Out[49]: 23.92
Out[50]: 23.924
In [51]: round(1/3, 3)
Out[51]: 0.333
Note: If nothing is specified, round()function rounds off the decimal number to the nearest integer
(ceiling or floor of the number)
In [ ]: