Unit 3 Python
Unit 3 Python
• Rules:
• The colon (:) is required at the end of the condition.
• The body of the if statement is indicated by the indentation. In
Python, four spaces are used for indenting.
• All lines indented the same amount after the colon will be
executed for the true condition.
• Python interprets non-zero values as True. None and 0 are
interpreted as False.
Conditional Statements (Cont….)
• if statements:
The statement is executed only if the condition is
true, if false then not executed.
Syntax:
if condition:
True block statement
Program :
1. age = input("What's your age = ")
2. if ( age >= 60 ) :
3. print "You are a Senior Citizen"
4. print "Good bye!"
Execution
sh-4.3$ python [Link]
What's your age = 68
You are a Senior Citizen
Good bye!
Conditional Statements (Cont….)
• if...else statements:
• Executes the true statement block only when test condition is True.
• If False, then false statement block is executed.
• Indentation is used to separate the blocks.
Syntax:
if condition:
True statement block.
else:
False statement block.
Program :
1. age = input("What's your age = ")
2. if ( age >= 60 ) :
3. print "Sorry! You are a Senior Citizen"
4. print "Good bye!"
5. else:
6. print "You are selected"
7. print "Have a great day!"
Execution
sh-4.3$ python [Link]
What's your age = 45
You are selected
Have a great day!
sh-4.3$ python [Link]
What's your age = 63
Sorry! You are a Senior Citizen
Good Bye!!
Conditional Statements (Cont….)
• Ternary operator: C and Python
The ternary operator(? : ;) in C takes three arguments. The first
argument is a comparison argument, the second is the result upon a
true comparison, and the third is the result upon a false comparison.
Syntax in C: if condition ? value_if_true : value_if_false;
Example : max = (a > b) ? a : b;
In Python, the syntax for ternary operator is
Program :
1. a = raw_input("Enter a = ")
2. b = raw_input("Enter b = ")
3. max = (a,b)[(a > b)]
4. max = a if (a > b) else b# work in some compilers
only
5. print "Maximum of two numbers = ", max
Execution
sh-4.3$ python [Link]
Enter a = 89
Enter b = 568
Maximum of two numbers = 568
Enter a = 56
Enter b = 41
Maximum of two numbers = 41
Conditional Statements (Cont….)
• if...elif...else (or) chained conditionals
• The elif is short form for else if, used to check multiple conditions.
• If the condition 1 is false, it checks the condition 2 of the next elif block and so on.
• If all the conditions are False, then the else statement is executed.
• Syntax:
if condition 1:
True statement block for condition 1.
elif condition 2:
True statement block for condition 2.
elif condition 3:
True statement block for condition 3.
else:
False statement block. :
• Flowchart for if...elif...else stateme nts
Conditional Statements (Cont….)
• if...elif...else (or) chained conditionals (cont...)
Example program for if...elif...else statement
Program:
1. age = input("What's your age = ")
2. if ( age >= 60 ) :
3. print "Sorry! You are a Senior Citizen"
4. print "Good bye!"
5. elif (age < 60 and age > 40 ):
6. print "You are selected for the post of Senior Manager"
7. print "Have a great day!"
8. elif (age < 40 and age > 20 ):
9. print "You are selected for the post of Junior Manager"
10. print "Have a great day!"
11. else:
12. print("Sorry! you cannot apply")
Execution
sh-4.3$ python [Link]
What's your age = 72
Sorry! You are a Senior Citizen
Good bye!
What's your age = 55
You are selected for the post of Senior Manager
Have a great day!
What's your age = 18
Sorry! you cannot apply
Conditional Statements (Cont….)
• Nested if statements:
if...elif...else statement can be used inside another if...elif...else
statement. This is called nesting in computer programming.
Example program for Nested if statements:
Program :
#check whether the given number is positive, negative or
zero
1. number = input("Enter a number: ")
2. if number >= 0:
3. if number == 0:
4. print("Zero")
5. else:
6. print("Positive number")
7. else:
8. print("Negative number")
Execution
sh-4.3$ python [Link]
Enter a number: 8
Positive number
Enter a number: -9
Negative number
Enter a number: 0
Zero
Iteration (or) Looping
• Repeated execution of a set of statements is called
iteration or looping.
• Flowchart for looping statements:
for<loop_variable> in <sequence>:
<statement or statement block)>
else
Flowchart for FOR loo p: <statement or statement block>
Iteration (or) Looping (cont..)
• The for loop(cont..)
Example program for For loop:
Program 7:
1. # simple program to explain for loop
2. for i in '123':
3. print "Welcome",i,"times"
Execution
sh-4.3$ python [Link]
Welcome 1 times
Welcome 2 times
Welcome 3 times
Iteration (or) Looping (cont..)
• The range() function
Sequence of numbers are also generated using range() function.
range() is defined with start_element, stop_element and step size.
Default step size is equal to 1 if not provided.
Syntax:
Program :
1. # Display numbers from 0 to 10 (11 numbers)
2. numbers = range(11)
3. print(numbers)
4. # Display numbers from 5 (start_element) to 10 (stop_element)
5. numbers = range(5,11)
6. print(numbers)
7. # Display numbers from 1 (start_element) to
8. # 11 (stop_element) with step_size = 2
9. numbers = range(1,11,2)
10. print(numbers)
11. # Display numbers from 10 (start_element) to
12. # 0 (stop_element) with step_size = -1
[Link] = range(10, 0, -1)
[Link](numbers)
Execution
sh-4.3$ python [Link]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[5, 6, 7, 8, 9, 10]
[1, 3, 5, 7, 9]
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
Iteration (or) Looping (cont..)
• The While loop:
The while loop iterates over a block of statements as long as the test condition is true.
The statement body is entered only when the test condition is true. After first iteration,
the test condition is checked again
.In Python, the statement body is determined through indentation. Python interprets
any non-zero value as True. None and 0 are interpreted as False.
Syntax:
While condition:
statement_1
…….
Flowchart for While loop: statement_2
Iteration (or) Looping (cont..)
• The While loop (cont..):
Example program for While loop
Program 12:
1. # Simple While loop
2. a = 0
3. #Body of the loop is intended by four spaces
4. while a < 10:
5. a=a+1
6. print a
Execution
sh-4.3$ python [Link]
1
2
3
4
5
6
7
8
9
10
Iteration (or) Looping (cont..)
• While-Else loop:
Python supports to have an else statement with a while loop statement.
The else statement is executed when the condition becomes false.
Syntax:
While condition:
statement_1
………..
statement_n
Else:
staement_1
Flowchart for While-Else loop: statement_n
Iteration (or) Looping (cont..)
• While-Else loop (cont..)
Example program for While-Else loop
Program :
1.#program for While-Else statement
[Link] = 0
3. while count < 5:
4. print count, " is less than 5"
5. count = count + 1
6. else:
7. print count, " is not less than 5"
Execution
sh-4.3$ python [Link]
Apple
Asus
Dell
Samsung
Iteration (or) Looping (cont..)
• Nested loops statements:
Python programming language allows using one loop inside another loop.
Syntax: Nested for loop
while expression:
while expression:
statement(s)
statement(s)
Example program for Nest ed loops
Program :
#program to explainforloop
list1 = [["john", "Jerry"],[1, 2], ["Paris", "London"]]
for i in list1:
print i
Execution
sh-4.3$ python [Link]
['john', 'Jerry']
[1, 2]
['Paris', 'London']
Iteration (or) Looping (cont..)
• Nested loops statements (cont..):
Example program for Nested loops
Program:
1. #program to show nested loops –for loop within
anotherforloop
2. list1 = [["john", "Jerry"],[1, 2], ["Paris",
"London"]]
3. for i in list1:
4. for x in i:
5. print x
Execution
sh-4.3$ python [Link]
john
Jerry
1
2
Paris
London
Python Break, Continue And Pass Statements
Execution
sh-4.3$ python [Link]
We have 10 number of chocolates
We have 9 number of chocolates
We have 8 number of chocolates
We have 7 number of chocolates
We have 6 number of chocolates
Alarm!!! Chocolate thief
Press enter to exit
Python Break, Continue And Pass Statements
(cont..)
• Continue statement:
The continue statement rejects all the remaining statements in the current
iteration of the loop and moves the control back to the top (begining)of the
loop.
Syntax:
continue;
Flowchart for break statement:
Python Break, Continue And Pass Statements (cont..)
pe
Flowchart for pass statem an
sst:;
Python Break, Continue And Pass Statements (cont..)
Program :
1. #program to explain pass statement
2. for letter in 'hello':
3. if letter == 'o':
4. pass
5. print 'This is pass block'
6. print 'Current Letter :', letter
7. print "Thank you!"
Execution
sh-4.3$ python [Link]
Current Letter : h
Current Letter : e
Current Letter : l
Current Letter : l
This is pass block
Current Letter : o
Thank you!
Fruitful Functions
• Functions that return values are called as fruitful functions.
• The return statement is followed by an expression which is evaluated. Its
result is returned to the caller as the “fruit” of calling this function.
• Simple Example:
Let’s create a mathematical function called add. that takes two numbers as
parameters and return the result of adding two numbers.
Program :
1. # Fruitful function with return statement
2. def add(x,y):
3. sum = x + y
4. return sum
5. a = input("Enter a = ")
6. b = input("Enter b = ")
7. print "Addition of two numbers = ", add(a,b)
Execution
sh-4.3$ python [Link]
Enter a = 2
Enter b = 5
Addition of two numbers = 7
Fruitful Functions (cont...)
• Sometimes it is useful to have multiple return statements, one in
each branch of a conditional statement.
• Code that appears after a return statement is called dead code.
• Example:
Program :
1. # Fruitful function with multiple return statements
2. def original(x):
3. if x < 0:
4. print "This is if"
5. return -x
6. else:
7. return x
8. print "This is else"#Dead code
9. a = input("Enter value = ")
10. print original(a)
Execution
sh-4.3$ python [Link]
Enter value = 9
9
Enter value = -8
This is if
8
Fruitful Functions (cont...)
• Parameters in Fruitful functions:
A function in Python
Takes input data, called parameters or arguments
Performs some computations
Returns the result
A function definition syntax:
function_name(param1, param2);
Parameter is the input data that is sent from one function to
another. The parameters are of two types:
Formal parameters
• This parameter defined as part of the function definition.
• The actual parameter value is received by the formal parameter.
Actual parameters
• This parameter defined in the function call.
Fruitful Functions (cont...)
• Example program:
Program :
1. # Function with actual and formal parameters
2. def cube(x): # x is the formal
parameter
3. return x*x*x
4. a = input("Enter the number = ")
5. b = cube(a) # a is the actual
parameter
6. print "cube of the given number =", b
Execution
sh-4.3$ python [Link]
Enter the number = 2
cube of the given number = 8
Fruitful Functions (cont...)
• Parameter Passing Techniques:
• Two types:
Call by value
a copy of actual arguments is passed to formal arguments and any changes made to the formal
arguments have no effect on the actual arguments.
Call by reference
the address of actual arguments is passed to formal arguments. By accessing the addresses of
formal arguments, it will be reflected in the actual arguments too.
Program :
1. #Python program - call by value example
2. k = 2
3. def sqre(n): # n = 2, value is copied
4. n=n*n #n=2*2=4
5. square = n # square = 4
6. return square
7. j = sqre(k) # value of k =
2 is passed to the function sqre
8. print "Square of the given number =", j
9. print k # k value = 2
Execution
sh-4.3$ python [Link]
Square of the given number = 4
2
Fruitful Functions (cont...)
• Parameter Passing Techniques:
Example Program(Call by value)
Program :
#Python program - call by reference example
1. def change_list(the_list):
2. print 'Inside the Function =', the_list
3. the_list.append('raj')
4. print 'New list inside function = ', the_list
5. my_list = ['john', 'jack', 'atlee']
6. print 'My list before function call =', my_list
7. change_list(my_list)
8. print 'My list after function call =', my_list #call by
reference
Execution
sh-4.3$ python [Link]
My list before function call = ['john', 'jack', 'atlee']
Inside the Function = ['john', 'jack', 'atlee']
New list inside function = ['john', 'jack', 'atlee', 'raj']
My list after function call = ['john', 'jack', 'atlee', 'raj']
Fruitful Functions (cont...)
• Void functions:
It is possible to compose a function without a return statement. Functions
like this are called void functions and they return none.
Program :
1. # Void Function
2. def simple(): #Function definition without
return statement
3. print 'Hello'
4. print 'This is an example for void function'
5. simple() #Function call statement
Execution
sh-4.3$ python [Link]
Hello
This is an example for void function
Fruitful Functions (cont...)
• Scope of the Variable
A variable in the program can be either local variable or global
variable.
A global variable is a variable that is declared in the main program
while a local variable is a variable that is declared within the function.
s = 10 # Here, s is the Global variable
def f1():
s= 55 # Here, s is the Local variable
print s # output = 55
Example:
Program :
# Scope of the variable in the functions
1. def f():
2. s = "Inside function!"
3. print(s)
4. s = "Outside function!"
5. f()
6. print(s)
Execution
sh-4.3$ python [Link]
Inside function!
Outside function!
Fruitful Functions (cont...)
• Composition
When a function is called from within another function, it’s called composition.
If this type of nested function is used, the inner function has its scope only in the
outer function, so it is most often useful when the inner function is being returned
or when it is being passed into another function.
Syntax:
def outer()
def inner(a)
return a;
return inner;
…..
f outer( )
f
Example:
Program :
# Composition of functions
1. def make_adder(x):
2. def add(y):
3. print "Inside inner", x + y
4. return add
5. plus5 = make_adder(5)
6. print (plus5(12))
Execution
sh-4.3$ python [Link]
17
Fruitful Functions (cont...)
• Python Recursive Function:
• A function is recursive if it calls itself and has a termination condition.
• Limitations of recursions:
A recursive function could hold much more memory than a traditional
function as it stores memory every time its called.
• Example – Factorial function using Recursion
The mathematical definition of factorial is: n! = n * (n-1)!,
Example: 3! = 3 x 2 x 1 = 6.
Program :
# Recursive functions
1. def factorial(n):
2. if n == 0:
3. return 1
4. else:
5. return n * factorial(n - 1)
6. num = input("Enter the input = ")
7. print "Factorial of the given number =", factorial(num)
8.
Execution
sh-4.3$ python [Link]
Enter the input = 5
Factorial of the given number = 120
Strings
• A string is a sequence of characters ie., letter, a number, or a backslash.
• Python strings are "immutable" which means they cannot be changed after
they are created.
• The various built-in methods are described below:
Execution
sh-4.3$ python [Link]
Character at location 3 = t
Length of the string = 19
Number of times the given character (m) = 2
Number of times , blank space = 2
Location of the character (p) = 7
Index of the sub string = 7
Join the character : with each character of the string = P:y:t:h:o:n:
:p:r:o:g:r:a:m:m:i:n:g:
Join the empty space with each character of the string = P y t h o n p r o g r a m m i n g
Concatenation of two strings using + symbol = Python programming reg_no:892898!
String in lower case = python programming
String in upper case = PYTHON PROGRAMMING
Title case of the String = Python Programming
Swap the case of the String = pYTHON PROGRAMMING
Capitalize the String reg no. 892898 = Reg_no:892898!
Reverse the String = gnimmargorp nohtyP
Split the String on white space = ['Python', 'programming', '']
Split the String on character m = ['Python progra', '', 'ing ']
Replace old string with new string = Cent OS programming
Replace old string with new string = PythCent OSn prCent OSgramming
Replace old with new string only 1 time = PythCent OSn programming
Maximum characters in the string reg No. 892898 = r
Minimum characters in the string reg No. 892898 = !
Strings (cont..)
• Example program for String Manipulations(cont)
Program :
# String Module
1. import string
2. text = "This is python programming“
3. print "upper", "=>", [Link](text)
4. print "lower", "=>", [Link](text)
5. print "split", "=>", [Link](text)
6. print "join", "=>", [Link]([Link](text), "+")
7. print "replace", "=>", [Link](text, "python", "Java")
8. print "find", "=>", [Link](text, "python"), [Link](text, "Java")
9. print "count", "=>", [Link](text, "n")
Execution
sh-4.3$ python [Link]
upper => THIS IS PYTHON PROGRAMMING
lower => this is python programming
split => ['This', 'is', 'python', 'programming']
join => This+is+python+programming
replace => This is Java programming
find => 8 -1
count => 2
Python Lists
• Python doesn't have a native array data structure, but it
has the list. List is one of the compound data type
available in Python often referred to as sequences.
• A list is created by placing all the items (elements)
inside a square bracket [ ], separated by commas.
• Items in a list need not be of the same data type.
• A list is mutable; it means the contents of the list are
changed.
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "d"]
• Index operator [] is used to access an item in a list.
Index starts from 0. Python allows negative indexing for
its sequences. The index of -1 refers to the last item.
Nested list are accessed using nested indexing.
Python Lists (cont..)
• Sample Program:
Program :
#Simple program for list
1. my_list = ['p','r','o','b','e']
2. print "First item in the List = ", (my_list[0])
3. print "Third item in the List = ",(my_list[2])
4. print "Last item in the List = ",(my_list[-1])
5. # Nested List
6. n_list = ["Happy", [2,0,1,5], ['john',78,17.3,"hi"]]
7. print "2nd item in list 1 = ", n_list[0][1]
8. print "3rd item in list 3 = ", n_list[2][3]
Execution:
sh-4.3$ python [Link]
First item in the List = p
Third item in the List = o
Last item in the List = e
2nd item in list 1 = a
3rd item in list 3 = hi
Python Lists (cont..)
• Basic List Operations:
Lists respond to the + and * operators much like strings; they mean concatenation
and repetition which results is a new list.
Method name Description Syntax
Execution
sh-4.3$ python [Link]
Items in the list = [56, 78, 98, 78]
Reversed items in the list = [78, 98, 78, 56]
Append item in the list = [78, 98, 78, 56, 568]
Insert new item after 1st iem = ['hi', 78, 98, 78, 56, 568]
Number of items 78 is in the list = 2
Length of items in the list = 6
Sort the items in the list = [56, 78, 78, 98, 568, 'hi']
Minimum element in the list = 56
Maximum element in the list = hi
Pop last time in the list = hi
Pop 1st time in the list = 56
Pass by value vs Pass by address
(or)
call by value vs call by reference
• Note:
• Parameters (or) Arguments
Call by value Vs call by reference Contd…