Python Module-1
Python Module-1
Module 1
Introduction:
Python is a general purpose programming language like C, C++, JAVA created by Guido Vas
Rossum.
Features of Python:
Application of Python:
Software development
Web application development
Text processing
System scripting (Shell programming)
Data analytics
Many more…
Version history:
Python 0.9.0- 1991
Python 1.0- 1994
Python 2.0- 2000
Python 3 – 2008
Python 3.9 – 2020
Python 3.10 – 2021
Python download:
Python.org
Note: these commands has to be executed in command line. In Jupyter notebook use !pip
list, !pip install package name
Syntax:
Whitespace for indentation to define a scope for loop, function, classes ( curly
brackets {} are not used)
Subsequent lines in the indented regions should be in the same column
Code block is called as suites
No semi-colon at the end of statement
Use backslash character \ to join a statement span over multiple lines
o E.g.,
if a > b and \
a <= c:
print('a is largest')
Indentation Rules
E.g.,
Executing Code:
Keywords:
Identifiers:
Rules:
This identifier is used to store the result of the last evaluation in the interactive
interpreter.
Named memory locations. Variables are created when you assign a value
to it.
E.g.,
Operators:
Arithmetic Operators
Assignment Operators
Comparison Operators
Logical Operators
Identity Operators
Membership Test Operators
Bitwise Operators
Arithmetic Operators
The arithmetic operators return the type of result depends on the type of
operands, as below.
Assignment Operators
= >>> x = 5;
>>> x
5
+= operator.iadd(a,b) >>> x = 5
>>> x += 5
10
>>> import operator
>>> x = operator.iadd(5, 5)
10
-= operator.isub(a,b) >>> x = 5
>>> x -= 2
3
>>> import operator
>>> x = operator.isub(5,2)
*= operator.imul(a,b) >>> x = 2
>>> x *= 3
6
>>> import operator
>>> x = operator.imul(2, 3)
/= operator.itruediv(a,b) >>> x = 6
>>> x /= 3
2
>>> import operator
>>> x = operator.itruediv(6, 3)
//= operator.ifloordiv(a,b) >>> x = 6
>>> x //= 5
1
>>> import operator
>>> operator.ifloordiv(6,5)
%= operator.imod(a, b) >>> x = 11
>>> x %= 3
Operator Function Example in Python Shell
2
>>> import operator
>>> operator.imod(11, 3)
2
&= operator.iand(a, b) >>> x = 11
>>> x &= 3
1
>>> import operator
>>> operator.iand(11, 3)
1
|= operator.ior(a, b) >>> x = 3
>>> x |= 4
7
>>> import operator
>>> operator.mod(3, 4)
7
^= operator.ixor(a, b) >>> x = 5
>>> x ^= 2
7
>>> import operator
>>> operator.ixor(5, 2)
7
>>= operator.irshift(a, b) >>> x = 5
>>> x >>= 2
1
>>> import operator
>>> operator.irshift(5, 2)
1
<<= operator.ilshift(a, b) >>> x = 5
>>> x <<= 2
20
>>> import operator
>>> operator.ilshift(5, 2)
20
Comparison Operators
Logical Operators
The logical operators are used to combine two boolean expressions. The
logical operations are generally applicable to all objects, and support truth
tests, identity tests, and boolean operations.
Operator Description Example
Identity Operators
The identity operators check whether the two objects have the same id
value e.i. both the objects point to the same memory location.
The membership test operators in and not in test whether the sequence
has a given item or not. For the string and bytes types, x in y is True if
and only if x is a substring of y.
True
>>> import operator
>>>
operator.contains(nums,
2)
True
not in not Returns True if the >>> nums = [1,2,3,4,5]
operator.contains(a,b) sequence does not >>> 1 not in nums
False
contains the specified
>>> 10 not in nums
item, else returns False. True
>>> 'str' not in 'string'
False
>>> import operator
>>> not
operator.contains(nums,
2)
False
Bitwise Operators
& operator.and_(a,b) Sets each bit to 1 if both bits are 1. >>> x=5; y=10
>>> z=x & y
>>> z
0
>>> import operator
>>> operator.and_(x,
y)
0
| operator.or_(a,b) Sets each bit to 1 if one of two bits >>> x=5; y=10
is 1. >>> z=x | y
>>> z
15
>>> import operator
>>> operator.or_(x,
y)
15
^ operator.xor(a,b) Sets each bit to 1 if only one of two >>> x=5; y=10
bits is 1. >>> z=x ^ y
>>> z
15
>>> import operator
Operator Function Description Example in Python Shell
>>> operator.xor(x,
y)
15
~ operator.invert(a) Inverts all the bits. >>> x=5
>>> ~x
-6
>>> import operator
>>>
operator.invert(x)
-6
<< operator.lshift(a,b) Shift left by pushing zeros in from >>> x=5
the right and let the leftmost bits >>> x<<2
20
fall off.
>>> import operator
>>>
operator.lshift(x,2)
20
>> operator.rshift(a,b) Shift right by pushing copies of the >>> x=5
leftmost bit in from the left, and let >>> x>>2
1
the rightmost bits fall off.
>>> import operator
>>>
operator.rshift(x,2)
1
When an expression contains more than one operator, the order of evaluation depends
on the order of operations. For mathematical operators, Python follows mathematical
convention. The acronym PEMDAS is a useful way to remember the rules:
• Parentheses have the highest precedence and can be used to force an expression to
evaluate in the order you want. Since expressions in parentheses are evaluated first,
2 * (3-1) is 4, and (1+1)**(5-2) is 8. You can also use parentheses to make an
expression easier to read, as in (minute * 100) / 60, even if it doesn’t change the
result.
• Exponentiation has the next highest precedence, so 1 + 2**3 is 9, not 27, and 2 *
3**2 is 18, not 36.
• Multiplication and Division have higher precedence than Addition and Subtraction.
So 2*3-1 is 5, not 4, and 6+4/2 is 8, not 5.
• Operators with the same precedence are evaluated from left to right (except
exponentiation).
So in the expression degrees / 2 * pi, the division happens first and the
result is multiplied by pi. To divide by 2p, you can use parentheses or write degrees
/ 2 / pi.
Data Types:
Scalar Types
Sequence Type
Mapping Type
Set Types
Data objects of the above types are stored in a computer's memory for
processing. Some of these values can be modified during processing, but
contents of others can't be altered once they are created in the memory.
Numbers, strings, and Tuples are immutable, which means their contents
can't be altered after creation.
Type Conversion:
Python provides us with the two inbuilt functions as input() and print().
Input function:
The syntax for input is input(prompt_message); the python will automatically identify
whether the user entered a string, number, or list; if the input entered from the user is not
correct, then python will throw a syntax error.
E.g,
i=int(x)
j=int(y)
Output function:
We use the print() function to output data to the standard output device (screen)
Syntax: The actual syntax of the print() function is:
The sep separator is used between the values. It defaults into a space character.
After all values are printed, end is printed. It defaults into a new line.
The file is the object where the values are printed and its default value is sys.stdout
(screen). Here is an example to illustrate this.
E.g.,
a=5
print(1, 2, 3, 4) o/p-> 1 2 3 4
Output formatting
>>> x = 5; y = 10
Here, the curly braces {} are used as placeholders. We can specify the
order in which they are printed by using numbers (tuple index).
print('I love {0} and {1}'.format('MIT','MCA'))
We can also format strings like the old sprintf() style used in C
programming language. We use the % operator to accomplish this.
>>> x = 12.3456789
1 if statements
Looping/Iterative statements:
Python provides with While loop and for loop for executing code
repeatedly.
While loop:
Entry controlled loop: first, the given condition is verified then the
execution of statements is determined based on the condition result
Syntax:
while condition:
Statement_1
Statement_2
Statement_3
...
E.g.,
x=1
n=5
while (x <=10):
p=x*n
print(n,’*’,x,’=’,p)
x=x+1
Do-While Loop:
For loop:
For loop in Python is used to iterate over items of any sequence, such as a list or a
string.
Syntax:
statements
statements
Run Code
Output :-
1
22
333
4444
55555
for i in range(1,6):
for j in range(5,i-1,-1):
print(i, end=" ")
print('')
Output :-
11111
2222
333
44
5
The break is a keyword in python which is used to bring the program control out of
the loop. The break statement breaks the loops one by one, i.e., in the case of nested
loops, it breaks the inner loop first and then proceeds to outer loops. In other words,
we can say that break is used to abort the current execution of the program and the
control goes to the next line after the loop.
The break is commonly used in the cases where we need to break the loop for a given
condition.
Example 1
n=2
while 1:
i=1;
while i<=10:
print("%d X %d = %d\n"%(n,i,n*i));
i = i+1;
choice = int(input("Do you want to continue printing the table, press 0 for no?"))
if choice == 0:
break;
n=n+1
Continue statement:
The continue statement skips the remaining lines of code inside the loop and start with
the next iteration.
#loop statements
continue
#the code to be skipped
E.g.,
i=0
while(i < 10):
i = i+1
if(i == 5):
continue
print(i)
Pass statement:
he pass keyword is used to execute nothing; it means, when we don't want to execute
code, the pass can be used to execute empty. to bypass any code pass statement can be
used.
Usage:
# Empty Function
def function_name(args):
pass
#Empty Class
class Python:
pass
Functions in Python:
Creating a Function
Example
def my_function():
print("Hello from a function")
Calling a Function
Example
def my_function():
print("Hello from a function")
my_function()
Arguments
Arguments are specified after the function name, inside the parentheses.
You can add as many arguments as you want, just separate them with a
comma.
The following example has a function with one argument (fname). When
the function is called, we pass along a first name, which is used inside the
function to print the full name:
Example
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
If you do not know how many arguments that will be passed into your
function, add a * before the parameter name in the function definition.
This way the function will receive a tuple of arguments, and can access
the items accordingly:
Example
def my_function(*kids):
print("The youngest child is " + kids[2])
Keyword Arguments
You can also send arguments with the key = value syntax.
Example
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
If you do not know how many keyword arguments that will be passed into
your function, add two asterisk: ** before the parameter name in the
function definition.
This way the function will receive a dictionary of arguments, and can
access the items accordingly:
Example
def my_function(**kid):
print("His last name is " + kid["lname"])
Example
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
Return Values
Example
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
Lambda function:
Syntax
lambda arguments : expression
Example
x = lambda a : a + 10
print(x(5))
Example
x = lambda a, b : a * b
print(x(5, 6))
Void function:
E.g.,
# Creation of Function
function add_v(a, b);
c = a + b;
print(c);
end
# Function Call
add_v(3, 4)
The part of a program where a variable is accessible is called as scope, and the
duration for which the variable exists its lifetime.
A variable which is defined in the main body of a file is called a global variable. It will
be visible throughout the file, and also inside any file which imports that file.
A variable which is defined inside a function is local to that function. It is accessible
from the point at which it is defined until the end of the function, and exists for as
long as the function is executing. If we want to access the global value for a variable
inside a function we need to use global keyword.
E.g.,
def myfunc():
global x
print(x)
x = 300
print(x)
x=12
myfunc()
print(x)
Output:
12
300
300
Python Modules
Create a Module
To create a module just save the code you want in a file with the file
extension .py:
Example
def greeting(name):
print("Hello, " + name)
Use a Module
Example
Import the module named mymodule, and call the greeting function:
import mymodule
mymodule.greeting("Chandrajit")
Variables in Module
The module can contain functions, as already described, but also variables
of all types (arrays, dictionaries, objects etc):
Example
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
Example
Import the module named mymodule, and access the person1 dictionary:
import mymodule
a = mymodule.person1["age"]
print(a)
Re-naming a Module
Example
a = mx.person1["age"]
print(a)
As we know that the Python interactive shell has a number of built-in functions. As a
shell start, these functions are loaded automatically and are always available, such
as,
In addition to these many built-in functions, there are also a large number of pre-
These functions are defined in modules which are known as built-in modules.
These built-in modules are written in C language and integrated with the Python
shell.
help('modules')
Math Module
Random Module
Datetime Module
Statistics Module
math.dist() Returns the Euclidean distance between two points (p and q), wher
point
Math Constants
Constant Description
Statistics Methods
Method Description
Random Module
Python has a built-in module that you can use to make random numbers.
getstate() Returns the current internal state of the random number generator
choices() Returns a list with a random selection from the given sequence
triangular() Returns a random float number between two given parameters, you c
specify the midpoint between the two other parameters
Example: Let’s suppose there is a Python script for adding two numbers and the
numbers are passed as command-line arguments.
# total arguments
n = len(sys.argv)
# Arguments passed
# Addition of numbers
Sum = 0
Sum += int(sys.argv[i])
print("\n\nResult:", Sum)
Output:
$ python test.py 10 20
10 20
Result: 30