0% found this document useful (0 votes)
6 views

01 Python I 08-02-24

Uploaded by

vedangtripathi45
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

01 Python I 08-02-24

Uploaded by

vedangtripathi45
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 228

INTRODUCTION TO

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
 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.

 Examples of valid identifiers:


• Var1, _var1, _1_var, var_1

 Examples of invalid identifiers


• !var1, 1var, 1_var, var#1
Lines and Indentations
 Python does not use braces({}) to indicate blocks of code for class and
function definitions or flow control.
 Blocks of code are denoted by line indentation, which is rigidly
enforced.
if True:
print ("True")
else:
print ("False")
print("Hello")
 The following gives error
if True:
print ("True")
else:
print ("False")
print("Hello")
Comments
# First comment
print ("Hello, Python!") # second comment
Variable Declaration
# declaration/creation of variables happen automatically
counter = 100 # An integer assignment
miles = 1000.0 # A floating point
name = "John" # A string
print(counter)
print(miles)
print(name)
Data Types
Standard Data Types
 Numbers
 String
 List
 Tuple
 Dictionary
 A complex number consists of an ordered pair of real floating-point
numbers denoted by x + yj, where x and y are real numbers and j is
the imaginary unit.
Strings
 Python accepts single ('), double (") and triple (''' or """) quotes to denote
string literals, as long as the same type of quote starts and ends the string.
word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""
print(word)
print(sentence)
print(paragraph)
print('a' + 'd')
ad
print("hello"+" world")
hello world
Lists
 A list contains items separated by commas and enclosed within square
brackets ([]).
 Similar to arrays in C. However, items belonging to a list can be of
different data type.

mylist = [0, 3, 2, 'hi']


print(mylist)
[0, 3, 2, 'hi']
newlist = [3, 2, [5, 4, 3], [2, 3, 2]]
print(newlist)
[3, 2, [5, 4, 3], [2, 3, 2]]
#list within list

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]]

alist = mylist[:] #does deep copy only to one level


alist[0]=5
print(mylist)#OK
[4, 2, [5, 4, 3], [2, 3, 2]]
print(alist)
[5, 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

mytuple = (0, 3, 2, 'h')


tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')
print (tuple) # Prints complete tuple
('abcd', 786, 2.23, 'john', 70.2)
print (tuple[0]) # Prints first element of the tuple
abcd
print (tuple[1:3]) # Prints elements starting from 2nd till 3rd
(786, 2.23)
print (tuple[2:]) # Prints elements starting from 3rd element
(2.23, 'john', 70.2)
print (tinytuple * 2) # Prints tuple two times
(123, 'john', 123, 'john')
print (tuple + tinytuple) # Prints concatenated tuple
('abcd', 786, 2.23, 'john', 70.2, 123, 'john')
Tuples are read-only
 The following gives error while running the code
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tuple[2] = 1000 # Invalid syntax with tuple
#The next sentence gives error while running the code
list[2] = 1000 # Valid syntax with list
Dictionaries
 Kind of hash-table type
 Consist of key-value pairs
 Dictionaries are enclosed in curly braces
 You assign a key to each entry that you can use to access it
months = {'Jan': 31, 'Feb': 28, 'Mar': 31}
print(months['Jan'])
31
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print (dict['one']) # Prints value for 'one' key
This is one
This is oneprint (dict[2]) # Prints value for 2 key
This is two
print (tinydict) # Prints complete dictionary
{'name': 'john', 'code': 6734, 'dept': 'sales'}
print (tinydict.keys()) # Prints all the keys
dict_keys([‘name’, ‘code’, 'dept'])
print (tinydict.values()) # Prints all the values
dict_values(['john’, 6734, ‘sales'])
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.
print(int(2.7)) ord() : This function is used to convert a character to
2 integer.
hex() : This function is to convert integer to hexadecimal
print(float(2)) string.
oct() : This function is to convert integer to octal string.
2.0
s = '4’
print(complex(2,4)) c = ord(s)
print (c)
(2+4j) Output: 52

print(str(44+55)+str(30/9)) c = hex(56)
print (c)
993.3333333333333335 Output: 0x38

c = oct(56)
print (c)
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

Sign-magnitude: -(2^(n-1)) -1 to +(2^(n-1)) -1

One’s complement: -(2^(n-1)) -1 to +(2^(n-1)) -1


Can we write one’s complement of a negative
number directly?
Ans: NO
E.g., -5, for -5, first write signed magnitude of +5
(0101), then do one’s complement. (1010).
Therefore -5 in one’s complement is 1010.

Reverse: suppose we have to read 1010 (represented in


one’s complement), first do one’s complement (0101),
take magnitude part (5) and reverse its sign (-5).
Signed Number Representation
Two’s complement: -(2^(n-1)) to +(2^(n-1))-1
E.g., -6, for -6, first write signed magnitude of +6
(0110), and do 2’s complement (1010).

Reverse: suppose we have to read 1010 (represented in


2’s complement), first do 2’s complement (0110), take
magnitude part (6) and reverse its sign (-6).

How to read directly?


1010 = -1*2^3 + 0*2^2 + 1*2^1 + 0*2^0 = -6
How to convert into 2’s complement directly?
-13 = -16 + 3 = 10011
1. a = 60 # 60 = 0011 1100 c,':',bin(c))
2. b = 13 # 13 = 0000 1101 result of EXOR is 49 : 0b110001
3. print 11. c = ~a; # -61 = 1100 0011
('a=',a,':',bin(a),'b=',b,':',bin(b)) 12. print ("result of COMPLEMENT is ",
a= 60 : 0b111100 b= 13 : 0b1101 c,':',bin(c))
4. c=0 result of COMPLEMENT is -61 : -0b111101
5. c = a & b; # 12 = 0000 1100 13. c = a << 2; # 240 = 1111 0000

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

print(not(x>5) and (y<3))


True
Membership Operators
 Test for membership in a sequence, such as strings, lists, or tuples.
1. a = 10 10. else:

2. b = 20 11. print ("Line 2 - b is available in


3. list = [1, 2, 3, 4, 5 ] the given list")
4. if ( a in list ): Line 2 - b is not available in the given list
12. c=b/a
5. print ("Line 1 - a is available in
the given list") 13. if ( c in list ):

6. else: 14. print ("Line 3 - a is available in


7. print ("Line 1 - a is not the given list")
available in the given list") 15. else:

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")
Line 3 - a is available in the given list
9. print ("Line 2 - b is not
available in the given list")
Identity Operators
 Compare the memory locations of two objects.
Python id() Function

 The id() function returns a unique id for the specified object.


 All objects in Python has its own unique id.
 The id is assigned to the object when it is created.
 The id is the object's memory address, and will be different for each time you run the
program.
(except for some object that has a constant unique id, like integers from -5 to 256)
1. a = 20 10. else:
2. b = 20 11. print ("Line 3 - a and b do not
3. print ('Line 1','a=',a,':',id(a), have same identity")
'b=',b,':',id(b)) Line 3 - a and b have same identity
Line 1 a= 20 : 497419344 b= 20 : 12. b = 30
497419344 13. print ('Line 4','a=',a,':',id(a),
4. if ( a is b ): 'b=',b,':',id(b))
5. print ("Line 2 - a and b have Line 4 a= 20 : 497419344 b= 30 :
same identity") 497419664
6. else: 14. if ( a is not b ):
7. print ("Line 2 - a and b do not 15. print ("Line 5 - a and b do not
have same identity") have same identity")
Line 2 - a and b have same identity 16. else:
8. if ( id(a) == id(b) ): 17. print ("Line 5 - a and b have
9. print ("Line 3 - a and b have same identity")
same identity") Line 5 - a and b do not have same identity
Python Operator Precedence
1. a = 20 9. print ("Value of ((a + b) * c) / d
2. b = 10 is ", e)
Value of (a + b) * (c / d) is 90.0
3. c = 15
4. d=5 10. e = (a + b) * (c / d) # (30) *
(15/5)
5. print ("a:%d b:%d c:%d d:%d"
% (a,b,c,d )) 11. print ("Value of (a + b) * (c / d)
a:20 b:10 c:15 d:5
is ", e)
Value of (a + b) * (c / d) is 90.0
6. e = (a + b) * c / d #( 30 * 15 )
/5 12. e = a + (b * c) / d # 20 +
(150/5)
7. print ("Value of (a + b) * c / d is
", e) 13. print ("Value of a + (b * c) / d is
Value of (a + b) * c / d is 90.0
", e)
Value of a + (b * c) / d is 50.0
8. e = ((a + b) * c) / d # (30 * 15 )
/5
Decision Making
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
Discount 30.0
print ("Discount",discount)
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
Discount 300.0
print ("Discount",discount)
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
Discount 900.0
print ("Discount",discount)
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)
Reading Input
 The input([prompt]) function reads one line from standard input
and returns it as a string.

str = input("Enter your input: ");


print("Received input is : ", str)
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)
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
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().
Now this list can be iterated using the for statement.
print(list(range(5)))
[0, 1, 2, 3, 4]
for loop
for var in list(range(5)): Output:
print (var) 0
1
2
3
4
for loop
1. for letter in 'Python': # traversal of Output:
Current Letter : P
a string sequence
Current Letter : y
2. print ('Current Letter :', letter) Current Letter : t
3. print()#prints newline character Current Letter : h
Current Letter : o
4. fruits = ['banana', 'apple', 'mango'] Current Letter : n
5. for fruit in fruits: # traversal of List
sequence Current fruit : banana
Current fruit : apple
6. print ('Current fruit :', fruit) Current fruit : mango
7. print ("Good bye!") Good bye!
for loop iteration by sequence index
for letter in 'Python': # traversal of a string sequence
print ('Current Letter :', letter) Output
print()#prints newline character Current Letter : P
Current Letter : y
fruits = ['banana', 'apple', 'mango'] Current Letter : t
for fruit in fruits: # traversal of List sequence Current Letter : h
Current Letter : o
print ('Current fruit :', fruit) Current Letter : n
Current fruit : banana
print ("Good bye!") Current fruit : apple
Current fruit : mango
Good bye!
Else statement with Loops
 If the else statement is used with a for loop, the else block is executed
only if for loops terminates normally (and not by encountering break
statement).
 If the else statement is used with a while loop, the else statement is
executed when the condition becomes false.
numbers=[11,33,55,39,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')

the list does not contain 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’)
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’)

the list contains an even number


Loop Control Statements
Loop Control Statements
break continue
break statement
1. for letter in 'Python': # First Example Output:
2. if letter == 'h':
Current Letter : P
3. break
4. print ('Current Letter :', letter) Current Letter : y
Current Letter : t
5. var = 10 # Second Example
Current variable value : 10
6. while var > 0:
7. print ('Current variable value :', var) Current variable value : 9
8. var = var -1 Current variable value : 8
9. if var == 5: Current variable value : 7
10. break
Current variable value : 6
11. print ("Good bye!") Good bye!
Output:
Current Letter : P
continue statement Current Letter : y
Current Letter : t
1. for letter in 'Python': # First Example Current Letter : o
2. if letter == 'h': Current Letter : n
3. continue Current variable value : 9
4. print ('Current Letter :', letter)
Current variable value : 8
Current variable value : 7
5. var = 10 # Second Example
Current variable value : 6
6. while var > 0:
7. var = var -1 Current variable value : 4
8. if var == 5: Current variable value : 3
9. continue Current variable value : 2
10. print ('Current variable value :', var) Current variable value : 1
Current variable value : 0
11. print ("Good bye!") Good bye!
Working with Lists
Lists
 A list contains items separated by commas and enclosed within square
brackets ([]).
 Similar to arrays in C. However, items belonging to a list can be of
different data type.

mylist = [0, 3, 2, 'hi']


print(mylist)
[0, 3, 2, 'hi']
Accessing Values in Lists
list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5, 6, 7 ]
print ("list1[0]: ", list1[0])#through indexing
list1[0]: physics

print ("list2[1:5]: ", list2[1:5])#using slicing


list2[1:5]: [2, 3, 4, 5]
Lists – updating single element
list = ['physics', 'chemistry', 1997, 2000]
print ("Value available at index 2 : ", list[2])
Value available at index 2 : 1997

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

list2=list(range(5)) #creates list of numbers between 0-4


print (len(list2))
5
List max() Method
 max() method returns the elements from the list with maximum value.
 Syntax
max(list)
 Parameters
 list - This is a list from which max valued element are to be returned.
 Return Value
This method returns the elements from the list with maximum value.
list1, list2 = ['C++','Java', 'Python'],
[456, 700, 200]
print ("Max value element : ", max(list1))
Max value element : Python

print ("Max value element : ", max(list2))


Max value element : 700

Note: By default, it will return the string with the maximum


lexicographic value.
 Maximum of 3 string variables according to the length:
 passing a key function in the max() method.

list1 = ['C++','Java', 'Python’]


max_val = max(list1, key = len)
print("Max value element based on length of string : ", max_val)
Output: Max value element based on length of string : Python
List min() Method
 min() returns the elements from the list with minimum value.
 Syntax
min(list)
 Parameters
 list - This is a list from which min valued element is to be returned.
 Return Value:
This method returns the elements from the list with minimum value.
list1, list2 = ['C++','Java', 'Python'],
[456, 700, 200]
print ("min value element : ", min(list1))
min value element : C++

print ("min value element : ", min(list2))


min value element : 200
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

print ("Count for zara : ",


aList.count('zara'))
Count for zara : 1
List extend() Method
 extend() method appends the contents of seq to list.
 Syntax
list.extend(seq)
 Parameters
 seq - This is the list of elements
 Return Value
This method does not return any value but adds the content to an existing list.
list1 = ['physics', 'chemistry', 'maths']
list2=list(range(5)) #creates list of
numbers between 0-4
list1.extend( list2)
print ('Extended List :',list1)

Extended List : ['physics', 'chemistry', 'maths', 0, 1, 2, 3, 4]


List index() Method
 index() method returns the lowest index in list that obj appears.
 Syntax
index(obj)
 Parameters
 obj - This is the object to be find out.
 Return Value
This method returns index of the found object otherwise raises an exception
indicating that the value is not found.
list1 = ['physics', 'chemistry', 'maths']
print ('Index of chemistry',
list1.index('chemistry'))
Index of chemistry 1

print ('Index of C#', list1.index('C#'))


Traceback (most recent call last):
print ('Index of C#', list1.index('C#'))
ValueError: 'C#' is not in list
List insert() Method
 insert() method inserts object obj into list at offset index.
 Syntax
insert(index, obj)
 Parameters
 index - This is the Index where the object obj need to be inserted.
 obj - This is the Object to be inserted into the given list.

 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']

print ("list now : ", list1)


list1.remove('maths')
print ("list now : ", list1)
list now : ['physics', 'chemistry']
List reverse() Method
 reverse() method reverses objects of list in place.
 Syntax
reverse()
 Parameters
NA
 Return Value
This method does not return any value but reverse the given object from the
list.
list1 = ['physics', 'Biology', 'chemistry',
'maths']
list1.reverse()
print ("list now : ", list1)
list now : ['maths', 'chemistry', 'Biology', 'physics']
List sort() Method
 sort() method sorts objects of list, use compare function if given.
 Syntax
sort([func])
 Parameters
NA
 Return Value
This method does not return any value but reverses the given object from the
list.
list1 = ['physics', 'Biology', 'chemistry', 'maths']
list1.sort()
print ("list now : ", list1)
list now : ['Biology', 'chemistry', 'maths', 'physics’]
list1 = ['physics', 'Biology', 'chemistry', 'maths']
list1.sort()
print ("list now : ", list1)
list now : ['Biology', 'chemistry', 'maths', 'physics’]

 # A function that returns the length of the value:


def myFunc(e):
return len(e)
cars = ['Ford', 'Mitsubishi', 'BMW', 'VW’]
cars.sort(key=myFunc)
print(cars)
Output: ['VW', 'BMW', 'Ford', 'Mitsubishi']
Importing Modules
Writing and Importing Code
 Python is a scripting language
 everything can be run interactively from the command line
 .py extension for source file; complied into .pyc file when first loaded
 Any set of commands or functions is known as a module in Python
 To load it, you use the import command
 If you import a script file then Python will run it immediately, but if it is a set
of functions then it will not run anything.
def print_func( par ):
print("Hello : ", par)
return
The above can be saved as “support.py”
import support
support.print_func("Zara")
Hello : Zara
To add a folder in the list of folders to search while importing a module
import sys
sys.path.append("./otherDir")
import support
support.print_func("Zara")
Hello : Zara
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

 Need to import random module


choice()
 choice() method returns a random item from a list, tuple, or string.
 Syntax
random.choice(seq )
 Parameters
 seq - This could be a list, tuple, or string...
 Return Value
This method returns a random item.
import random

outcomes = { 'heads':0,
import random
'tails':0,
}
sides = list(outcomes.keys()) x = "WELCOME"

for i in range(10000): print(random.choice(x))


outcomes[ random.choice(sides) ] += 1

print('Heads:', outcomes['heads']) Output: Any letter


print('Tails:', outcomes['tails']) written in word
Heads: 5033 “WELCOME”
Tails: 4967
randrange()
 randrange() method returns a randomly selected element from
range(start, stop, step).
 Syntax
randrange ([start,] stop [,step])
 Parameters
 start - Start point of the range. This would be included in the range. Default
is 0.
 stop - Stop point of the range. This would be excluded from the range.
 step - Value with which number is incremented. Default is 1.

 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

# randomly select a number between 0-99


print ("randrange(100) : ",
random.randrange(100))
randrange(100) : 97
random()
 random() method returns a random floating point number in the range
[0.0, 1.0].
 Syntax
random( )
 Parameters
NA
 Return Value
This method returns a random float r, such that 0.0 <= r <= 1.0
import random
# First random number
print ("random() : ", random.random())
random() : 0.5476053663383964

# Second random number


print ("random() : ", random.random())
random() : 0.1308558535179697
seed() method
 Initializes the basic random number generator.
 Call this function before calling any other random module function.
 Syntax
random.seed(a, version)
# random module is imported # random module is imported
import random import random
for i in range(5): for i in range(5):

# Any number can be used in place of '0'. # Any number can be used in place of '0'.
random.seed(0) random.seed()

# Generated random number will be between 1 to 1000. # Generated random number will be between 1 to 1000.
print(random.randint(1, 1000)) print(random.randint(1, 1000))
# random module is imported # random module is imported
import random import random
for i in range(5): for i in range(5):

# Any number can be used in place of '0'. # Any number can be used in place of '0'.
random.seed(0) random.seed()

# Generated random number will be between 1 to 1000. # Generated random number will be between 1 to 1000.
print(random.randint(1, 1000)) print(random.randint(1, 1000))

Same Random Number Different Random Numbers


Always
import random
random.seed()
print ("random number with default seed",
random.random())
random number with default seed 0.3844734828760715

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 ("Random Float uniform(7, 14) : ",


random.uniform(7, 14))
Random Float uniform(7, 14) : 12.678404498161704
NumPy
NUMPY
 NumPy is the fundamental package for scientific computing with
Python
 Among other things, it provides a powerful n-dimensional array
import numpy
# of simply
import numpy as np
#np acts as a short name for numpy
Arrays
import numpy as np
myarray = np.array([4,3,2])
mybigarray = np.array([[3, 2, 4], [3, 3, 2], [4, 5, 2]])
print(myarray)
[4 3 2]

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.]]

#similarly, we have np.zeros()


print(np.eye(3))
[[ 1. 0. 0.]
[ 0. 1. 0.]
[ 0. 0. 1.]]
#produces 2D square identity matrix of size 3

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]
#performs row concatenation
print(np.r_[1:4,0,4])
[1 2 3 0 4]
print(np.c_[np.array([1,2,3]), np.array([4,5,6])])
[[1 4]
[2 5]
[3 6]]

print(np.c_[np.array([[1,2,3]]), 0, 0, np.array([[4,5,6]])])
[[1 2 3 0 0 4 5 6]]
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

print(a[np.where(a < 8)])


[5 6 7]
#returns values <8
a = np.arange(4,10).reshape(2,3)
print(a)
[[4 5 6]
[7 8 9]]
np.where(a > 5)
(array([0, 1, 1, 1], dtype=int64), array([2, 0, 1, 2], dtype=int64))
#in case of 2D array, it returns an array of row indices and an array
of col indices
print(a[np.where(a > 5)])
[6, 7, 8, 9]
Statistics Module
import statistics
Averages and measures of central location

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.

from statistics import pstdev


print(pstdev([1.5, 2.5, 2.5, 2.75, 3.25, 4.75]))
0.986893273527251
 statistics.pvariance(data, mu=None)
 Return the population variance of data, a non-empty iterable of real-
valued numbers.
 If the optional second argument mu is given, it should be the mean of data.

from statistics import pvariance


print(pvariance([1.5, 2.5, 2.5, 2.75, 3.25, 4.75]))
0.9739583333333334
 Decimals and Fractions are supported:

from statistics import pvariance


from decimal import Decimal as D
from fractions import Fraction as F
print( pvariance([D("27.5"), D("30.25"), D("30.25"), D("34.5"),
D("41.75")]))
24.815

print( pvariance([F(1, 4), F(5, 4), F(1, 2)]))


13/72
 statistics.stdev(data, xbar=None)
 Return the sample standard deviation (the square root of the sample
variance).
 If the optional second argument xbar is given, it should be the mean of
data. If it is missing or None (the default), the mean is automatically
calculated.
 statistics.variance(data, xbar=None)
 Return the sample variance of data, an iterable of at least two real-valued
numbers.
 If the optional second argument xbar is given, it should be the mean of
data. If it is missing or None (the default), the mean is automatically
calculated.
Python math Module
import math
Python has a built-in module that you can use for mathematical tasks.
The math module has a set of methods and constants.
Math Constants
Python cmath Module
cMath Constants
math.acos()
 The math.acos() method returns the arc cosine value of a number.
 Note: The parameter passed in math.acos() must lie between -1 to 1.

 # Import math Library


import math Output:
# Return the arc cosine of numbers
print(math.acos(0.55)) 0.9884320889261531
print(math.acos(-0.55)) 2.15316056466364
print(math.acos(0)) 1.5707963267948966
print(math.acos(1)) 0.0
print(math.acos(-1)) 3.141592653589793
math.acosh()
 The math.acosh() method returns the inverse hyperbolic cosine of a number.
Note: The parameter passed in acosh() must be greater than or equal to 1.

# Import math Library


import math Output:

# Return the inverse hyperbolic 2.6339157938496336


cosine of different numbers 4.718419142372879
print (math.acosh(7)) 1.5447131178707394
print (math.acosh(56)) 0.0
print (math.acosh(2.45))
print (math.acosh(1))
math.ceil()
 The math.ceil() method rounds a number UP to the nearest integer, if necessary,
and returns the result.

# Import math library


import math Output:

# Round a number upward 2


to its nearest integer 6
print(math.ceil(1.4))
print(math.ceil(5.3)) -5
print(math.ceil(-5.3)) 23
print(math.ceil(22.6)) 10
print(math.ceil(10.0))
math.copysign()
 The math.copysign() method returns a float consisting of the value of
the first parameter and the sign(+/-) of the second parameter.

-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.

 # Import math Library


import math Output:
# Convert from radians to degrees: 509.9324376664327
print (math.degrees(8.90))
-1145.9155902616465
print (math.degrees(-20))
print (math.degrees(1)) 57.29577951308232
print (math.degrees(90)) 5156.620156177409
179.9087476710785
 print (math.degrees(3.14))
math.dist()
 The math.dist() method returns the Euclidean distance between two points (p and q), where p and q
are the coordinates of that point.
 Note: The two points (p and q) must be of the same dimensions.

 # Import math Library


import math
p = [3]
q = [1]
# Calculate Euclidean distance Output:
print (math.dist(p, q))
p = [3, 3] 2.0
q = [6, 12] 9.486832980505138
# Calculate Euclidean distance
print (math.dist(p, q))
math.exp()
 The math.exp() method returns E raised to the power of x (Ex). 'E' is the
base of the natural system of logarithms (approximately 2.718282)
and x is the number passed to it.

 #Import math Library


import math Output:

#find the exponential of the specified value 1.6948892444103338e+28


print(math.exp(65)) 0.0010179138409954387
print(math.exp(-6.89))
math.factorial()
 The math.factorial() method returns the factorial of a number. Note:
This method only accepts positive integers.

 #Import math Library


import math Output:

#Return factorial of a number 362880


720
print(math.factorial(9)) 479001600
print(math.factorial(6))
print(math.factorial(12))
math.floor()
 The math.floor() method rounds a number DOWN to the nearest
integer, if necessary, and returns the result.
 # Import math library
import math

# Round numbers down to the


Output:
 nearest integer
print(math.floor(0.6)) 0
print(math.floor(1.4)) 1
print(math.floor(5.3)) 5
print(math.floor(-5.3)) -6
print(math.floor(22.6)) 22
print(math.floor(10.0)) 10
math.gcd()
 The math.gcd() method returns the greatest common divisor of the two integers int1
and int2.
 GCD is the largest common divisor that divides the numbers without a remainder.
 GCD is also known as the highest common factor (HCF). Tip: gcd(0,0) returns 0.
 #Import math Library
import math
Output:
#find the the greatest common divisor of the two integers 3
print (math.gcd(3, 6))
print (math.gcd(6, 12))
6
print (math.gcd(12, 36)) 12
print (math.gcd(-12, -36)) 12
print (math.gcd(5, 12)) 1
print (math.gcd(10, 0))
print (math.gcd(0, 34)) 10
print (math.gcd(0, 0)) 34
0
math.log()
 The math.log() method returns the natural logarithm of a number, or
the logarithm of number to base.
 math.log(x, base)
math.log()
# Import math Library
import math

# Return the natural logarithm


of different numbers
Output:
print(math.log(2.7183))
print(math.log(2))
1.0000066849139877
print(math.log(1))
0.6931471805599453
print(math.log(10)) 0.0
print(math.log(10,10)) 2.302585092994046
1.0
math.pow()
 The math.pow() method returns the value of x raised to power y.
 If x is negative and y is not an integer, it returns a ValueError.
 This method converts both arguments into a float.
 Tip: If we use math.pow(1.0,x) or math.pow(x,0.0), it will always returns 1.0.

# Import math Library


import math Output:

#Return the value of 9 raised to the power of 3 729.0


print(math.pow(9, 3))
Math Constants: math.e, math.inf

 The math.e constant returns the Eular's number: 2.718281828459045.


# Import math Library
import math Output: 2.718281828459045
# Print the value of E
print (math.e)

 The math.inf constant returns a floating-point positive infinity.


# Import math Library
import math

# Print the positive infinity Output:


print (math.inf) inf
-inf
# Print the negative infinity
print (-math.inf)
math.nan, math.pi, math.tau
 The math.nan constant returns a floating-point nan (Not a Number) value. This value is not a legal number.
 The math.pi constant returns the value of PI: 3.141592653589793.
 The math.tau constant returns the value of tau, which is 6.283185307179586. It is defined as the ratio of the circumference to
the radius of a circle. Tau is a circle constant and the value is equivalent to 2π.

# Import math Library


import math # Import math Library
import math
# Print the value of nan
print (math.nan) # Print the value of pi
Output: nan print (math.pi)
Output: 3.141592653589793

# Import math Library


import math
# Print the value of tau
print (math.tau)
Output: 6.283185307179586
cMath Methods

 cmath.acos()

#import cmath for complex number operations


import cmath
Output: (
#find the arc cosine of a complex number 1.0001435424737972-1.9833870299165355j)
print (cmath.acos(2+3j))
cmath.log10()
 The cmath.log10() method returns the base-10 logarithm of a complex number. There
is one branch cut, from 0 along the negative real axis to -∞, continuous from above.

 #Import cmath Library


import cmath
Output:
#print base-10 log value of complex numbers
print (cmath.log10(2+ 3j)) (0.5569716761534184+0.42682189085546657j)
print (cmath.log10(1+ 2j))
(0.3494850021680094+0.480828578784234j)
Python cmath Constant: cmath.e, cmath.nan,
cmath.pi, cmath.tau
# Import cmath Library #Import cmath Library
import cmath import cmath
# Print the value of Euler e
print (cmath.e) # Print the value of pi
print (cmath.pi)

Output: Output:
2.718281828459045 3.141592653589793

#Import cmath Library


#Import cmath Library import cmath
import cmath
# Print the value of nan #Print the value of tau
print (cmath.nan) print (cmath.tau)

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
The Anonymous Functions
 These functions are called anonymous because they are not declared in the
standard manner by using the def keyword. You can use the lambda
keyword to create small anonymous functions.
 Lambda forms can take any number of arguments but return just one value
in the form of an expression.
 They cannot contain commands or multiple expressions.
 An anonymous function cannot be a direct call to print because lambda
requires an expression.
 Lambda functions have their own local namespace and cannot access
variables other than those in their parameter list and those in the global
namespace.
lambda argument
 Sytax
lambda argument_list: expression
sum = lambda x, y : x + y
print(sum(3,4)) 7
map command
 map command calls a function once for every argument in the list
 Syntax: map(function,list)
def fahrenheit(T):
return ((float(9)/5)*T + 32)
temperatures = (36.5, 37, 37.5, 38, 39) 97.7
F = map(fahrenheit, temperatures) 98.60000000000001
for num in F: 99.5
print(num) 100.4
102.2
map with lambda
temperatures = (36.5, 37, 37.5, 38, 39)
F = list(map(lambda x: (float(9)/5)*x + 32, temperatures))
print(F) [97.7, 98.60000000000001, 99.5, 100.4, 102.2]

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]
Global vs. Local variables
total = 0 # This is global variable.
# Function definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2; # Here total is local variable.
print ("Inside the function local total : ", total)
return total
# Now you can call sum function
sum( 10, 20 )
print ("Outside the function global total : ", total )
Inside the function local total : 30
Outside the function global total : 0
Pass by Value vs. Pass by Reference
 Primitive types like numbers, strings, tuples are passed by values
 Collection types like lists and dictionaries are passed by references
#int and strings are immutable (can not change
value, if we will #change the value then a new
refrence will be created)
def value_change(x):
x = x+50
print("Value of x inside function: ", x)
x = 10
print("Value of x before calling function", x)
value_change(x)
print("Value of x after calling function", x)
Output:
Value of x before calling function 10
Value of x inside function: 60
Value of x after calling function 10
Pass by Value vs. Pass by Reference
#int and strings are immutable (can not change value, if we will #change the
value then a new reference will be created)

def value_change(x):
print("This is original x", id(x)) Output:
x = x+50 Value of x before calling function 10
print("This is new x", id(x)) This is main x 140703992588352
This is original x 140703992588352
print("Value of x inside function: ", x)
This is new x 140703992589952
x = 10 Value of x inside function: 60
print("Value of x before calling function", x) Value of x after calling function 10
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:
x[0] = x[0]+50 Value of x before calling function [10]
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]
print("Value of x before calling function", x) Value of x after calling function [60]
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
Error Control
Exception handling with try, except, else, and
finally
try: An Exception is an Event, which occurs during the execution of the
# Some Code.... program. It is also known as a run time error.

When that error occurs, Python generates an exception during the


except: execution and that can be handled, which avoids your program to
interrupt.
# optional block
# Handling of exception (if required) a=5
Try: This block will test the excepted error to b=0
occur print(a/b)
else: Except: Here you can handle the error
Else: If there is no exception then this block will
# execute if no exception be executed Output:
Finally: Finally block always gets executed
either exception is generated or not
Traceback (most recent call last):
finally: File "<string>", line 3, in <module>
ZeroDivisionError: division by zero
# Some code .....(always executed)
Exception handling with try, except, else, and
finally
# import module sys to get the type of exception
import sys Output:
randomList = ['a', 0, 2]
for entry in randomList: The entry is a
try: Oops! <class 'ValueError'> occurred.
print("The entry is", entry) Next entry.
r = 1/int(entry)
break The entry is 0
except: Oops! <class 'ZeroDivisionError'> occured.
print("Oops!", sys.exc_info()[0], "occurred.") Next entry.
print("Next entry.“)
print()
The entry is 2
print("The reciprocal of", entry, "is", r)
The reciprocal of 2 is 0.5
Catching Specific Exceptions in Python
 In the above example, we did not mention any specific exception in the except clause.
 This is not a good programming practice as it will catch all exceptions and handle every case in the same way. We can specify which
exceptions an except clause should catch.
 A try clause can have any number of except clauses to handle different exceptions, however, only one will be executed in case an
exception occurs.
try:
a = 1/0
Output:
#b = 1/int('c’)
TypeError or, ZeroDivisionError
except ValueError:
# handle ValueError exception
print("ValueError")
except (TypeError, ZeroDivisionError):
# handle multiple exceptions # TypeError and ZeroDivisionError
print("TypeError or, ZeroDivisionError")
except:
# handle all other exceptions
pass
Exception handling with try, except, else, and
finally
def divide(x, y): def divide(x, y):
try: try:
# Floor Division : Gives only Fractional # Floor Division : Gives only Fractional
# Part as Answer
# Part as Answer
result = x // y
result = x // y except ZeroDivisionError:
print("Yeah ! Your answer is :", result) print("Sorry ! You are dividing by zero ")
except ZeroDivisionError: else:
print("Sorry ! You are dividing by zero ") print("Yeah ! Your answer is :", result)

# 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

def divide(x, y):


try: The try statement in Python can have an optional
# Floor Division : Gives only Fractional
# Part as Answer finally clause. This clause is executed no matter
result = x // y what, and is generally used to release external
except ZeroDivisionError:
print("Sorry ! You are dividing by zero ") resources.
else:
print("Yeah ! Your answer is :", result)
finally:
# this block is always executed try:
# regardless of exception generation. f = open("test.txt",encoding = 'utf-8')
print('This is always executed')
# perform file operations
# Look at parameters and note the working of Program
finally:
divide(3, 2) f.close()
divide(3, 0)

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

A variable created outside of a function is global and can be used by anyone

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
 It also has functions for generating popular distributions like beta,
exponential, gamma, Gaussian (normal), Pareto and Weibull
distribution.
 For details see https://docs.python.org/3.6/library/random.html
Selection sort
1. selection_sort(array)
2. repeat (0, length - 1) times
3. set the first unsorted element as the minimum
4. for each of the unsorted elements
5. if element < currentMinimum
6. set element as new minimum
7. swap minimum with first unsorted position
8. end selection_sort
def selection_sort(array):
length = len(array)

for i in range(length-1):
minIndex = i

for j in range(i+1, length):


if array[j]<array[minIndex]:
minIndex = j

array[i], array[minIndex] = array[minIndex], array[i]

return array
array = [50,18,9,5,76]

print("The sorted array is: ", selection_sort(array))


Insertion sort
 Insertion Sort Algorithm
 To sort an array of size N in ascending order:
• Iterate from arr[1] to arr[N] over the array.
• Compare the current element (key) to its predecessor.
• If the key element is smaller than its predecessor, compare it to the
elements before. Move the greater elements one position up to make
space for the swapped element.

You might also like