Module 1 - Python
Module 1 - Python
Module 1
Python Basics, Flow Control, Functions
Textbook 1: Al Sweigart, “Automate the Boring Stuff with Python”, 1 st Edition, No Starch Press,
2015. (Available under CC-BY-NC-SA license at https://automatetheboringstuff.com/)
Python 2.4 November 30, 2004 Python 3.7 June 27, 2018
Python 2.5 September 19, 2006 Python 3.8 December 18, 2019
Python 2.6 October 1, 2008 Python 3.8.2 February 24, 2020
Python 2.7 July 3, 2010 Python 3.8.3 May 13, 2020
Python 3.8.4 July 13, 2020
Python 3.8.5 July 20, 2020
Python 3.9 Oct 10, 2020
Python 3.10 Oct 4, 2021
9) Enterprise Applications: Python can be used to create applications which can be used within an
Enterprise or an Organization. Some real time applications are: OpenErp, Tryton, Picalo etc.
10) Applications for Images: Using Python several applications can be developed for image.
Applications developed are: VPython, Gogh, imgSeek etc.
Define particular block by curly braces, No need of semi colons and curly
Syntax Complexity
end statements by ; braces, uses indentation
Strongly typed, need to define the exact Dynamic, no need to define the
Ease of typing
datatype of variables exact datatype of variables.
Java is much faster than python in terms Expected to run slower than Java
Speed of execution
of speed. programs
Keywords 51 37
** Exponent 2 ** 3 8
/ Division 22 // 8 2.75
* Multiplication 3*5 15
- Subtraction 5–2 3
+ Addition 2+2 4
Evaluate
>>> 2 + 5 * 6 #32
>>> 29 // 6 #4
>>> (6 -1) * ((7+2)/(3-1)) #22.5
Evaluating expression
The values -2 and 30, are said to be integer values. The integer (or int) data type indicates values
that are whole numbers.
Numbers with a decimal point, such as 3.14, are called floating-point numbers (or floats).
Note that even though the value 42 is an integer, the value 42.0 would be a floating-point number.
If + operator is used between string and integer, an error message will be displayed
o >>>’Alice’ + 5 #TypeError : Can’t convert ‘int’ object to str implicitly
A variable is initialized (or created) the first time a value is stored in it (spam = 'Hello')
After that, variable can be used in expressions with other variables and values (s=spam)
When a variable is assigned a new value, the old value is forgotten. (spam = 'Goodbye‘)
first.py
# This program says hello and asks for your name
print(‘Hello world!’)
print(‘What is your name?’) # ask for your name
myname = input() #ask user to enter name
print(‘It is good to meet you ’+myname)
print(‘The length of your name is :’+str(len(myname))
print(‘What is your age?’) # ask for the age
myage = input() #ask user to enter age
print(‘You are ’+str(int(myage) + 1) +’ in next year.’)
If we pass a value to int that in cannot evaluate as an integer, an error message will be displayed.
int('99.99') #ValueError: invalid literal for int() with base 10: '99.99‘
int(‘two’) #ValueError: invalid literal for int() with base 10: 'two‘
int() function is also used if we need to round a floating point number down.
int(7.7) + 1 #8
float() function converts the value passed to it as floating point
float(10) #10.0
The str() function is handy when you have an integer or float that you want to concatenate to a
string. The int() function is also helpful if you have a number as a string value that you want to
use in some mathematics.
>>> spam = input() # read 100
>>> spam # ’100’
>>> spam = int(spam)
>>> spam # 100
>>> spam * 10 / 5 # 200.0
>>> int(7.7) #7
Operator Meaning
== Equal to
!= Not Equal to
Operators evaluate to True or False depending on the values you give them.
>>> 42 == 42 #True
>>> 42 == 99 #False
>>> 2 != 3 #True
>>> 2 != 2 #False
== (equal to) evaluates to True when the values on both sides are the same, and != (not equal to)
evaluates to True when the two values are different.
>>> 'hello' == 'hello‘ #True
>>> 'hello' == 'Hello‘ #False
>>> 'dog' != 'cat‘ #True
>>> True == True #True
>>> True != False #True
>>> 42 == 42.0 #True
>>> 42 == '42‘ #False
The <, >, <=, and >= operators, on the other hand, work properly only with integer and floating-
point values.
>>> 42 < 100 #True
>>> 42 > 100 #False
The three Boolean operators (and, or, and not) are used to compare Boolean values.
Boolean operators evaluate the expressions down to a Boolean value.
Expression Evaluates to ….
Expression Evaluates to ….
The Boolean operators have an order of operations just like the math operators do.
After any math and comparison operators evaluate, Python evaluates the not operators first, then
the and operators, and then the or operators.
if Statements
An if statement’s clause (the block following the if statement) will execute if the statement’s
condition is True. The clause is skipped if the condition is False.
An if statement could be read as, “If this condition is true, execute the code in the clause.”
In Python, an if statement consists of the following:
o The if keyword
o A condition (that is, an expression that evaluates to True or False)
o A colon
o Starting on the next line, an indented block of code (called the if clause)
Ex:-
if name == ‘Alice’:
print(‘Hi Alice’)
else Statements
An if clause can optionally be followed by an eelse Statements lse statement. The else clause is
executed only when the if statements condition is False.
An else statement could be read as, “If this condition is true, execute this code. Or else, execute
that code.”
An else statement doesn’t have a condition, and in code, an else statement always consists of the
following:
o The else keyword
o A colon
o Starting on the next line, an indented block of code (called the else clause)
Example
if name == ‘Alice’:
print(‘Hi Alice’)
else:
print(‘Hello Stranger’)
Flow chart
elif Statements
• The elif statement is an “else if” statement that always follows an if or another elif statement.
• It provides another condition that is checked only if any of the previous conditions were False.
• In code, an elif statement always consists of the following:
o The elif keyword
o A condition (that is, an expression that evaluates to True or False)
o A colon
o Starting on the next line, an indented block of code (called the elif clause)
• Example 1:
if name == 'Alice':
print('Hi, Alice.')
elif age < 12:
print('You are not Alice, kiddo.')
• Flow Chart
Example 2:
if name == 'Alice':
print('Hi, Alice.')
elif age < 12:
print('You are not Alice, kiddo.')
elif age > 2000:
print('Unlike you, Alice is not an undead, immortal vampire.')
elif age > 100:
print('You are not Alice, grannie.')
spam = 0
while spam < 5:
print('Hello, world.')
spam = spam + 1
Flowchart
Flow chart
break Statements
If the execution of the program reaches a break statement it immediately exits the while loop’s
clause.
Example
while True:
print(‘Enter name of the subject’)
name = input()
if name == ‘python’:
break
print(‘Thanks’)
Flow chart
continue Statements
Continue statements are used inside loops. When the program execution reaches a continue
statement, the program execution immediately jumps back to the start of the loop and re-evaluates
the loop’s condition.
Example
while True :
print('who are you')
name = input()
if name != 'abc':
continue
print('Hello abc, enter your password')
password = input()
if(password == '1234'):
break
print('Access Granted')
Example 1
total = 0
for num in range(10) :
total = total + num
print(total) #45
Example 2
print('My name is')
for i in range(5):
print('Jimmy Five Times (' + str(i) + ')')
The range() function can also be called with three arguments. The first two arguments will be the
start and stop values, and the third will be the step argument. The step is the amount that the
variable is increased by after each iteration.
for i in range(0, 10, 2): #Begin: 0 End: 10 (Exclude) interval: 2
print(i) #prints 0 2 4 6 8
The range() function is flexible in the sequence of numbers it produces for for loops
for i in range(5, -1, -1):
print(i) #5 4 3 2 1 0
For example, the math module has mathematics-related functions, the random module
(random.randint() function) for random number related functions, and so on.
To use module, use import keyword with module name.
An import statement consists of the following:
o The import keyword
o The name of the module
o Optionally, more module names, as long as they are separated by commas.
Example
import random
for i in range(5): #repeat for 0 to 4
print(random.randint(1, 10)) #prints 4 1 8 4 1 (may very)
The random.randint() function call evaluates to a random integer value between the two integers
that you pass it.
An import statement that imports four different modules:
import random, sys, os, math
for i in range(5):
print(randint(1,10) # call to randint() need not be prefixed with
# random.
1.4. Functions
• A function is a block of organized, reusable code that is used to perform a single, related action.
printme(“Abc”)
Calling a function
• It can be called by name of the function and passing arguments.
• Ex:- printme(‘Vemana Institute of Technology’)
‘
• Example :
def hello(name):
print('Hello ' + name)
Output: Values inside the function: [10, 20, 30, [1, 2, 3, 4]]
Values outside the function: [10, 20, 30, [1, 2, 3, 4]]
res = no_return(4, 5)
print(res) #None
return 'Friday'
elif num == 6:
return 'Saturday'
elif num == 7:
return 'Sunday'
#main program
r = random.randint(1,7)
day = getDay(r)
print(day)
• keyword arguments are identified by the keyword put before them in the function call.
• Keyword arguments are often used for optional parameters.
• For example, the print() function has the optional parameters end and sep to specify what should
be printed at the end of its arguments and between its arguments (separating them),respectively.
• The two strings appear on separate lines because the print() function automatically adds a newline
character to the end of the string it is passed.
• However, use of end keyword argument to change this to a different
print('Hello') #outputs Hello
print('World') #Outputs World in separate line
• For example:
print('Hello', end=‘ ')
print('World') #outputs Hello World in a single line
• But you could replace the default separating string by passing the sep keyword argument.
• Enter the following into the interactive shell:
>>> print('cats', 'dogs', 'mice') #cats dogs mice
>>> print('cats', 'dogs', 'mice', sep=',') #cats,dogs,mice
Variables that are assigned outside all functions are said to exist in global scope.
A local scope is created whenever a function is called. When the function returns, the local scope
is destroyed.
local variables cannot be used in global scope.
A variable that exists in a local scope is called a local variable, while a variable that exists in the
global scope is called a global variable. A variable must be one or the other; it cannot be both local
and global.
spam()
print(eggs) #NameError: name 'eggs' is not defined
def bacon():
ham = 101
eggs = 0 #0
eggs = 42
spam()
print(eggs)
def bacon():
eggs = 'bacon local'
print(eggs) # prints 'bacon local'
spam()
print(eggs) # prints 'bacon local'
eggs = 'global'
bacon()
print(eggs) # prints 'global'
There are actually three different variables in this program, but confusingly they are all named
eggs.
The variables are as follows:
o A variable named eggs that exists in a local scope when spam() is called.
o A variable named eggs that exists in a local scope when bacon() is called.
o A variable named eggs that exists in the global scope.
• There are four rules to tell whether a variable is in a local scope or global scope:
1. If a variable is being used in the global scope (that is, outside of all functions), then it is
always a global variable.
2. If there is a global statement for that variable in a function, it is a global variable.
3. Otherwise, if the variable is used in an assignment statement in the function, it is a local
variable.
4. But if the variable is not used in an assignment statement, it is a global variable.
Example
def spam():
global eggs
eggs = 'spam' # this is the global
def bacon():
eggs = 'bacon' # this is a local
def ham():
print(eggs) # this is the global
• If you try to use a local variable in a function before you assign a value to it, as in the following
program, Python will give you an error.
def spam():
print(eggs) # ERROR!
eggs = 'spam local'
eggs = 'global'
spam() #Raises Error
print(spam(2)) #21.0
print(spam(12)) #3.5
print(spam(0)) #ZeroDivisionError: division by zero
print(spam(1)) #not executed
• Example
def spam(dividedby):
try:
return 42/dividedby
except ZeroDivisionError:
print('Error : Invalid argument.')
print(spam(2)) #21.0
print(spam(0)) #Error : Invalid argument None
print(spam(1)) #42.0
print(spam(2)) #21.0
print(spam(0)) #Exception : Invalid argument None
print(spam(1)) #42.0
• Example
def spam(divideBy):
return 42 / divideBy
try:
print(spam(2)) #21.0
print(spam(12)) #3.5
print(spam(0)) #Exception:Error: Invalid argument.
print(spam(1)) #not Executed
except ZeroDivisionError:
print('Error: Invalid argument.')
• The reason print(spam(1)) is never executed is because once the execution jumps to the code in
the except clause, it does not return to the try clause.
• Instead, it just continues moving down as normal.
Output:
Exception Type: <class 'ZeroDivisionError'>
Exception Type: <class 'ZeroDivisionError'>
Exception Class Name: ZeroDivisionError
Description of Exception: division by zero
Example
try:
x=int(input("Enter the First Number: "))
y=int(input("Enter the Second Number:"))
print("The result :",x/y)
except ZeroDivisionError:
print("Cannot divide with Zero")
except ValueError:
print("Please provide int value only")
finally block
• It is not recommended to place cleanup code (resource deallocation, closing database connection
etc) inside try block because there is not guarantee for execution of every statement inside try block
• It is not recommended to place cleanup code inside except block because id there is no exception
then except block will not be executed.
• The main purpose is to maintain cleanup code
• Finally block is executed always irrespective of whether exception raised or not and exception
handled or not.
• Syntax
try:
Risky code
except:
Handling code
finally:
cleanup code
else:
it will be executed if no exception in try block
finally:
cleanup code
it will be executed if either exception or non exception
Example 1
try:
print("Try")
except:
print("Except")
else:
print("Else")
finally:
print("Finally")
Example 2
try:
print("Try")
print(10/0)
except:
print("Except")
else:
print("Else")
finally:
print("Finally")