01 Python I 08-02-24
01 Python I 08-02-24
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.
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
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
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")
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
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')
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
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']
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
# 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))
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]
#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
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
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.
# 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
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
return array
array = [50,18,9,5,76]