PYTHON - I
Fall 2025 CS011903 Computing With Python
Credits
B1: Python for Everybody, Exploring Data Using Python
3
Dr. Charles R. Severance
https://www.py4e.com/
https://www.tutorialspoint.com/python3/
https://docs.python.org
Assignment
Reading
B1: Ch1-12
Problem:
B1: Ch1-12
COMPUTER HARDWARE ARCHITECTURE
Why do we need a programming
Language?
We understand English/Hindi/Malayalam/Telugu
Computer understands Python/C/C++/Java
(Programming Languages)
Generations of Programming
Languages
Generation First Second Third Fourth
1010101001
100010 body.top
1001101010 { color :
Code LDA 34 ADD
000001 x=x+1 red; font-
example #1 STO 34
1111111110 style :
100010 italic }
(HIGH)
(LOW) (LOW) (HIGH) SQL,
Visual Basic
Language Machine Assembly CSS, Haskell
, C, python
Code Code etc.
A set of “instructions” written in a “programing
language” to achieve a specific task is called a
“program”
Flowcharts
Graphical representation of any program is called
flowchart.
There are some standard graphics that are used in
flowchart as following:
Make a flowchart to input temperature, if temperature
is less than 32 then print "below freezing" otherwise
print "above freezing"?
Draw a flowchart to check if a number is divisible by 5
and greater than 100.
Draw a flowchart to check if a number is prime.
Draw a flow chart to find factorial of a number.
Example: Write an algorithm to determine a student’s
final grade and indicate whether it is passing or failing.
The final grade is calculated as the average of four
marks.
Input a set of 4 marks
Calculate their average by summing and dividing by 4
if average is below 50
Print “FAIL”
else
Print “PASS”
Pseudocode
Similar to algorithm but more human like yet
independent of any particular programming language
Input M1,M2,M3,M4
GRADE (M1+M2+M3+M4)/4
if (GRADE < 50) then
Print “FAIL”
else
Print “PASS”
endif
Hello World Program
print("Hello, World!")
Running Python Code
Python file has .py extension
Execution through
Command prompt
IDE like VS
Cloud based like Google Collab
Python code execution
Python is an
interpreted
language
High level vs. low level
Python is a general-purpose interpreted, interactive,
object-oriented, and high-level programming language.
Portable
Extendable
Databases
GUI Programming
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).
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")
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)
Python Keywords
Variable, Values, Types, Statement
counter = 100 # An integer assignment
print(counter)
print(type(counter))
100
<class 'int'>
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]]
#However
alist[2][0]=1
print(mylist)
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)
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 3 rd
(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
print (dict[2]) # Prints value for 2 key
This is two
print (tinydict) # Prints complete dictionary
{'dept': 'sales', 'code': 6734, 'name': 'john'}
print (tinydict.keys()) # Prints all the keys
dict_keys(['dept', 'code', 'name'])
print (tinydict.values()) # Prints all the values
Data Type Conversion
To convert between types, you simply use the type-
name as a function.
print(int(2.7))
2
print(float(2))
2.0
print(complex(2,4))
(2+4j)
print(str(44+55)+str(30/9))
993.3333333333333335
Basic Operators
Arithmetic Operators
Comparison (Relational) Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
Arithmetic Operators
and
a=10
b=21
Assume
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 ", 14. c = a**b
c) 15. print ("Line 6 - Value of c is ", c)
Line 2 - Value of c is 11 Line 6 - Value of c is 8
6. c=a*b 16. a = 10
7. print ("Line 3 - Value of c is ", c) 17. b = 5
Line 3 - Value of c is 210
18. c = a//b
8. c = a / b
19. print ("Line 7 - Value of c is ", c)
9. print ("Line 4 - Value of c is ", Line 7 - Value of c is 2
c)
Line 4 - Value of c is 2.1
Comparison Operators
and
a=10
b=20
Assume
1. a = 21; b = 10 Line 2 - a is not equal to b
2. if ( a == b ): 10. if ( a < b ):
3. print ("Line 1 - a is equal 11. print ("Line 3 - a is less
to b") than b" )
4. else: 12. else:
5. print ("Line 1 - a is not 13. print ("Line 3 - a is not
equal to b") less than b")
Line 1 - a is not equal to b Line 3 - a is not less than b
6. if ( a != b ): 14. if ( a > b ):
7. print ("Line 2 - a is not 15. print ("Line 4 - a is
equal to b") greater than b")
8. else: 16. else:
9. print ("Line 2 - a is equal 17. print ("Line 4 - a is not
to b") greater than b")
1. a = 21; b = 10 Line 5 - a is either less than
2. a,b=b,a #values of a and or equal to b
b swapped. a becomes 10, 7. if ( b >= a ):
b becomes 21 8. print ("Line 6 - b is
3. if ( a <= b ): either greater than or
4. print ("Line 5 - a is equal to b")
either less than or equal 9. else:
to b") 10. print ("Line 6 - b is
5. else: neither greater than nor
6. print ("Line 5 - a is equal to b")
neither less than nor equal Line 6 - b is either greater than or
equal to b
to b")
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 ",
2. b = 10 c)
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)
Line 1 - Value of c is 31 14. print ("Line 5 - Value of c is ", c)
Line 5 - Value of c is 2
6. c += a
7. print ("Line 2 - Value of c is ", 15. c **= a
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 ", 18. print ("Line 7 - Value of c is ", c)
c) Line 7 - Value of c is 99864
Line 3 - Value of c is 1092
10. c /= a
Assume
a=10
and
b=20
Bitwise Operators
1. a = 60 # 60 = 0011 1100 10. print ("result of EXOR is ",
2. b = 13 # 13 = 0000 1101 c,':',bin(c))
result of EXOR is 49 : 0b110001
3. print
('a=',a,':',bin(a),'b=',b,':',bin(b) 11. c = ~a; # -61 = 1100 0011
) 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
15. c = a >> 2; # 15 = 0000 1111
8. print ("result of OR is ",
c,':',bin(c)) 16. print ("result of RIGHT SHIFT is
result of OR is 61 : 0b111101
", c,':',bin(c))
result of RIGHT SHIFT is 15 : 0b1111
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
Short-circuit evaluation of logical
expressions
Expressions are evaluated from left to right
Leaves or short-circuits the rest of the expression if decision
can be made early
x=6 Output:
y=2 True
print(x >= 2 and (x/y) > 2) False
x=1 ZeroDivisionError: division by zero
y=0 We can decide which
print(x >= 2 and (x/y) > 2) expression to place first
x=6 Guard evaluation
y=0
print(x >= 2 and (x/y) > 2)
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
3. list = [1, 2, 3, 4, 5 ] available in the given list")
Line 2 - b is not available in the given
4. if ( a in list ):
list
5. print ("Line 1 - a is 12. c=b/a
available in the given list")
13. if ( c in list ):
6. else:
14. print ("Line 3 - a is
7. print ("Line 1 - a is not available in 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.
1. a = 20 10. else:
2. b = 20 11. print ("Line 3 - a and b do
3. print ('Line 1','a=',a,':',id(a), not 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 15. print ("Line 5 - a and b do
not have same identity") not 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
Highest
Lowest
Operators with the same precedence are evaluated from left
to right
1. a = 20 15 ) / 5
2. b = 10 9. print ("Value of ((a + b) *
3. c = 15 c) / d is ", e)
Value of (a + b) * (c / d) is 90.0
4. d=5
5. print ("a:%d b:%d c:%d d: 10.e = (a + b) * (c / d) # (30)
%d" % (a,b,c,d )) * (15/5)
a:20 b:10 c:15 d:5 11. print ("Value of (a + b) * (c
6. e = (a + b) * c / d #( 30 *
/ d) is ", e)
Value of (a + b) * (c / d) is 90.0
15 ) / 5
12. e = a + (b * c) / d # 20 +
7. print ("Value of (a + b) *
c / d is ", e) (150/5)
Value of (a + b) * c / d is 90.0 13. print ("Value of a + (b *
8. e = ((a + b) * c) / d # (30 *
c) / d is ", e)
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
if else statement
amount=int(input("Enter Output:
amount: ")) Enter amount: 300
if amount<1000: Discount 15.0
discount=amount*0.05 Net payable: 285.0
print ("Discount",discount)
else:
discount=amount*0.10
print ("Discount",discount)
print ("Net payable:",amount-
discount)
elif statement (Just like ‘else if’ in
C/C++)
amount=int(input("Enter amount: ")) Output 1:
if amount<1000:
Enter amount: 600
discount=amount*0.05
print ("Discount",discount)
Discount 30.0
elif amount<5000: Net payable: 570.0
discount=amount*0.10
print ("Discount",discount)
else:
discount=amount*0.15
print ("Discount",discount)
print ("Net payable:",amount-
discount)
elif statement (Just like ‘else if’ in
C/C++)
amount=int(input("Enter amount: ")) Output 2:
if amount<1000:
Enter amount: 3000
discount=amount*0.05
print ("Discount",discount)
Discount 300.0
elif amount<5000: Net payable: 2700.0
discount=amount*0.10
print ("Discount",discount)
else:
discount=amount*0.15
print ("Discount",discount)
print ("Net payable:",amount-
discount)
elif statement (Just like ‘else if’ in
C/C++)
amount=int(input("Enter amount: ")) Output 3:
if amount<1000:
Enter amount: 6000
discount=amount*0.05
print ("Discount",discount)
Discount 900.0
elif amount<5000: Net payable: 5100.0
discount=amount*0.10
print ("Discount",discount)
else:
discount=amount*0.15
print ("Discount",discount)
print ("Net payable:",amount-
discount)
Nested conditionals
x, y = 5,6
if x == y:
print('x and y are equal')
else:
if x < y:
print('x is less than y')
else:
print('x is greater than y')
Reading Input
The input([prompt]) function reads one line from
standard input and returns it as a string (removing the
trailing newline).
str = input("Enter your input: ");
print("Received input is : ", str)
Catching exception with try and
except
print("\n")
inp = input('Enter Fahrenheit Temperature: ')
fahr = float(inp)
cel = (fahr - 32.0) * 5.0 / 9.0
print(cel)
Enter Fahrenheit Temperature: we
ValueError: could not convert string to float: 'we’
“try / except” help with catching and dealing with expected
and unexpected errors
print("\n")
inp = input('Enter Fahrenheit Temperature:')
try:
fahr = float(inp)
cel = (fahr - 32.0) * 5.0 / 9.0
print(cel)
except:
print('You did not enter a valid number')
Enter Fahrenheit Temperature:we
You did not enter a valid number
Exceptions
x=3
y=4
try:
x/y
except ZeroDivisionError:
print("Divisor must not be 0")
except TypeError:
print("They must be numbers")
except:
print("Something unspecified went wrong")
else:
A Catch All Exception Script
import traceback
try:
a = 2/0
except Exception as e:
print(e.__doc__)
print(traceback.format_exception(e))
Functions
Function
A named sequence of statements that performs a
specific computational task
print("Hello, World!")
Built-in functions
print(max('Hello world'))
print(min('Hello world'))
print(len('Hello world'))
Type conversion functions
print(int('32')) 32
#print(int('Hello')) ValueError: invalid literal
for int() with base 10:
print(int(3.99999)) 'Hello’
print(int(-2.3)) 3
print(float(32)) -2
print(float('3.14159')) 32.0
3.14159
print(str(32))
32
print(str(3.14159))
3.14159
Defining Own Functions
Your own function is a set of reusable statements
Naming a function: same as variables
The first character cannon be a number
Cannot use a keyword
Defining a Function
def name(args):
""" function_docstring """
commands
return value
def pythagoras(x,y): 5.0
""" Computes the hypotenuse of Help on function pythagoras in
two arguments""" module __main__:
h = pow(x**2+y**2,0.5)
pythagoras(x, y)
# pow(x,0.5) is the square root Computes the hypotenuse o
return h two arguments
print(pythagoras(3,4))
Flow of execution
A function is not executed until called
When called
Execution flow jumps to the function
Returns to the callee after the last line of the function
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("Akshay")
Akshay
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
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) Output:
print ("Age ", age) Name: miki
return Age 50
Name: miki
# Now you can call printinfo function
Age 35
printinfo( age=50, 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) 10
return Output is:
# Now you can call printinfo function 70
printinfo( 10 ) 60
printinfo( 70, 60, 50 )
50
Anonymous Functions
Sytax
lambda argument_list: expression
sum = lambda x, y : x + y
print(sum(3,4)) 7
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.
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) 97.7
temperatures = (36.5, 37, 37.5, 38, 98.600000000000
39)
F = map(fahrenheit, temperatures) 01
for num in F: 99.5
print(num) 100.4
102.2
map with lambda
temperatures = (36.5, 37, 37.5, 38, 39)
F = map(lambda x: (float(9)/5)*x + 32, temperatures)
for x in F: [97.7, 98.60000000000001, 99.5, 100.4,
102.2]
print(x)
a = [1,2,3,4]
b = [17,12,11,10]
c = [-1,-4,5,9] [18, 14, 14,
print(list(map(lambda x,y:x+y, a,b))) 14]
print(list(map(lambda x,y,z:x+y+z, a,b,c))) [17, 10, 19,
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
T=sum( 10, 20 )
print ("Outside the function global total : ", total )
Inside the function local total : 30
Pass by Value vs. Pass by Reference
Primitive types like numbers, strings, and tuples are
passed by values
Collection types like lists and dictionaries are passed by
references
Identity Operators
Compare the memory locations of two objects.
1. def checkPassBy( t_num, t_str, 12. a_tup = ('b', 'a', 'n', 'a', 'n', 'a')
t_tup, t_list): 13. b_tup = ('b', 'a', 'n', 'a', 'n', 'a')
2. print(id(t_num), id(t_str), 14. a_list = ['b', 'a', 'n', 'a', 'n', 'a']
id(t_tup), id(t_list)) 15. b_list = ['b', 'a', 'n', 'a', 'n', 'a']
3. t_num += 1 16. print(help(id))
4. t_str += t_str 17. print(id(a_num) , id(b_num),
5. t_list[1] = '$' a_num is b_num)
6. print(t_num, t_str, t_tup, 18. print(id(a_str), id(b_str), a_str is
t_list) b_str)
7. return 19. print(id(a_tup), id(b_tup), a_tup
is b_tup)
8. a_num = 5 20. print(id(a_list), id(b_list), a_list
9. b_num = 5 is b_list)
10. a_str = 'banana' 21. checkPassBy(a_num, a_str,
11. b_str = 'banana' a_tup, a_list)
22. print(a_num, a_str, a_tup, a_list)
return statement
Can return no value
Can return single value like numbers and strings
Can return multiple value using collection types such as
lists
Why functions?
Makes your program easier to read, understand, and
debug.
Make a program smaller by eliminating repetitive code.
Later, if you make a change, you only have to make it
in one place.
Dividing a long program into functions allows you to
debug the parts one at a time and then assemble them
into a working whole.
Well-designed functions are often useful for many
programs. Once you write and debug one, you can
reuse it.
Looping Constructs
while loop
count = 0 Output:
while (count < 9): The count is: 0
The count is: 1
print ('The count is:',
The count is: 2
count)
The count is: 3
count = count + 1 The count is: 4
print ("Good bye!") The count is: 5
The count is: 6
The count is: 7
The count is: 8
Infinite Loop
print("\n")
count = 0
while (True):
print ('The count is:', count)
count = count + 1
print ("Good bye!")
Using else with while loop
If the else statement is used Output:
with a while loop, the else 0 is less than 5
statement is 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
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
Iterating over a set of things
for var in list(range(5)): Output:
print (var) 0
1
2
3
4
for loop
1. for letter in 'Python': # traversal Output:
of a string sequence Current Letter : P
2. print ('Current Letter :', letter) Current Letter : y
3. print()#prints newline character Current Letter : t
4. fruits = ['banana', 'apple', Current Letter : h
'mango'] Current Letter : o
5. for fruit in fruits: # traversal of Current Letter : n
List sequence
6. print ('Current fruit :', fruit) Current fruit : banana
Current fruit : apple
7. print ("Good bye!")
Current fruit : mango
for loop iteration by sequence index
fruits = ['banana', 'apple', 'mango']
for index in range(len(fruits)):
print ('Current fruit :', fruits[index])
Output
print ("Good bye!") Current fruit :
banana
Current fruit : apple
Current fruit :
mango
Good bye!
Loop Control Statements
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
break statement
1. for letter in 'Python': # First Example Output:
if letter == 'h':
2.
Current Letter : P
3. break
4. print ('Current Letter :', letter)
Current Letter : y
Current Letter : t
5. var = 10 # Second Example Current variable value :
6. while var > 0: 10
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
Good bye!
Output:
continue statement Current Letter : P
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
5. var = 10 # Second Example
Current variable value : 7
6. while var > 0: Current variable value : 6
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!
Else statement with Loops
If the else statement is used within 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. Again, the loop must terminate normally.
Maximum and minimum loops
largest = None
print('Before:', largest)
for itervar in [3, 41, 12, 9, 74, 15]:
if largest is None or itervar > largest : #
None is a special constant to mark the variable
as "empty"
largest = itervar
print('Loop:', itervar, largest)
print('Largest:', largest)
smallest = None
print('Before:', smallest)
for itervar in [3, 41, 12, 9, 74, 15]:
if smallest is None or itervar <
smallest:
smallest = itervar
print('Loop:', itervar, smallest)
print('Smallest:', smallest)
Strings
A string is a sequence of characters.
fruit = 'banana'
print(fruit[1])
print(fruit[1.5]) #TypeError: string indices must be
integers, not 'float'
print(len(fruit))
print(fruit[len(fruit)]) #IndexError: string index out
of range
Traversal through a string with a loop
fruit = 'banana'
O/p:
index = 0 b
while index < a
len(fruit): n
letter = fruit[index] a
print(letter) n
index = index + 1 a
fruit = 'banana' O/p:
for char in fruit: b
print(char) a
n
a
n
a
String Slices
s = 'Monty
O/p:
Python'
Monty
print(s[0:5]) Python
print(s[6:12]) Monty
print(s[:6])
print(s[6:6])
Strings are immutable
greeting = 'Hello, world!'
greeting[0] = 'J' #TypeError: 'str' object does not
support item assignment
new_greeting = 'J' + greeting[1:]
print(new_greeting)
Jello, world!
Looping and counting
word = 'banana'
count = 0
for letter in word:
if letter == 'a':
count = count + 1
print(count)
3
The in operator
Does substring comparison
print('a' in 'banana')
print('seed' in 'banana’)
O/p:
True
False
String comparison
word = 'banana'
if word == 'banana':
print('All right, bananas.')
word = 'apple'
if word < 'banana': #string comparison
print('Your word,' + word + ', comes before
banana.')
elif word > 'banana':
print('Your word,' + word + ', comes after banana.')
else:
print('All right, bananas.')
String methods
Strings are Python objects.
Object = data (the actual string itself) + methods
(functions built into the object)
Object (metadata/template) is used to create an
instance of the object.
type function: type of object
dir function: lists the methods available for an object
help function: prints documentation on a method
stuff = 'Hello world'
print(type(stuff))
print(dir(stuff))
#https://docs.python.org/library/stdtypes.html#string-methods.
<class 'str'>
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__',
'__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__',
'__getnewargs__', '__getstate__', '__gt__', '__hash__', '__init__',
'__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__',
'__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__',
'__rmul__', '__setattr__',
'__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center',
'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map',
'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier',
'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust',
'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix',
'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines',
'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
print(help(str.capitalize))
Help on method_descriptor:
capitalize(self, /)
Return a capitalized version of the string.
More specifically, make the first character have upper case
and the rest lower
case.
None
Method vs. Function
Function is an independent piece
Method: a function in built or associated with an object
word = 'banana'
new_word = word.upper() #upper is a method
print(new_word) #print is a function
word = 'banana'
print(word.find('a')) # 1
print(word.find('na')) # 2
print(word.find('na', 3)) #finds substring starting at index 3, o/p 4
print(' How do you do '.strip()) #removes trailing white spaces,
o/p 'How do you do'
line = 'Have a nice day'
print(line.startswith('Have')) # True
print(line.startswith('h')) #case sensitive, False
print(line.lower().startswith('h')) # True
E.g., extracting domain from an email id
data = 'From [email protected] Sat Jan 5
09:14:16 2008'
atpos = data.find('@')
print(atpos) #21
sppos = data.find(' ',atpos)
print(sppos) #31
host = data[atpos+1:sppos]
print(host) #uct.ac.za
Files
Files
Persistence
RAM vs. Secondary Storage (Hard Disk, USB Drive)
fhand = open('./files/mbox.txt')
print(fhand)
<_io.TextIOWrapper name='./files/mbox.txt' mode='r'
encoding='cp1252'>
File not found error
fhand = open('./mbox.txt')
print(fhand)
FileNotFoundError: [Errno 2] No such file or
directory: './mbox.txt'
Count lines in files
fhand = open('./files/mbox-short.txt')
count = 0
for line in fhand:
count = count + 1
print('Line Count:', count)
Line Count: 1910
Using while loop
fhand = open('./files/mbox-short.txt')
line = fhand.readline()
count = 0
while line:
count = count + 1
line = fhand.readline()
print('Line Count:', count)
Reading entire contents
fhand = open('./files/mbox-short.txt')
inp = fhand.read()
print(len(inp))
print(inp[:40])
O/p:
94626
From
[email protected] Sat
Jan
Warning
fhand = open('./files/mbox-short.txt')
print(len(fhand.read()))
print(len(fhand.read()))
O/p:
94626
0
Searching through a file
All lines that start with “From:”
O/p:
From:
fhand = open('./files/mbox-short.txt')
[email protected]
for line in fhand:
From:
if line.startswith('From:'): [email protected]
print(line)
From: [email protected]
fhand = open('./files/mbox-short.txt')
for line in fhand:
line = line.rstrip() # strips whitespaces on the
right side
if line.startswith('From:'):
O/p:
print(line) From:
[email protected] From:
[email protected] From:
[email protected] From:
[email protected]...
Another take
fhand = open('./files/mbox-short.txt')
for line in fhand:
line = line.rstrip()
# Skip 'uninteresting lines'
if not line.startswith('From:'):
continue
# Process our 'interesting' line
print(line)
String find
Find returns position of the substring or -1 if not
found
fhand = open('./files/mbox-short.txt')
for line in fhand:
line = line.rstrip()
if line.find('@uct.ac.za') == -1: continue
print(line)
Letting the user choose the file name
fname = input('Enter the file name: ')
fhand = open(fname)
count = 0
for line in fhand:
if line.startswith('Subject:'):
count = count + 1
print('There were', count, 'subject lines in', fname)
Using try, except, and open
print("\n")
fname = input('Enter the file name: ')
try:
fhand = open(fname)
except:
print('File cannot be opened:', fname)
exit() #terminates the program
count = 0
for line in fhand:
if line.startswith('Subject:'):
count = count + 1
print('There were', count, 'subject lines in', fname)
Writing files
fout = open('./files/output.txt', 'w') #w indicates write mode, a is for
append
print(fout)
line1 = "This here's the wattle,\n"
print(fout.write(line1)) #print automatically appends new line, write
doesn't
line2 = 'the emblem of our land.\n'
print(fout.write(line2)) #outputs #chars written
fout.close()
O/p:
<_io.TextIOWrapper name='./files/output.txt' mode='w' encoding='cp1252’>
24
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 “:”
oddList = [0,2,4,6]
evenList = [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]=oddList
newList[1::2]=evenList
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] #does not return the deleted value
print ("After deleting value at index 2 : ", list)
After deleting value at index 2 : ['physics', 'chemistry',
2000]
del list[2:4] #deletes multiple value
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
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']
Traversing a list
numbers = [17, 123]
cheeses = ['Cheddar', 'Edam', 'Gouda']
for cheese in cheeses:
print(cheese) #without using index
for i in range(len(numbers)):
numbers[i] = numbers[i] * 2 #with index
print(numbers)
Iterating over an empty list
for x in empty:
print('This never happens.')
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']
Average in a list of numbers
numlist = list()
while (True):
inp = input('Enter a number: ')
if inp == 'done': break
value = float(inp)
numlist.append(value)
average = sum(numlist) / len(numlist)
print('Average:', average)
Lists and strings
A list of characters is not same as a string
s = 'spam'
t = list(s)
print(t)
O/p:
['s', 'p', 'a', 'm']
Sentence to word
s = 'pining for the fjords'
t = s.split()
print(t)
O/p:
['pining', 'for', 'the', 'fjords']
the
s = 'spam-spam-spam'
t = s.split('-')
print(t)
print(t[2])
O/p
['spam', 'spam', 'spam']
Concatenating words to a string
t = ['pining', 'for', 'the', 'fjords']
delimiter = ' '
print(delimiter.join(t))
O/p:
pining for the fjords
Parsing Lines
fhand = open('./files/mbox-
short.txt') O/p:
Sat
for line in fhand:
Fri
line = line.rstrip() Fri
if not line.startswith('From '): Fri
continue ...
words = line.split()
print(words[2])
Slice operator returns a new list
a_list = [1,2,3]
b_list = a_list
c_list = a_list[:3]
b_list.pop();
print(a_list, b_list, c_list); # [1, 2] [1, 2] [1, 2, 3]
Working with Dictionaries
Each key is separated from its value by a colon (:), the
items are separated by commas, and the whole thing is
enclosed in curly braces.
An empty dictionary without any items is written with
just two curly braces, like this: {}.
Keys are unique within a dictionary while values may not
be.
The values of a dictionary can be of any type, but the
keys must be of an immutable data type such as strings,
numbers, or tuples.
Creating empty list
print("\n")
eng2sp = dict()
print(eng2sp)
Accessing Values in Dictionary
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print ("dict['Name']: ", dict['Name'])
dict['Name']: Zara
print ("dict['Age']: ", dict['Age'])
dict['Age']: 7
Trying to access a non-existent key
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
print("dict['Alice']: ", dict['Alice'])
Traceback (most recent call last):
…
print("dict['Alice']: ", dict['Alice'])
KeyError: 'Alice'
Updating Dictionary
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School" # Add new entry
print ("dict['Age']: ", dict['Age'])
dict['Age']: 8
print ("dict['School']: ", dict['School'])
dict['School']: DPS School
Delete Dictionary Elements
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
del dict['Name'] # remove entry with key 'Name'
print(dict)
{'Age': 7, 'Class': 'First'}
dict.clear() # remove all entries in dict
del dict # delete entire dictionary
print ("dict['Age']: ", dict['Age']) #gives error
print ("dict['School']: ", dict['School']) #gives error
Properties of Dictionary Keys
Dictionary values have no restrictions.
More than one entry per key is not allowed.
When duplicate keys are encountered during assignment,
the last assignment wins.
dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'}
print ("dict['Name']: ", dict['Name'])
dict['Name']: Manni
Keys must be immutable.
You can use strings, numbers or tuples as dictionary
keys but mutable lists, e.g., ['key’], is not allowed.
dict = {['Name']: 'Zara', 'Age': 7}
print ("dict['Name']: ", dict['Name'])
TypeError: unhashable type: 'list'
Built-in Dictionary Functions &
Methods
len(dict)
Gives the total length of the dictionary. This would be equal
to the number of items in the dictionary.
str(dict)
Produces a printable string representation of a dictionary.
type(variable)
Returns the type of the passed variable. If passed variable
is dictionary, then it would return a dictionary type.
Dictionary len() Method
Description
The method len() gives the total length of the dictionary. This
would be equal to the number of items in the dictionary.
Syntax
len(dict)
Parameters
dict - This is the dictionary, whose length needs to be
calculated.
Return Value
This method returns the length.
dict = {'Name': 'Manni', 'Age': 7, 'Class': 'First'}
print (“Length :”, len (dict))
Length : 3
Dictionary str() Method
Description
The method str() produces a printable string representation
of a dictionary.
Syntax
str(dict)
Parameters
dict - This is the dictionary.
Return Value
This method returns string representation.
dict = {'Name': 'Manni', 'Age': 7, 'Class': 'First'}
print ("Equivalent String : %s" % str (dict))
Equivalent String : {'Name': 'Manni', 'Age': 7, 'Class':
'First'}
Dictionary type() Method
Description
The method type() returns the type of the passed variable. If
passed variable is dictionary then it would return a dictionary
type.
Syntax
type(dict)
Parameters
dict - This is the dictionary.
Return Value
This method returns the type of the passed variable.
dict = {'Name': 'Manni', 'Age': 7, 'Class': 'First'}
print ("Variable Type : %s" % type (dict))
Variable Type : <class 'dict'>
Dictionary Methods
dict.clear()
Removes all elements of dictionary dict.
dict.copy()
Returns a shallow copy of dictionary dict.
dict.fromkeys()
Create a new dictionary with keys from seq and values set to
value.
dict.get(key, default=None)
For key key, returns value or default if key not in dictionary.
dict.items()
Returns a list of dict's (key, value) tuple pairs.
dict.keys()
Returns list of dictionary dict's keys.
dict.setdefault(key, default=None)
Similar to get(), but will set dict[key]=default if key is not
already in dict.
dict.update(dict2)
Adds dictionary dict2's key-values pairs to dict.
dict.values()
Returns list of dictionary dict's values.
Dictionary clear() Method
Description
The method clear() removes all items from the dictionary.
Syntax
dict.clear()
Parameters
NA
Return Value
This method does not return any value.
dict = {'Name': 'Zara', 'Age': 7}
print ("Start Len : ", len(dict))
Start Len : 2
dict.clear()
print ("End Len : ", len(dict))
End Len : 0
Dictionary copy() Method
Description
The method copy() returns a shallow copy of the dictionary.
Syntax
dict.copy()
Parameters
NA
Return Value
This method returns a shallow copy of the dictionary.
dict1 = {'Name': 'Manni', 'Age': 7, 'Class': 'First'}
dict2 = dict1.copy()
print ("New Dictionary : ",dict2)
New Dictionary : {'Name': 'Manni', 'Age': 7, 'Class':
'First'}
Dictionary fromkeys() Method
Description
The method fromkeys() creates a new dictionary with keys from seq and
values set tovalue.
Syntax
dict.fromkeys(seq[, value]))
Parameters
seq - This is the list of values which would be used for dictionary keys
preparation.
value - This is optional, if provided then value would be set to this value
Return Value
This method returns the created dictionary.
seq = ('name', 'age', 'sex')
dict = dict.fromkeys(seq)
print ("New Dictionary : ", str(dict))
New Dictionary : {'name': None, 'age': None, 'sex':
None}
dict = dict.fromkeys(seq, 10)
print ("New Dictionary :", str(dict))
New Dictionary : {'name': 10, 'age': 10, 'sex': 10}
Dictionary get() Method
Description
The method get() returns a value for the given key. If the key is
not available then returns default value None.
Syntax
dict.get(key, default=None)
Parameters
key - This is the Key to be searched in the dictionary.
default - This is the Value to be returned in case key does not
exist.
Return Value
This method returns a value for the given key. If the key is not
dict = {'Name': 'Zara', 'Age': 27}
print ("Value : ", dict.get('Age'))
Value : 27
print ("Value : ", dict.get('Sex', "NA"))
Value : NA
Dictionary items() Method
Description
The method items() returns a list of dict's (key, value) tuple
pairs.
Syntax
dict.items()
Parameters
NA
Return Value
This method returns a list of tuple pairs.
dict = {'Name': 'Zara', 'Age': 7}
print ("Value : " , dict.items())
Value : dict_items([('Name', 'Zara'), ('Age', 7)])
Dictionary keys() Method
Description
The method keys() returns a list of all the available keys in the
dictionary.
Syntax
dict.keys()
Parameters
NA
Return Value
This method returns a list of all the available keys in the
dictionary.
dict = {'Name': 'Zara', 'Age': 7}
print ("Value :" , dict.keys())
for key in dict:
print(key, dict[key])
Value : dict_keys(['Name', 'Age’])
Name Zara
Age 7
Dictionary setdefault() Method
Description
The method setdefault() is similar to get(), but will set dict[key]=default
if the key is not already in dict.
Syntax
dict.setdefault(key, default=None)
Parameters
key - This is the key to be searched.
default - This is the Value to be returned in case key is not found.
Return Value
This method returns the key value available in the dictionary and if
given key is not available then it will return provided default value.
dict = {'Name': 'Zara', 'Age': 7}
print ("Value :" , dict.setdefault('Age', None))
Value : 7
print ("Value : ", dict.setdefault('Sex', None))
Value : None
print (dict)
{'Name': 'Zara', 'Age': 7, 'Sex': None}
Dictionary update() Method
Description
The method update() adds dictionary dict2's key-values pairs
in to dict.
Syntax
dict.update(dict2)
Parameters
dict2 - This is the dictionary to be added into dict.
Return Value
This method does not return any value.
dict = {'Name': 'Zara', 'Age': 7}
dict2 = {'Sex': 'female' }
dict.update(dict2)
print ("updated dict : ", dict)
updated dict : {'Name': 'Zara', 'Age': 7, 'Sex': 'female'}
Dictionary values() Method
Description
The method values() returns a list of all the values available in a
given dictionary.
Syntax
dict.values()
Parameters
NA
Return Value
This method returns a list of all the values available in a given
dictionary.
dict = {'Sex': 'female', 'Age': 7, 'Name': 'Zara'}
print ("Values : ", list(dict.values()))
Values : ['female', 7, 'Zara']
Word Counting Program
fname = input('Enter the file for line in fhand:
name: ') words = line.split()
try: for word in words:
fhand = open(fname) if word not in counts:
except: counts[word] = 1
print('File cannot be else:
opened:', fname) counts[word] += 1
exit() print(counts)
counts = dict()
Working with Tuples
A tuple is a sequence of immutable Python objects.
Tuples are sequences, just like lists. The main
difference between the tuples and the lists is that the
tuples cannot be changed unlike lists.
Tuples use parentheses, whereas lists use square
brackets.
Creating a Tuple
Syntactically, a tuple is a comma-separated list of
values.
Optionally, it is common to enclose tuples in
parentheses to help us quickly identify tuples when we
look at Python code.
exampletup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5 )
tup3 = "a", "b", "c", "d“
t = tuple('lupins')
Empty Tuple
tup1 = ();
To write a tuple containing a single value you have to
include a comma, even though there is only one value.
tup1 = (50,)
Without comma, it is treated as an individual
tup1 = (50)
print(type(tup1))
<class 'int'>
Accessing Values in Tuples
tup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5, 6, 7 )
print ("tup1[0]: ", tup1[0])
print ("tup2[1:5]: ", tup2[1:5])
tup1[0]: physics
tup2[1:5]: (2, 3, 4, 5)
You cannot update or change the values of tuple elements.
You are able to take portions of the existing tuples to create
new tuples:
tup1 = (12, 34.56)
tup2 = ('abc', 'xyz')
# Following action is not valid for tuples
# tup1[0] = 100;
# So let's create a new tuple as follows
tup3 = tup1 + tup2
print (tup3)
Delete Tuple Elements
Removing individual tuple elements is not possible.
However, an entire tuple can be deleted
tup = ('physics', 'chemistry', 1997, 2000);
print (tup)
del tup;
# print(tup) will give an error (raises an exception)
after deletion
Basic Tuples Operations
Indexing, Slicing
Work the same was as lists and strings
Let
T=('C++', 'Java', 'Python')
Built-in Tuple Functions
len(tuple)
Gives the total length of the tuple.
max(tuple)
Returns item from the tuple with max value.
min(tuple)
Returns item from the tuple with min value.
tuple(seq)
Converts a list into tuple.
Tuple len() Method
Description
The len() method returns the number of elements in the tuple.
Syntax
len(tuple)
Parameters
tuple - This is a tuple for which number of elements to be
counted.
Return Value
This method returns the number of elements in the tuple.
tuple1, tuple2 = (123, 'xyz', 'zara'), (456, 'abc')
print ("First tuple length : ", len(tuple1))
First tuple length : 3
print ("Second tuple length : ", len(tuple2))
Second tuple length : 2
Tuple max() Method
Description
The max() method returns the elements from the tuple with
maximum value.
Syntax
max(tuple)
Parameters
tuple - This is a tuple from which max valued element to be
returned.
Return Value
This method returns the elements from the tuple with maximum
value.
tuple1, tuple2 = ('maths', 'che', 'phy', 'bio'), (456,
700, 200)
print ("Max value element : ", max(tuple1))
Max value element : phy
print ("Max value element : ", max(tuple2))
Max value element : 700
Tuple min() Method
Description
The min() method returns the elements from the tuple with minimum
value.
Syntax
min(tuple)
Parameters
tuple - This is a tuple from which min valued element is to be
returned.
Return Value
This method returns the elements from the tuple with minimum
value.
tuple1, tuple2 = ('maths', 'che', 'phy', 'bio'), (456,
700, 200)
print ("min value element : ", min(tuple1))
min value element : bio
print ("min value element : ", min(tuple2))
min value element : 200
Tuple tuple() Method
Description
The tuple() method converts a list of items into tuples.
Syntax
tuple(seq )
Parameters
seq - This is a tuple to be converted into tuple.
Return Value
This method returns the tuple.
list1= ['maths', 'che', 'phy', 'bio']
tuple1=tuple(list1)
print ("tuple elements : ", tuple1)
tuple elements : ('maths', 'che', 'phy', 'bio')
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,
'tails':0,
}
sides = list(outcomes.keys())
for i in range(10000):
outcomes[ random.choice(sides) ] += 1
print('Heads:', outcomes['heads'])
print('Tails:', outcomes['tails'])
Heads: 5033
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
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
seed([x], [y])
Parameters
x - This is the seed for the next random number. If omitted, then
it takes system time to generate the next random number.
Y - This is version number (default is 2). str, byte or byte array
object gets converted in int. Version 1 used hash() of x.
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
random.seed("hello",2)
print ("random number with string seed", random.random())
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
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