Professional Documents
Culture Documents
U18CSI2201 - Unit 2 Course Material 1
U18CSI2201 - Unit 2 Course Material 1
UNIT - II
CO4: Analyze a problem and use appropriate data structures to solve it.(K4,S3)
CO5: Develop python programs to implement various file operations and exception
handling.(K3,S2)
Source of Content
• http://nptel.ac.in
• https://www.edx.org/course/introduction-to
-python-fundamentals-1
• https://www.edx.org/course/computing-in-p
ython-ii-control-structures-0
Grading
Total 100%
CONTROL STATEMENTS
AGENDA
• Introduction
• (conditional) if
• (alternative) if-else
• Nested-if
• (chained conditional) if-elif-else
Decision Making Statements or Control
Statements
Python supports various conditional statements.
They are:
• (conditional) if
• (alternative) if-else
• Nested-if
• (chained conditional) if-elif-else
if statement
It is used to control the flow of execution of the statements and
also to test logically whether the condition is true or false.
Syntax:
if condition :
statement (s)
Output:
Enter a number: 3
3 is a positive number
Exercise
Write a program which prompts a user to enter
the radius of a circle. If the radius is greater than
zero then calculate and print the area and
circumference of the circle.
if-else statement
It is used to execute some statements when the condition is
true and execute some other statements when the condition
is false depending on the logical test.
Syntax:
if condition :
statement 1 (if the condition is true this statement will be executed)
else:
statement 2 (if the condition is false this statement will be executed)
if-else statement
Example:
num = int(input(“Enter a number:”))
if num >= 0:
print("Positive or Zero")
else:
print("Negative number")
Output:
Case 1:
Enter a number: -5
Negative number
Case2:
Enter a number: 3
Positive or Zero
Exercise
1.) Write a program to prompt the user to enter
two numbers. Find the greater number.
if condition 1:
if condition 2:
statement 1
else:
statement 2
else:
if condition 3:
statement 3
else:
statement 4
Nested if statements
Example:
Output:
Case 1:
Enter a number: 5
Positive number
Case 2:
Enter a number: -1
Negative number
Case 3:
Enter a number: 0
Zero
Exercise
• Write a program to check whether a given
year is leap year or not using nested if
statements.
• Write a program to find the greatest of three
numbers using nested if statements.
if-elif-else statements
• When a series of decisions are involved we have to use more
than one if – else statement called as multiple if-elif-else.
• Multiple if-elif-else statements are much faster than a series
of if – else statements, since their structure is exited when
any one of the condition is satisfied.
Syntax:
if (condition_1) :
execute statement_1
elif (condition_2):
execute statement_2
elif (condition_3):
execute statement_3
----------------------
----------------------
elif (condition_n):
execute statement_n
else:
execute statement_x
if-elif-else statements
Example:
x = int(input("Enter x:"))
y = int(input("Enter y:"))
if(x < y):
st= "x is less than y"
elif (x == y):
st= "x is same as y"
else:
st="x is greater than y"
print(st)
Output:
Case 1: Case 2: Case 3:
Enter x: 5 Enter x: 2 Enter x: 5
Enter y: 5 Enter y: 5 Enter y: 3
x is same as y x is less than y x is greater than y
Output:
Four digit
Exercise
• Write a program to prompt a user to read the marks
of five subjects. Calculate the total marks and
percentage of the marks and display the message
according to the range of percentage given in table:
Percentage Message
Per > = 90 Distinction
Per > = 80 && Per < 90 First Class
Per > = 70 && Per < 80 Second Class
Per > = 60 && Per < 70 Third Class
Per < 60 Fail
• Write a program to prompt a user to enter a
day of the week. If the entered day of the
week is between 1 and 7, then display the
respective name of the day.
num=10
if num==20:
print("apple")
print("grapes") Output:
vegetable
print(“vegetable")
Quiz
What will be the output of the following
program?
if (20<1) and (1<-1):
print("Hello")
elif (20>10) or False: Output:
Hi
print('Hi')
else:
print('Bye')
Summary
• Python supports various decision statements,
such as if, if-else, multi-way if-elif-else
statements.
• Python does not have a ternary operator. It
uses a conditional expression instead.
LOOP CONTROL STATEMENTS
Agenda
• while loop
• range( ) function
• for Loop
• Nested Loops
• break statement
• continue statement
• pass statement
The while loop
• It executes a sequence of statements repeatedly as long
as the condition is true.
• Syntax:
while test-condition:
statement(s)
• test-condition is a boolean expression
• Colon(:) must follow the test condition
• The statements within the while loop will be executed till
the condition is true.
• When the condition is false, the execution goes out of
the loop
• Note: All statements within the while block must be
indented with the same number of spaces.
The while loop
• Flowchart for while loop:
The while loop
Example:
Write a program to print the numbers from one
to five using the while loop.
count =0
while count<=5: Output:
count = 0
print("count = ", count) count = 1
count = count + 1 count = 2
count = 3
count = 4
count = 5
The while loop
Example:
Write a program to add 10 consecutive numbers
starting from1 using the while loop.
count =0 Output:
Sum of first 10 Numbers = 55
sum = 0
while count<=10:
sum = sum + count
count = count + 1
print("Sum of first 10 Numbers = ", sum)
Example:
Write a program to print the factorial of a number
using the while loop.
if(c==rev):
print("Palindrome")
else:
Exercise
• Write a program to find the sum of the
digits of a given number.
• Write a program to display the reverse of
the number entered.
• Write a program to check whether the
number entered is an Armstrong number
or not. i.e., 153 = 13 + 53 + 33
The range( ) Function
• range() is a built in function
• Used to generate list of integers
• Has one, two or three parameters
• Last two parameters are optional
• General form:
range(begin, end, step)
begin – first beginning number in the sequence at
which the list starts
end – limit - last number in the sequence
step – difference between each number in the
sequence
Examples of range()
>>>list(range(1,6))
[1, 2, 3, 4, 5]
>>>list(range(1,10,2))
[1, 3, 5, 7, 9]
Example Output
range(1,5) [1, 2, 3, 4]
range(1,20,2) [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
range(5) [0, 1, 2, 3, 4]
range(5,0,-1) [5, 4, 3, 2, 1]
range(5,0,-2) [5, 3, 1]
range(1,10,2) [1, 3, 5, 7, 9]
range(-4,4) [-4, -3, -2, -1, 0, 1, 2, 3]
range(-4,4,2) [-4, -2, 0, 2]
range(0,1) [0]
range(1,1) []empty
range(0) []empty
The for loop
• for loop iterates through a sequence of objects.
• Iterates through each value in a sequence
Syntax:
for var in sequence:
statement(s)
for i in range(1,6): 1
print(i) 2
print("End of the program") 3
4
5
End of the program
Exercise:
Write a program to read a string from the user
and print the string after removing spaces.
Difference between break and continue functions
Break Continue
Exits from current block or Skips the current iteration
loop. and also skips the
remaining statements
within the body.
for i in range(11,16):
if i%2==0:
print('Jack')
Jill and Jack
elif i%3==0:
Jack
print('Jill')
Jill and Jack
elif i%2==0 and i%3==0:
Jack
print('Jack and Jill')
Jill
else:
print('Jill and Jack')
SUMMARY
• Loop is a process of executing a set of
statements for fixed number of times.
• Two types of loop control statements:
– for loop and while loop
• Break statement exits from the current block
or loop.
• Continue statement skips the current iteration
of the loop.
FUNCTIONS
FUNCTIONS
• A function is a self-contained block of one or
more statements that perform a special task
when called.
• Is a group of related statements that perform a
specific task.
• Help break our program into smaller and
modular chunks.
• Make the code more organized and manageable.
• Avoids repetition.
• Makes code reusable.
TYPES OF FUNCTIONS
• Built-in functions - Functions that are built into
Python. Functions that readily come with
Python are called built-in functions.
Eg. abs(), chr()
Function call:
>>> greet('Paul')
Hello, Paul. Good morning!
FUNCTIONS
Example 1:
def display( ): #Function definition
print(“Good morning!")
display() #Function call
Output:
Good morning!
USE OF A FUNCTION – Avoid repetition and code reusability
sum = 0 def sum(x,y):
for i in range(1,26): s=0
sum=sum+i
print("Sum of integers from 1 to 25 is: for i in range(x,y+1):
",sum) s=s+i
print('Sum of integers
sum = 0
for i in range(50,76): from ',x,' to ',y,' is: ',s)
sum=sum+i
print("Sum of integers from 50 to 76 sum(1,25)
is: ",sum) sum(50,75)
sum = 0 sum(90,100)
for i in range(50,101):
sum=sum+i
print("Sum of integers from 50 to 100
is: ",sum)
Example: To find the factorial of a number
def fact(n): Output:
f=1
for i in range(1,n + 1): Enter a number: 5
f=f*i The factorial of 5 is 120
print("The factorial of",n,"is",f)
Enter a number: 8
The factorial of 8 is 40320
num = int(input("Enter a number: "))
fact(num) Enter a number: 10
num = int(input("Enter a number: ")) The factorial of 10 is
fact(num) 3628800
num = int(input("Enter a number: "))
fact(num)
FUNCTIONS
Positional Arguments:
• The parameters are assigned according to their position.
Example:
def display(name,age):
print("name = ", name," age = ",age)
display("John",25)
display(40,"Sachin")
Output:
name = John age = 25
name = 40 age = Sachin
FUNCTIONS
KEYWORD ARGUMENTS
• The parameter name can be used explicitly while calling.
• A keyword can be passed to a function by using its
corresponding parameter name rather than its position.
Example:
def display(name,age):
print("name= ", name," age= ",age)
display(age=40,name="Sachin")
Output:
name= Sachin age= 40
FUNCTIONS
PARAMETER WITH DEFAULT VALUES
• Parameters within a function’s definition can have default
values.
• Default value can be provided by using assignment (=) operator.
Example:
def display(name, age=20):
print("name= ", name," age= ",age)
display("John",25)
display("Sachin")
Output:
name= John age= 25
name= Sachin age= 20
The return statement
• The return statement is used to return a value
from the function.
• Also used to exit a function.
Syntax:
return [expression_list]
• This statement can contain expression which gets
evaluated and the value is returned.
• If there is no expression in the statement or
the return statement itself is not present inside a
function, then the function will return
the None object.
The return statement
Example:
def minimum(a,b):
if a<b:
return a
elif b<a:
return b
else:
return “Both numbers are equal”
print(minimum(100,85))
Output:
85
The return statement
Example:
def absolute_value(num):
if num >= 0:
return num
else:
return –num
print(absolute_value(2))
# Output: 2
print(absolute_value(-4))
# Output: 4
Returning multiple values
• It is possible to return multiple values.
Example 1:
def calc(n1, n2):
return n1+n2, n1-n2
print(calc(20,10))
Output:
(30, 10)
Returning multiple values
• It is possible to return multiple values.
Example 2:
def calc(n1, n2):
return n1+n2, n1-n2
sum,sub = calc(20,10)
print("Sum = ",sum,"Diff = ", sub)
Output:
Sum = 30 Diff = 10
Area of Circle using Functions
def calc(r):
return 3.14*r*r
x = (int(input('Enter the radius:')))
print(' The are of circle is',calc(x)) #X passed as
argument to calc()
Output
Enter the radius:5
78.5
LOCAL AND GLOBAL VARIABLES
• Variables declared inside a function are known as local
variables.
• Variables declared outside a function are known as global
variables.
Example:
def fun( ):
q=10 #local variable
print("q= ",q)
print("p= ",p)
Output:
p= 10
p= 20
Exercise
• Write a program using functions to perform
arithmetic calculations.
• Write a function reverse_number() to return
the reverse of the number entered.
• Write a program using functions to find the
maximum of two numbers.
function reverse_number()
def reverse(n):
rev=0
while(n!=0):
num=n%10
rev=rev*10+num
n=n//10
return(rev)
n=int(input("Enter a number:"))
print(reverse(n))
Output
Enter the number:234
Recursive Functions
• A function is said to be recursive if a statement
within the body of the function
calc_factorial(4)
calls itself.
# 1st call with 4
Example: 4 * calc_factorial(3) # 2nd call with 3
4 * 3 * calc_factorial(2) # 3rd call with 2
4 * 3 * 2 * calc_factorial(1) # 4th call with 1
4*3*2*1 # return from 4th
def calc_factorial(x):
call as
if x == 1: number=1
return 1 4*3*2 # return from 3rd call
4*6 # return from 2nd call
else: 24 # return from 1st call
return (x * calc_factorial(x-1))
num = 4
print("The factorial of", num, "is", calc_factorial(num))
Exercise
• For a quadratic equation in the form of ax2+bx+c,
the discriminant is b2-4ac. Write a function to
compute the discriminant D, that returns the
following output depending on the discriminant
D.
• Write a program using recursion to find the sum
of numbers from 1 to n.
• Write a program to generate the fibonacci
numbers.
• A positive integer is entered through the
keyboard. Write a function factors(num) to
obtain the factors of the given numbers.
Quadratic equation Roots – Using Function
import math
def eval_Quadratic_Equa(a, b ,c, x):
d = (b**2) - 4*a*c
if d < 0:
print('The equation has no real solution')
elif d == 0:
x = (- b + math.sqrt(d))/ (2*a)
print(' This equation has one solution:',x)
else:
x1 = (-b - math.sqrt(d))/(2*a)
x2 = (-b + math.sqrt(d))/(2*a)
print(' Equation has two solutions: ',format(x1,'.2f'),' and ',format(x2,'.2f'))
Find and display the total ticket cost for a group which had
adults and children. Test the program with different input
values for number of adults and children.
Sample Input
Number of adults 5
Number of children 2
Number of adults 3
Number of children 1
Expected Output
return total_ticket_cost
total_ticket_cost=calc_total_ticket_cost(1,2)
print("Total Ticket Cost:",total_ticket_cost)
def calculate_total_ticket_cost(no_of_adults, no_of_children):
total_ticket_cost=0
rate_adult=37550.0
rate_child=37550.0 /3.0
ticket_cost=(no_of_adults*rate_adult)
+(no_of_children*rate_child)
tax=ticket_cost*.07
disc=(ticket_cost+ tax)*0.1
total_ticket_cost=(ticket_cost+ tax)-disc
return total_ticket_cost
a) x is now 50
b) x is now 2
c) x is now 100 d) x is 50
d) x is 50 Changed local x to 2
x is now 50
Changed local x to 2
Quiz
• What is the output of below program?
def say(message, times = 1):
print(message * times)
say('Hello') a) Hello
say('World', 5) WorldWorldWorldWorldWorld
a) Hello
WorldWorldWorldWorldWorld
b) Hello
World 5
c) Hello
World,World,World,World,World
d) Hello
HelloHelloHelloHelloHello
Quiz
What is the output of below program?
def func(a, b=5, c=10):
print('a is', a, 'and b is', b, 'and c is', c)
func(3, 7)
a is 3 and b is 7 and c is 10
func(25, c = 24) a is 25 and b is 5 and c is 24
func(c = 50, a = 100) a is 100 and b is 5 and c is 50
Summary
• A function is a self-contained block.
• A function definition begins with def keyword.
• Arguments can be passed as positional or
keyword arguments.
• A variable must be created before it is used.
• Scope of the variables are based on where they
are defined – local or global.
• The return statement is used to return a value
from a function.
• Functions can return multiple values.
• Python also supports recursive functions.