01_Python_I_All_Master_13_02_2025
01_Python_I_All_Master_13_02_2025
PYTHON
FCP – Introduction to Dr. Abhinav Kumar, Dept. of Computer Science & Engineering, MNNIT
Python (Part – 1) Allahabad
Credits
https://www.tutorialspoint.com/python3/
Machine learning: an algorithmic perspective. 2nd Edition, Marsland,
Stephen. CRC press, 2015. Appendix A.
https://docs.python.org/3.6/
https://docs.python.org/3.6/library/random.html
http://www.pythonforbeginners.com/random/how-to-use-the-random-
module-in-python
https://www.geeksforgeeks.org/
Python is a general-purpose interpreted, interactive, object-oriented,
and high-level programming language.
Portable (Same program can run on different systems without modifying anything)
Extendable (Same code can also be written in other languages)
Databases
GUI Programming
Hello World Program
print("Hello, World!")
Python Identifiers
Used to identify a variable, function, class, module or other object
An identifier starts with a letter A to Z or a to z or an underscore (_) followed by
zero or more letters, underscores and digits (0 to 9).
we should not use special characters ( #, @, $, %, ! ) in identifiers.
print(newlist[0])
3
#indexing starts at 0
#returns element from the last
newlist = [3, 2, [5, 4, 3], [2, 3, 2]]
print(newlist[-1])
[2, 3, 2]
print(newlist[-2])
[5, 4, 3]
print(newlist[3][1])
3
Slice operator ‘:’
newlist = [3, 2, [5, 4, 3], [2, 3, 2]]
print(newlist[2:4])
[[5, 4, 3], [2, 3, 2]]
#inclusive of start index and exclusive of end index
print(newlist[0:4:2])
[3, [5, 4, 3]]
#behaves as [start:stop:step]
newlist = [3, 2, [5, 4, 3], [2, 3, 2]]
print(newlist[::-1])
[[2, 3, 2], [5, 4, 3], 2, 3]
#reverses the elements of the list
print(newlist[:3])
[3, 2, [5, 4, 3]]
print(newlist[1:])
[2, [5, 4, 3], [2, 3, 2]]
mylist = [3, 2, [5, 4, 3], [2, 3, 2]]
alist = mylist #does shallow copy
alist[0]=4
print(mylist)
[4, 2, [5, 4, 3], [2, 3, 2]]
#However
alist[2][0]=1
print(mylist)
[4, 2, [1, 4, 3], [2, 3, 2]]
Deep Copy
import copy
mylist = [3, 2, [5, 4, 3], [2, 3, 2]]
alist = copy.deepcopy(mylist)
alist[0]=5
alist[2][0]=2
print(mylist)
print(alist)
[3, 2, [5, 4, 3], [2, 3, 2]]
[5, 2, [2, 4, 3], [2, 3, 2]]
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
print (tinylist * 2) # Prints list two times
[123, 'john', 123, 'john']
print (list + tinylist) # Prints concatenated lists
['abcd', 786, 2.23, 'john', 70.2, 123, 'john']
Comparing Lists
a==b
Compares lists item wise, returns TRUE if elements and their count is the same;
returns FALSE otherwise
a =[3, 2, 4, 1]
b= [3, 2, 4, 1]
print(a==b)
True
c = [3,2,4,1,0]
print(a==c)
False
Tuple
A tuple is an immutable list, meaning that it is read-only and doesn’t
change.
Tuples are defined using round brackets
num = input ("Enter number :") num = int(input ("Enter number :"))
print(num) print(num)
name1 = input("Enter name : ") name1 = int(input("Enter name : "))
print(name1)
print(name1)
# Printing type of input value
print ("type of number", type(num)) # Printing type of input value
print ("type of name", type(name1)) print ("type of number", type(num))
print(num + name1)
print ("type of name", type(name1))
print(num + name1)
Suppose num = 66 and name1 = 6; what
will be the output of these programs?
Reading Input
num = input ("Enter number :") num = int(input ("Enter number :"))
print(num) print(num)
name1 = input("Enter name : ") name1 = int(input("Enter name : "))
print(name1)
print(name1)
# Printing type of input value
print ("type of number", type(num)) # Printing type of input value
print ("type of name", type(name1)) print ("type of number", type(num))
print(num + name1)
print ("type of name", type(name1))
print(num + name1)
Output: 666 Output: 72
Data Type Conversion
There are two types of Type Conversion in Python:
1. Implicit Type Conversion: Python interpreter automatically converts one data
type to another without any user involvement.
2. Explicit Type Conversion: Data type is manually changed by the user as per their
requirement. With explicit type conversion, there is a risk of data loss since we are
forcing an expression to be changed in some specific data type.
Data Type Conversion
Implicit Type Conversion Explicit Type Conversion
x = 10
print(type(x)) s = "10010“
Output: <class 'int'> c = int(s,2)
y = 10.6 print (c)
print(type(y)) Output: 18
Output: <class 'float'>
e = float(s)
print (e)
z=x+y
Output: 10010.0
print(z)
Output: 20.6
print(type(z))
Output: <class 'float'>
Data Type Conversion
To convert between types, you simply use the type-name as a function.
ord() : This function is used to convert a character to integer.
print(int(2.7)) hex() : This function is to convert integer to hexadecimal string.
2 oct() : This function is to convert integer to octal string.
chr() : This function is to convert Unicode value to character.
print(float(2))
s = '4’ X = chr(52)
2.0 c = ord(s) print(X)
print (c) Output: ‘4’
print(complex(2,4)) Output: 52
(2+4j) c = hex(56)
print (c)
print(str(44+55)+str(30/9)) Output: 0x38
993.3333333333333335 c = oct(56)
print (c)
Output: 0o70
Basic Operators
Arithmetic Operators
Comparison (Relational) Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
Assume
a=10 and
b=21
Arithmetic Operators
Assume
a=10 and
b=20
1. a = 21; b = 10; c = 0 10. c=a%b
2. c=a+b 11. print ("Line 5 - Value of c is ", c)
3. print ("Line 1 - Value of c is ", c) Line 5 - Value of c is 1
Line 1 - Value of c is 31 12. a=2
4. c=a-b 13. b=3
5. print ("Line 2 - Value of c is ", c ) 14. c = a**b
Line 2 - Value of c is 11 15. print ("Line 6 - Value of c is ", c)
6. c=a*b Line 6 - Value of c is 8
7. print ("Line 3 - Value of c is ", c) 16. a = 10
Line 3 - Value of c is 210 17. b=5
8. c=a/b 18. c = a//b
9. print ("Line 4 - Value of c is ", c ) 19. print ("Line 7 - Value of c is ", c)
Line 4 - Value of c is 2.1 Line 7 - Value of c is 2
Comparison Operators
b=20
Assume
a=10 and
1. a = 21; b = 10 10. if ( a < b ):
2. if ( a == b ): 11. print ("Line 3 - a is less than b" )
3. print ("Line 1 - a is equal to b") 12. else:
4. else: 13. print ("Line 3 - a is not less than
5. print ("Line 1 - a is not equal to b")
b") Line 3 - a is not less than b
Line 1 - a is not equal to b 14. if ( a > b ):
6. if ( a != b ): 15. print ("Line 4 - a is greater than
7. print ("Line 2 - a is not equal to b")
b") 16. else:
8. else: 17. print ("Line 4 - a is not greater
9. print ("Line 2 - a is equal to b") than b")
Line 2 - a is not equal to b Line 4 - a is greater than b
1. a = 21; b = 10 8. print ("Line 6 - b is either
2. a,b=b,a #values of a and b greater than or equal to b")
swapped. a becomes 10, b 9. else:
becomes 21 10. print ("Line 6 - b is neither
3. if ( a <= b ): greater than nor equal to b")
4. print ("Line 5 - a is either less Line 6 - b is either greater than or equal to
b
than or equal to b")
5. else:
6. print ("Line 5 - a is neither less
than nor equal to b")
Line 5 - a is either less than or equal to b
7. if ( b >= a ):
x=4
print(3<x<6)
True
# not equal to test is != or <>
Assignment Operator
Assignment Operator (II)
1. a = 21 11. print ("Line 4 - Value of c is ", c )
2. b = 10 Line 4 - Value of c is 52.0
3. c=0 12. c=2
4. c=a+b 13. c %= a
5. print ("Line 1 - Value of c is ", c) 14. print ("Line 5 - Value of c is ", c)
Line 1 - Value of c is 31 Line 5 - Value of c is 2
6. c += a 15. c **= a
7. print ("Line 2 - Value of c is ", c ) 16. print ("Line 6 - Value of c is ", c)
Line 2 - Value of c is 52 Line 6 - Value of c is 2097152
8. c *= a 17. c //= a
9. print ("Line 3 - Value of c is ", c ) 18. print ("Line 7 - Value of c is ", c)
Line 3 - Value of c is 1092 Line 7 - Value of c is 99864
10. c /= a
Bitwise Operators
Signed Number Representation
Range of numbers :
Unsigned number: 0 – (2^n)-1
6. print ("result of AND is ", c,':',bin(c)) 14. print ("result of LEFT SHIFT is ",
result of AND is 12 : 0b1100 c,':',bin(c))
result of LEFT SHIFT is 240 : 0b11110000
7. c = a | b; # 61 = 0011 1101
8. print ("result of OR is ", c,':',bin(c)) 15. c = a >> 2; # 15 = 0000 1111
result of OR is 61 : 0b111101 16. print ("result of RIGHT SHIFT is ",
9. c = a ^ b; # 49 = 0011 0001 c,':',bin(c))
result of RIGHT SHIFT is 15 : 0b1111
10. print ("result of EXOR is ",
Logical Operators
x=5
y=2
print((x>4) and (y<3))
True
print((x>5) or (y<3))
True
Line 1 - a is not available in the given list 16. print ("Line 3 - a is not
8. if ( b not in list ): available in the given list")
9. print ("Line 2 - b is not Line 3 - a is available in the given list
available in the given list")
Identity Operators
Compare the memory locations of two objects.
Python id() Function
# if statement example
a = 100
if a > 5:
print("a greater than 5")
print("Program ended")
Output: No
Nested if-else
Output:
Bigger than 5
Between 5 and 15
If-elif statement
Output: letter is A
Elif in Nested If
x = 10
y=5
if x > 5:
if y > 5: Output:
x is greater than 5 and y is 5
print("x and y are greater than 5")
elif y == 5:
print("x is greater than 5 and y is 5")
else:
print("x is greater than 5 and y is less than 5")
if statement
var1 = 100
if var1:
print ("1 - Got a true expression value")
print (var1)
var2 = 0
if var2:
print ("2 - Got a true expression value")
print (var2)
print ("Good bye!")
1 - Got a true expression value
100
Good bye!
if else statement
amount=int(input("Enter amount: ")) Output:
if amount<1000: Enter amount: 300
discount=amount*0.05 Discount 15.0
print ("Discount",discount) Net payable: 285.0
else:
discount=amount*0.10
print ("Discount",discount)
print ("Net payable:",amount-discount)
elif statement (Just like ‘else if’ in C/C++)
amount=int(input("Enter amount: ")) Output 1:
if amount<1000:
Enter amount: 600
discount=amount*0.05
print ("Discount",discount) Discount 30.0
elif amount<5000: Net payable: 570.0
discount=amount*0.10
print ("Discount",discount)
else:
discount=amount*0.15
print ("Discount",discount)
print ("Net payable:",amount-discount)
elif statement (Just like ‘else if’ in C/C++)
amount=int(input("Enter amount: ")) Output 2:
if amount<1000:
Enter amount: 3000
discount=amount*0.05
print ("Discount",discount) Discount 300.0
elif amount<5000: Net payable: 2700.0
discount=amount*0.10
print ("Discount",discount)
else:
discount=amount*0.15
print ("Discount",discount)
print ("Net payable:",amount-discount)
elif statement (Just like ‘else if’ in C/C++)
amount=int(input("Enter amount: ")) Output 3:
if amount<1000:
Enter amount: 6000
discount=amount*0.05
print ("Discount",discount) Discount 900.0
elif amount<5000: Net payable: 5100.0
discount=amount*0.10
print ("Discount",discount)
else:
discount=amount*0.15
print ("Discount",discount)
print ("Net payable:",amount-discount)
Ternary Operator
x=5
b = int(input("Enter a Number: "))
result = "Positive" if x > 0 else "Negative"
output = b if b>=0 else 0
print(result)
print(output)
Output: Output:
Positive Enter a Number: 5
a=3 5
result = "Positive" if a**2 - a**3 > 0 else "Negative"
Enter a Number: 0
print(result) 0
Output:
Negative
Looping Constructs
Loops
while loop
count = 0 Output:
The count is: 0
while (count < 9): The count is: 1
print ('The count is:', count) The count is: 2
count = count + 1 The count is: 3
print ("Good bye!") The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
Good bye!
Using else with while loop
If the else statement is used with a Output:
while loop, the else statement is 0 is less than 5
executed when the condition
becomes false. 1 is less than 5
count = 0 2 is less than 5
while count < 5: 3 is less than 5
print (count, " is less than 5") 4 is less than 5
count = count + 1 5 is not less than 5
else:
print (count, " is not less than 5")
range() function
range(n) generates an iterator to progress integers starting with 0
upto n-1.
print(range(0, 5))
range(0, 5)
To obtain a list object of the sequence, it is type casted to list().
Output:
the list does not contain even number
the list does not contain even number
the list does not contain even number
the list contains an even number
numbers=[11,33,55,38,55,75,37,21,23,41,13]
for num in numbers:
if num%2==0:
print ('the list contains an even number')
break
else:
print ('the list does not contain even number’)
list[2] = 2001
print ("New value available at index 2 : ", list[2])
New value available at index 2 : 2001
Lists – updating multiple elements using “:”
evenList = [0,2,4,6]
oldList = [1,3,5,7]
newList = [9,9,9,9,9,9,9,9]
print(newList)
[9, 9, 9, 9, 9, 9, 9, 9]
newList[::2]=evenList
newList[1::2]=oldList
print(newList)
[0, 1, 2, 3, 4, 5, 6, 7]
List: deleting an element using del
list = ['physics', 'chemistry', 1997, 2000]
print (list)
['physics', 'chemistry', 1997, 2000]
del list[2]
print ("After deleting value at index 2 : ", list)
After deleting value at index 2 : ['physics', 'chemistry', 2000]
Basic List Operations
Indexing and Slicing
Built-in List Functions
List len() Method
len() method returns the number of elements in the list.
Syntax
len(list)
Parameters
list - This is a list for which, number of elements are to be counted.
Return Value
This method returns the number of elements in the list.
list1 = ['physics', 'chemistry', 'maths']
print (len(list1))
3
Unicode:
❑ Designed to support a much larger set of characters from various languages and scripts.
❑ Typically uses 8, 16, or 32 bits to encode characters, allowing for over a million unique values.
❑ Unicode can represent characters from nearly every language, symbols, emojis, and more.
The first 128 characters in Unicode are identical to ASCII
char = ' '
unicode_value = ord(char)
print(f"The Unicode value of '{char}' in hex is: {hex(unicode_value)}")
Output:
The Unicode value of ' ' in hex is: 0x1f60a
List list() Method
list() method takes sequence types and converts them to lists. This is
used to convert a given tuple into list.
Syntax
list(seq )
Parameters
seq - This is a tuple or string to be converted into list.
Return Value
This method returns the list.
aTuple = (123, 'C++', 'Java', 'Python')
list1 = list(aTuple)
print ("List elements : ", list1)
List elements : [123, 'C++', 'Java', 'Python']
str="Hello World"
list2=list(str)#converts string to a list
print ("List elements : ", list2)
List elements : ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
list Methods
list.append(obj): Appends object obj to list
list.count(obj): Returns count of how many times obj occurs in list
list.extend(seq): Appends the contents of seq to list
list.index(obj): Returns the lowest index in list that obj appears
list.insert(index, obj): Inserts object obj into list at offset index
list.pop(obj=list[-1]): Removes and returns last object or obj from list
list.remove(obj): Removes object obj from list
list.reverse(): Reverses objects of list in place
list.sort([func]): Sorts objects of list, use compare func if given
List append() Method
append() method appends a passed obj into the existing list.
Syntax
append(obj)
Parameters
obj - This is the object to be appended in the list.
Return Value
This method does not return any value but updates existing list.
list1 = ['C++', 'Java', 'Python']
list1.append('C#')
print ("updated list : ", list1)
updated list : ['C++', 'Java', 'Python', 'C#']
List count() Method
count() method returns count of how many times obj occurs in list.
Syntax
count(obj)
Parameters
obj - This is the object to be counted in the list.
Return Value
This method returns count of how many times obj occurs in list.
aList = [123, 'xyz', 'zara', 'abc', 123];
print ("Count for 123 : ", aList.count(123))
Count for 123 : 2
Return Value
This method does not return any value but it inserts the given element at the
given index.
list1 = ['physics', 'chemistry', 'maths']
list1.insert(1, 'Biology')
print ('Final list : ', list1)
Final list : ['physics', 'Biology', 'chemistry', 'maths']
List pop() Method
pop() method removes and returns last object or obj from the list.
Syntax
pop(obj=list[-1])
Parameters
obj - This is an optional parameter, index of the object to be removed from
the list.
Return Value
This method returns the removed object from the list.
list1 = ['physics', 'Biology', 'chemistry',
'maths']
list1.pop()
print ("list now : ", list1)
list now : ['physics', 'Biology', 'chemistry']
list1.pop(1)
print ("list now : ", list1)
list now : ['physics', 'chemistry']
List remove() Method
remove() removes given obj from the list
Syntax
remove(obj)
Parameters
obj - This is the object to be removed from the list.
Return Value
This method does not return any value but removes the given object from the
list
list1 = ['physics', 'Biology', 'chemistry',
'maths']
list1.remove('Biology')
list now : ['physics', 'chemistry', 'maths']
import sys
from support import print_func sys.path.insert(0, “Path”)
print_func("Zara") from support import print_func
print_func("Zara")
If both codes are in the same folder
If both codes are in the different folders
__main__
# creating a simple add function
def add(a, b): The odd_even(55)
return a+b function will only run if
the program is executed
directly as the main script.
# creating a simple odd_even function
If this code is imported
# to check if the number is odd or even into another program, the
def odd_even(n): odd_even(55)
if n % 2 == 0: function will not be
print("Even") executed automatically.
else:
print("Odd")
if __name__ == '__main__':
print("This will run if name is __main__")
odd_even(55)
Random Library
random: Generate pseudo-random numbers
This module implements pseudo-random number generators for various
distributions.
When to use it?
We want the computer to pick a random number in a given range
Pick a random element from a list, pick a random card from a deck, flip a
coin etc.
Shuffling a list of numbers of data samples
outcomes = { 'heads':0,
import random
'tails':0,
}
sides = list(outcomes.keys()) x = "WELCOME"
Return Value
This method returns a random item from the given range.
import random
# randomly select an odd number between 1-100
print ("randrange(1,100, 2) : ",
random.randrange(1, 100, 2))
randrange(1,100, 2) : 85
random.seed(10)
print ("random number with int seed",
random.random())
random number with int seed 0.5714025946899135
shuffle()
shuffle() method randomizes the items of a list in place.
Syntax
shuffle (lst,[random])
Parameters
lst- This could be a list or tuple.
random - This is an optional 0 argument function returning float between 0.0
-1.0.
Return Value
This method returns reshuffled list.
import random
list = [20, 16, 10, 5];
random.shuffle(list)
print ("Reshuffled list : ", list)
Reshuffled list : [5, 16, 10, 20]
random.shuffle(list)
print ("Reshuffled list : ", list)
Reshuffled list : [20, 10, 5, 16]
uniform()
uniform() method returns a random float r, such that x is less than or
equal to r and r is less than y.
Syntax
uniform(x, y)
Parameters
x - Sets the lower limit of the random float.
y - Sets the upper limit of the random float.
Return Value
This method returns a floating point number r such that x <=r < y.
import random
print ("Random Float uniform(5, 10) : ",
random.uniform(5, 10))
Random Float uniform(5, 10) : 9.481444778178155
print(mybigarray)
[[3 2 4]
[3 3 2]
[4 5 2]]
print(np.arange(5))
[0 1 2 3 4]
print(np.arange(3,7,2))
[3 5]
#arange(start,stop,step)
print(np.ones(3))
[ 1. 1. 1.]
print(np.ones((3,4)))
[[ 1. 1. 1. 1.]
[ 1. 1. 1. 1.]
[ 1. 1. 1. 1.]]
print(np.eye(3,4))
[[ 1. 0. 0. 0.]
[ 0. 1. 0. 0.]
[ 0. 0. 1. 0.]]
#fills the spare rows/columns with 0
print(np.linspace(3,7,3))
[ 3. 5. 7.]
#returns evenly spaced numbers in the given range.
#np.linspace(start,stop,npoints)
print(np.r_[np.array([1,2,3]), 0, 0, np.array([4,5,6])])
[1 2 3 0 0 4 5 6]
#np.r_ concatenates arrays along first axis (np.array([1,2,3]).shape = (3, ))
print(np.r_[1:4,0,4])
[1 2 3 0 4]
#np.c_ concatenates arrays along second axis
import numpy as np
Output:
print(np.c_[np.array([1,2,3]), np.array([4,5,6])]) [[1 4]
[2 5]
print(np.array([1,2,3]).shape) [3 6]]
(3,)
print(np.array([4,5,6]).shape)
(3,)
print(np.c_[np.array([1,2,3]), np.array([4,5,6])].shape) (3, 2)
[[1 2 3 0 0 4 5 6]]
(1, 3)
(1, 3)
print(np.c_[np.array([[1,2,3]]), 0, 0, np.array([[4,5,6]])])
(1, 8)
print(np.array([[1,2,3]]).shape)
print(np.array([[4,5,6]]).shape)
print(np.c_[np.array([[1,2,3]]), 0, 0, np.array([[4,5,6]])].shap)
1. a= np.arange(6).reshape(3,2) [3 4 5]]
2. print(a) 7. print(np.ravel(a))
[[0 1] [0 1 2 3 4 5]
[2 3] 8. print(np.transpose(a))
[4 5]] [[0 2 4]
3. print(np.ndim(a)) [1 3 5]]
2 9. print(a[::-1])
4. print(np.size(a)) [[4 5]
6 [2 3]
5. print(np.shape(a)) [0 1]]
(3, 2) 10. #reverses the elements in each
6. print(np.reshape(a,(2,3))) dimension
[[0 1 2]
1. a= np.arange(6).reshape(3,2) 6. print(np.sum(a, axis=0))
2. print(a) [6, 9]
[[0 1] 7. #sum of each column
[2 3] 8. print(np.sum(a, axis=1))
[4 5]] [1, 5, 9]
9. #sum of each row
3. print(np.min(a)) 10. b = np.copy(a)
0
11. print(b)
4. print(np.max(a)) [[0 1]
5 [2 3]
5. print(np.sum(a)) [4 5]]
15 12. #makes a deep copy
Matrix Operations
1. a= np.arange(6).reshape(3,2) 5. print(a+b)
2. print(a) [[ 3 5]
[[0 1] [ 7 9]
[2 3] [11 13]]
[4 5]] 6. print(a*b)
3. b = np.arange(3,9).reshape(3,2) [[ 0 4]
4. print(b) [10 18]
[[3 4] [28 40]]
[5 6] 7. #element-wise multiplication
[7 8]]
1. a= np.arange(6).reshape(3,2) 7. print(pow(a,2))
2. print(a) [[ 0 1]
[[0 1] [ 4 9]
[2 3] [16 25]]
[4 5]] 8. #computes every element raised to
3. c = np.arange(6).reshape(2,3) power 2
4. print(c) 9. print(pow(2,a))
[[0 1 2] [[ 1 2]
[3 4 5]] [ 4 8]
5. print(np.dot(a,c)) [16 32]]
[[ 3 4 5] 10. #computes 2 raised to every
[ 9 14 19] element of matrix as power
[15 24 33]] 11. #matrix subtraction and division also
6. #Traditional matrix multiplication work
#np.where() command
a = np.arange(5,10)
print(a)
[5 6 7 8 9]
print(np.where(a < 8))
(array([0, 1, 2], dtype=int64),)
#returns indices of numbers<8
Method Description
mean() Arithmetic mean (“average”) of data.
harmonic_mean() Harmonic mean of data.
median() Median (middle value) of data.
median_low() Low median of data.
median_high() High median of data.
median_grouped() Median, or 50th percentile, of grouped data.
mode() Mode (most common value) of discrete data.
statistics.mean(data)
Returns the sample arithmetic mean of data which can be a sequence or iterator.
from statistics import mean
print(mean([1, 2, 3, 4, 4]))
2.8
print(mean([-1.0, 2.5, 3.25, 5.75]))
2.625
from fractions import Fraction as F
print(mean([F(3, 7), F(1, 21), F(5, 3), F(1, 3)]))
13/21
from decimal import Decimal as D
print(mean([D("0.5"), D("0.75"), D("0.625"), D("0.375")]))
0.5625
statistics.harmonic_mean(data)
Return the harmonic mean of data, a sequence or iterator of real-valued
numbers.
import statistics
print(statistics.harmonic_mean([2.5, 3, 10]))
3.6
statistics.median(data)
Returns the median (middle value) of numeric data.
import statistics
print(statistics.median([1, 3, 5]))
3
print( statistics.median([1, 3, 5, 7]))
4.0
statistics.median_low(data)
Return the low median of numeric data.
The low median is always a member of the data set. When the number of data points is odd, the
middle value is returned. When it is even, the smaller of the two middle values is returned.
statistics.median_high(data)
Return the high median of data.
The high median is always a member of the data set. When the number of data points is odd, the
middle value is returned. When it is even, the larger of the two middle values is returned.
statistics.median_grouped(data, interval=1)
Return the median of grouped continuous data, calculated as the 50th percentile, using
interpolation.
Tip: The mathematical formula for Grouped Median is: GMedian = L + interval * (N / 2 - CF) / F.
L = The lower limit of the median interval
interval = The interval width
N = The total number of data points
CF = The number of data points below the median interval
F = The number of data points in the median interval
statistics.mode(data)
Return the most common data point from discrete or nominal data. The mode
(when it exists) is the most typical value, and is a robust measure of central
location
import statistics
print(statistics.mode([1, 1, 2, 3, 3, 3, 3, 4]))
3
Measures of spread
Method Description
pstdev() Population standard deviation of data.
pvariance() Population variance of data.
stdev() Sample standard deviation of data.
variance() Sample variance of data.
statistics.pstdev(data, mu=None)
Return the population standard deviation (the square root of the population
variance).
If the optional second argument mu is given, it should be the mean of data.
-4.0 Output:
#Import math Library 8.0
import math -43.0
-4.0
#Return the value of the first 8.0
parameter and the sign of the second parameter -43.0
print(math.copysign(4, -1))
print(math.copysign(-8, 97.21))
print(math.copysign(-43, -76))
math.degrees()
The mmath.degrees() method converts an angle from radians to degrees.
Tip: PI (3.14..) radians are equal to 180 degrees, which means that 1
radian is equal to 57.2957795 degrees.
cmath.acos()
Output: Output:
2.718281828459045 3.141592653589793
Output:
Output: 6.283185307179586
nan
Functions
Defining a Function
def name(args):
""" function_docstring """
commands
return value
def pythagoras(x,y): 5.0
""" Computes the hypotenuse of two Help on function pythagoras in module
arguments""" __main__:
h = pow(x**2+y**2,0.5)
pythagoras(x, y)
# pow(x,0.5) is the square root Computes the hypotenuse of two
return h arguments
print(pythagoras(3,4))
help(pythagoras)
Function Arguments
You can call a function by using the following types of formal
arguments-
Required arguments
Keyword arguments
Default arguments
Variable-length arguments
Required Arguments
Required arguments are the arguments passed to a function in correct
positional order.
Here, the number of arguments in the function call should match
exactly with the function definition.
def printme( str ):
"This prints a passed string into this function"
print (str)
return
# Now you can call printme function
printme(“Rahul")
Rahul
printme()#gives error
Keyword Arguments
When you use keyword arguments in a function call, the caller identifies the
arguments by the parameter name.
def printinfo( name, age ):
"This prints a passed info into this function"
print ("Name: ", name)
print ("Age ", age)
return
# Now you can call printinfo function
printinfo( age=50, name="miki" )#Note: the order does not matter
Name: miki
Age 50
Default Arguments
A default argument is an argument that assumes a default value if a value
is not provided in the function call for that argument.
def printinfo( name, age = 35 ):
"This prints a passed info into this function"
print ("Name: ", name)
print ("Age ", age) Output:
return Name: miki
# Now you can call printinfo function Age 50
printinfo( age=50, name="miki" ) Name: miki
Age 35
printinfo( name="miki" )
Variable-length Arguments
Syntax:
def
functionname([formal_args,] *var_args_tuple ):
"function_docstring"
function_suite
return [expression]
An asterisk (*) is placed before the variable name that holds the values
of all nonkeyword variable arguments.
def printinfo( arg1, *vartuple ):
"This prints a variable passed arguments"
print ("Output is: ")
print (arg1)
Output:
for var in vartuple:
Output is:
print(var)
return
10
# Now you can call printinfo function Output is:
printinfo( 10 ) 70
printinfo( 70, 60, 50 ) 60
50
Functions
def printinfo( arg1, name, *vartuple ):
"This prints a variable passed arguments" Output is:
print ("Output is: ") 10
Miki
print (arg1) ()
print(name) Output is:
for var in vartuple: 70
Miki
print(var) 60
print(vartuple) 50
(60, 50)
return
printinfo( 10 , "Miki")
def greet(**kwargs):
if 'name' in kwargs: Hello, Alice
You are 30 years old.
print("Hello,", kwargs['name']) Profession is Engineer
if 'age' in kwargs:
print("You are", kwargs['age'], "years old.")
if 'profession' in kwargs:
print("Profession is", kwargs['profession'])
a = [1,2,3,4]
b = [17,12,11,10]
c = [-1,-4,5,9]
print(list(map(lambda x,y:x+y, a,b))) [18, 14, 14, 14]
print(list(map(lambda x,y,z:x+y+z, a,b,c))) [17, 10, 19, 23]
reduce()
In Python, reduce() is a function from the functools module that is used to apply a function
cumulatively to the elements of an iterable (like a list). It reduces the iterable to a single
value by applying the function repeatedly.
print(result)
Output: 240
reduce()
def value_change(x):
print("This is original x", id(x)) Output:
x = x+50 Value of x before calling function 10
This is main x 140703992588352
print("This is new x", id(x)) This is original x 140703992588352
print("Value of x inside function: ", x) This is new x 140703992589952
Value of x inside function: 60
x = 10
Value of x after calling function 10
print("Value of x before calling function", x)
print("This is main x", id(x))
value_change(x)
print("Value of x after calling function", x)
Pass by Value vs. Pass by Reference
#list and dictionary are mutable
def value_change(x):
print("This is original x", id(x)) Output:
Value of x before calling function [10]
x[0] = x[0]+50 This is main x 2744139053248
print("This is new x", id(x)) This is original x 2744139053248
print("Value of x inside function: ", x) This is new x 2744139053248
x = [10] Value of x inside function: [60]
Value of x after calling function [60]
print("Value of x before calling function", x)
print("This is main x", id(x))
value_change(x)
print("Value of x after calling function", x)
return statement
Can return no value
Can return single value like numbers and strings
Can return multiple value using collection types such as lists
return statement
Using Tuples (Most Common) Using Lists Using Dictionaries
def get_coordinates(): def get_numbers(): def get_student():
x = 10 a = 3; b = 5; c = 10 return {"name": "Alice", "age":
y = 20 return [a, b, c] 25, "grade": "A"}
return x, y
# Returns a tuple (10, 20) numbers = get_numbers() student = get_student()
def factorial(x):
if x == 0 or x == 1:
return 1
else:
return (x * factorial(x-1))
number = 3
print("The factorial of", number, "is", factorial(number))
n_terms = 10
try: An Exception is an Event, which occurs during the execution of the program.
It is also known as a run time error.
# Some Code....
When that error occurs, Python generates an exception during the
except: execution and that can be handled, which avoids your program to interrupt.
# Look at parameters and note the working of Program # Look at parameters and note the working of Program
divide(3, 2)
divide(3, 2)
divide(3, 0)
divide(3, 0)
Output:
Output: Yeah ! Your answer is : 1
Yeah ! Your answer is : 1 Sorry ! You are dividing by zero
Sorry ! You are dividing by zero
Exception handling with try, except, else, and finally
Output:
Yeah ! Your answer is : 1
This is always executed
Sorry ! You are dividing by zero
This is always executed
Scope of Variables
❑ All variables in a program may not be accessible at all locations in that program. This depends on
where you have declared a variable.
The scope of a variable determines the portion of the program where you can access a particular
identifier. There are two basic scopes of variables in Python −
❑ Global variables
❑ Local variables
❑ Nonlocal Variables
❑ Variables that are defined inside a function body have a local scope, and those defined outside have
a global scope.
❑ In Python, nonlocal variables are used in nested functions whose local scope is not defined. This
means that the variable can be neither in the local nor the global scope.
Local Scope
def myfunction(): def myfunc():
x = 700 x = 700
print(x) def myinnerfunc():
myfunction() print(x)
myinnerfunc()
Output: 700 myfunc()
def myfunction():
Output: 700
x = 700
print(x) The local variable can be accessed from a function
myfunction() within the function.
print(x)
Output:
700
Traceback (most recent call last):
File "<string>", line 5, in <module>
NameError: name 'x' is not defined
Global Scope
x = 300 x = 300 If you operate with the same variable name inside and outside of a
function, Python will treat them as two separate variables, one
def myfunc(): def myfunc(): available in the global scope (outside the function) and one
available in the local scope (inside the function).
print(x) x = 200
print(x)
myfunc() def myfunc(): x = 300
myfunc() global x def myfunc():
x = 300 global x
print(x) x = 200
myfunc()
print(x) myfunc()
print(x)
Output: 300 #If you use the global keyword,
print(x)
300 Output: 200 # To change the value of a global variable
the variable belongs to the global scope inside a function, refer to the variable by
300 using the global keyword.
Output: 300
Output: 200
Global Scope
# Python program to demonstrate scope of variable
print('global : ', a)
f() h()
print('global : ', a) print('global : ', a)
a =1
# Uses global because there is no local 'a'
def f(): Output:
print('Inside f() : ', a) global : 1 Output:
# Variable 'a' is redefined as a local Inside f() : 1 Inside h() : 3
def g(): global : 1 global : 3
a =2
print('Inside g() : ', a) g()
# Uses global keyword to modify global 'a' print('global : ', a)
def h():
global a
a =3
Output:
print('Inside h() : ', a)
Inside g() : 2
global : 1
Nonlocal Scope
print ("Value of a using nonlocal is : ", end ="") # Python program to demonstrate nonlocal keyword
def outer(): print ("Value of a using nonlocal is : “,end ="")
a =5 def outer():
def inner(): a =5
a = 10 def inner():
inner() nonlocal a
print (a) a = 10
inner()
print (a)
outer()
outer()
Output: Output:
Value of a without using nonlocal is : 5 Value of a using nonlocal is : 10
Nonlocal Scope
def outer_function():
count = 0 # This variable will be modified by the inner
function
Output:
def inner_function(): Inner function: count = 1
nonlocal count # Refers to the 'count' variable from Outer function: count = 1
outer_function
count += 1 # Modify the count
print(f"Inner function: count = {count}")
outer_function()
Nonlocal Scope
def example():
ERROR!
def inner(): Traceback (most recent call last):
File "<main.py>", line 3
nonlocal x SyntaxError: no binding for nonlocal 'x' found
x = 10
inner() To use nonlocal, the variable must already
exist in the enclosing function.
Nonlocal Scope
def outer_function():
x = 10 # Variable in outer_function scope
def middle_function():
x = 20 # Variable in middle_function scope Output:
Inner function: x = 21
def inner_function(): Middle function: x = 21
nonlocal x # Refers to the 'x' in middle_function, NOT outer_function Outer function: x = 10
x += 1 # Modifying the 'x' in middle_function
print(f"Inner function: x = {x}")
inner_function() ▪ When you use nonlocal inside inner_function(), it looks for the
print(f"Middle function: x = {x}") nearest variable named x in the immediate enclosing
middle_function() scope, which is middle_function().
print(f"Outer function: x = {x}")
▪ It cannot modify the x in outer_function() directly because
outer_function() that’s two levels up.
Scope of Variables
Output:
total = 0 # This is global variable. 0
x =0 ERROR!
# Function definition is here Traceback (most recent call last):
File "<main.py>", line 12, in <module>
def sum( arg1, arg2 ): File "<main.py>", line 6, in sum
print(x) UnboundLocalError: cannot access local variable 'total'
print(total) where it is not associated with a value
# Add both the parameters and return them." Key Concept: Python’s Local vs. Global Variable
Handling
total = arg1 + arg2; # Here total is local
❑ When you assign a value to a variable inside a function,
variable. Python treats it as a local variable by default.
print ("Inside the function local total : ", total) ❑ If you need to access a global variable inside a function,
return total you need to explicitly use the global keyword.
# Now you can call sum function ❑ Without the global keyword, Python raises the UnboundLocalError
because it thinks you're referencing a local variable before
sum( 10, 20 ) assigning it.
Scope of Variables
# Global variables
total = 0 # Global variable 'total'
x=0 # Global variable 'x'
# Function definition Output:
def sum(arg1, arg2): 0
0
global total # Tell Python that we want to use the global 'total'
Inside the function local total: 30
print(x) # Access global 'x'
Outside the function global total: 30
print(total) # Access global 'total'
for i in range(length-1):
minIndex = i
return array
array = [50,18,9,5,76]