Python Lecture 3(Conditional Statements)
Python Lecture 3(Conditional Statements)
• 3.1 Introduction
• 3.2.2 if-else,
• 3.2.3 if...elif...else
• 3.5 Summary
• 3.6 References
Lecture Objectives
After reading through this chapter, you will be able to :
• To understand the concepts of python and able to apply it for solving the
complex problems.
INTRODUCTION
• In order to write useful programs, we almost always need the ability to check conditions and
• The Boolean expression after if is called the condition. If it is true, then the indented
INTRODUCTION
• In that case, you can use the pass statement, which does
CONDITIONAL STATEMENTS
• Conditional Statement in Python perform different computations or actions depending on
• Story of Two if’s: Consider the following if statement, coded in a C-like language:
• if p > q: p = 1 q = 2
CONDITIONAL STATEMENTS
• Parentheses are optional
• C-like languages
• x = 1;
• Python language
• x=1
• b = 2;
• print (a + b)
• You can chain together only simple statements, like assignments, prints, and function calls.
CONDITIONAL STATEMENTS
• if statement
• Syntax
• if test expression:
• statement(s)
• Here, the program evaluates the test expression and will execute statement(s)
only if the test expression is True.
• If the test expression is False, the statement(s) is not executed.
• In Python, the body of the if statement is indicated by the indentation. The body
starts with an indentation and the first un-indented line marks the end.
• Python interprets non-zero values as True. None and 0 are interpreted as
False.
Python Programming : Lecture Two
Dr. Khalil Alawdi 9
CONDITIONAL STATEMENTS
• Example: Python if Statement
• # If the number is positive, we print an appropriate message
• num = 3
• if num > 0:
• print (num, "is a positive number.")
• print ("This is always printed.")
• num = -1
• if num > 0:
• print (num, "is a positive number.")
• print ("This is also always printed.")
• When you run the program, the output will be:
• 3 is a positive number.
• This is always printed.
• This is also always printed.
Python Programming : Lecture Two
Dr. Khalil Alawdi 10
CONDITIONAL STATEMENTS
• Example: Python if Statement
• In the previous example, num > 0 is the test expression.
• When the variable num is equal to 3, test expression is true and statements
inside the body of if are executed.
• If the variable num is equal to -1, test expression is false and statements
CONDITIONAL STATEMENTS
• if-else statement
• Syntax
• if test expression:
• Body of if
• else:
• Body of else
• The if...else statement evaluates test expression and will execute the body of if
only when the test condition is True.
• If the condition is False, the body of else is executed. Indentation is used to
separate the blocks.
CONDITIONAL STATEMENTS
• Example of if...else
• # Program checks if the number is positive or negative
• # And displays an appropriate message
• num = 3
• # Try these two variations as well.
• # num = -5
• # num = 0
• if num >= 0:
• print ("Positive or Zero")
• else:
• print ("Negative number")
Python Programming : Lecture Two
Dr. Khalil Alawdi 13
CONDITIONAL STATEMENTS
• Output
• Positive or Zero
• In the pervious example, when num is equal to 3, the test
expression is true and the body of if is executed and the body of
else is skipped.
• If num is equal to -5, the test expression is false and the body of
else is executed and the body of if is skipped.
• If num is equal to 0, the test expression is true and body of if is
executed and body of else is skipped.
CONDITIONAL STATEMENTS
• if...elif...else Statement
• Syntax
• if test expression:
• Body of if
• elif test expression:
• Body of elif
• else:
• Body of else
• The elif is short for else if. It allows us to check for multiple expressions.
• If the condition for if is False, it checks the condition of the next elif block and so on.
• If all the conditions are False, the body of else is executed.
• Only one block among the several if...elif...else blocks is executed according to the condition.
• The if block can have only one else block. But it can have multiple elif blocks.
CONDITIONAL STATEMENTS
• Example of if...elif...else
• '''In this program, we check if the number is positive or negative or zero and display an
appropriate message'''
• num = 3.4
• # Try these two variations as well:
• # num = 0 • When variable num is positive, Positive
• #num = -4.5
number is printed.
• if num > 0:
• print ("Positive number") • If num is equal to 0, Zero is printed.
• elif num == 0:
• print("Zero") • If num is negative, Negative number is p
• else:
• print ("Negative number")
Python Programming : Lecture Two
Dr. Khalil Alawdi 16
CONDITIONAL STATEMENTS
• nested if – else
• We can have a if...elif...else statement inside another if...elif...else
statement.
CONDITIONAL STATEMENTS
• Python Nested if Example
• '''In this program, we input a number check if the number is positive or
negative or zero and display an appropriate message This time we use
nested if statement''‘
• num = float (input ("Enter a number: "))
• if num >= 0:
• if num == 0:
• print("Zero")
• else:
• print ("Positive number")
• else:
• print ("Negative number")
Python Programming : Lecture Two
Dr. Khalil Alawdi 18
CONDITIONAL STATEMENTS
• Output1
• Enter a number: 5
• Positive number
• Output2
• Enter a number: -1
• Negative number
• Output3
• Enter a number: 0
• Zero
LOOPING STATEMENTS
• In general, statements are executed sequentially: The first
LOOPING STATEMENTS
• for loop
• The for loop in Python is used to iterate over a sequence (list, tuple, string) or
other iterable objects. Iterating over a sequence is called traversal(-إحصاء-مسح
مقطع بلك-)مرور.
• Here, val is the variable that takes the value of the item inside the sequence
on each iteration.
• Loop continues until we reach the last item in the sequence. The body of for
loop is separated from the rest of the code using indentation.
Python Programming : Lecture Two
Dr. Khalil Alawdi 21
LOOPING STATEMENTS
• Example: Python for Loop
• # Program to find the sum of all numbers stored in a list
• # List of numbers
• numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
• # variable to store the sum
• sum = 0
• # iterate over the list
• for val in numbers:
• sum = sum+val
• print ("The sum is", sum)
• When you run the program, the output will be:
• The sum is 48
LOOPING STATEMENTS
• The range () function
• We can generate a sequence of numbers using range () function. range (10)
will generate numbers from 0 to 9 (10 numbers).
• We can also define the start, stop and step size as range (start,
stop,step_size). step_size defaults to 1, start to 0 and stop is end of object if
not provided.
• This function does not store all the values in memory; it would be inefficient.
So, it remembers the start, stop, step size and generates the next number on
the go.
• To force this function to output all the items, we can use the function list().
LOOPING STATEMENTS
• The range () function Example
• print(range(10))
• print(list(range(10)))
• print (list (range (2, 8)))
• print (list (range (2, 20, 3)))
• Output:
• range (0, 10)
• [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
• [2, 3, 4, 5, 6, 7]
• [2, 5, 8, 11, 14, 17]
LOOPING STATEMENTS
• The range () function Example
• We can use the range () function in for loops to iterate through a sequence of numbers. It can
be combined with the len () function to iterate through a sequence using indexing.
• Here is an example.
• # Program to iterate through a list using indexing
• city = ['pune', 'mumbai', 'delhi']
• # iterate over the list using index
• for i in range(len(city)):
• print ("I like", city[i])
• Output:
• I like pune
• I like mumbai
• I like delhi
LOOPING STATEMENTS
• for loop with else
• A for loop can have an optional else block as well. The else part is executed if the items in the
sequence used in for loop exhausts.
• The break keyword can be used to stop a for loop. In such cases, the else part is ignored.
• Hence, a for loop's else part runs if no break occurs.
• Example:
• digits = [0, 1, 5]
• for i in digits:
• print(i)
• else:
• print("No items left.")
• When you run the program, the output will be:
• 015
• No items left.
LOOPING STATEMENTS
• for loop with else
• Here, the for loop prints items of the list until the loop exhausts. When the for-loop exhausts, it
executes the block of code in the else and prints No items left.
• This for...else statement can be used with the break keyword to run the else block only when
the break keyword was not executed.
• Example:
• # program to display student's marks from record
• student_name = 'Soyuj'
• marks = {'Ram': 90, 'Shayam': 55, 'Sujit': 77}
• for student in marks:
• if student == student_name:
• print(marks[student])
• break
• else:
• print ('No entry with that name found.')
• Output:
• No entry with that name found.
Python Programming : Lecture Two
Dr. Khalil Alawdi 27
LOOPING STATEMENTS
• while loop
• The while loop in Python is used to iterate over a block of code as long as the test
expression (condition) is true.
• We generally use while loop when we don't know the number of times to iterate
beforehand .
• Syntax of while Loop in Python while test_expression: Body of while
• In the while loop, test expression is checked first. The body of the loop is entered
only if the test_expression evaluates to True.
• After one iteration, the test expression is checked again. This process continues until
the test_expression evaluates to False.
• In Python, the body of the while loop is determined through indentation.
• The body starts with indentation and the first unindented line marks the end.
• Python interprets any non-zero value as True. None and 0 are interpreted as False.
Python Programming : Lecture Two
Dr. Khalil Alawdi 28
LOOPING STATEMENTS
• Example: Python while Loop
• # Program to add natural numbers up to sum = 1+2+3+...+n # To take input from the
user,
• When you run the program, the output will
• # n = int (input ("Enter n: "))
be: Enter n: 10 The sum is 55
• n = 10
• In the above program, the test expression will
• # initialize sum and counter
be True as long as our counter variable i is
• sum = 0 less than or equal to n (10 in our program).
• i=1
• We need to increase the value of the counter
• while i <= n: variable in the body of the loop. This is very
• sum = sum + i important. Failing to do so will result in an
• i = i+1 # update counter infinite loop (never-ending loop).
• # print the sum
• print ("The sum is", sum)
Python Programming : Lecture Two
Dr. Khalil Alawdi 29
LOOPING STATEMENTS
• While loop with else
• Same as with for loops, while loops can also have an optional else block.
• The else part is executed if the condition in the while loop evaluates to False.
• The while loop can be terminated with a break statement. In such cases, the else part is
ignored. Hence, a while loop's else part runs if no break occurs and the condition is false.
• Example: • Output:
• '''Example to illustrate the use of • Inside loop
• else statement with the while loop''' • Inside loop
• counter = 0 • Inside loop
• while counter < 3: • Inside else
• print ("Inside loop") • Here, we use a counter variable to print the string
• counter = counter + 1 Inside loop three times.
• else: • On the fourth iteration, the condition in while
• print ("Inside else") becomes False. Hence, the else part is executed.
Python Programming : Lecture Two
Dr. Khalil Alawdi 30
LOOPING STATEMENTS
• Nested Loops
• Loops can be nested in Python similar to nested loops in other
programming languages.
• Nested loop allows us to create one loop inside another loop.
• It is similar to nested conditional statements like nested if
statement.
• Nesting of loop can be implemented on both for loop and while
loop.
• We can use any loop inside loop for example, for loop can have
while loop in it.
Python Programming : Lecture Two
Dr. Khalil Alawdi 31
LOOPING STATEMENTS
• Nested for loop
• For loop can hold another for loop inside it.
• In above situation inside for loop will finish its execution first and the control will be
returned back to outside for loop.
• Syntax
• for iterator in iterable:
• for iterator2 in iterable2:
• statement(s) of inside for loop
• statement(s) of outside for loop
• In this first for loop will initiate the iteration and later second for loop will start its first
iteration and till second for loop complete its all iterations the control will not be given
to first for loop and statements of inside for loop will be executed.
• Once all iterations of inside for loop are completed then statements of outside for
loop will be executed and next iteration from first for loop will begin.
Python Programming : Lecture Two
Dr. Khalil Alawdi 32
LOOPING STATEMENTS
• Example1: of nested for loop in python
• for i in range (1,11):
• for j in range (1,11):
• m=i*j
• print (m, end=' ')
• print (“Table of “, i)
• Output:
• 1 2 3 4 5 6 7 8 9 10 Table of 1
• 2 4 6 8 10 12 14 16 18 20 Table of 2
• 3 6 9 12 15 18 21 24 27 30 Table of 3
• 4 8 12 16 20 24 28 32 36 40 Table of 4
• 5 10 15 20 25 30 35 40 45 50 Table of 5
• 6 12 18 24 30 36 42 48 54 60 Table of 6
• 7 14 21 28 35 42 49 56 63 70 Table of 7
• 8 16 24 32 40 48 56 64 72 80 Table of 8
• 9 18 27 36 45 54 63 72 81 90 Table of 9
• 10 20 30 40 50 60 70 80 90 100 Table of 10
LOOPING STATEMENTS
• Example 2: of nested for loop in python
• for i in range (10):
• for j in range(i):
• print ("*”, end=' ')
• print (" ")
• Output:
• *
• **
• ***
• ****
• *****
• ******
• *******
• ********
• *********
LOOPING STATEMENTS
• Nested while loop
• While loop can hold another while loop inside it.
• In above situation inside while loop will finish its execution first and the control will be returned back to
outside while loop.
• Syntax
• while expression:
• while expression2:
• statement(s) of inside while loop
• statement(s) of outside while loop
• In this first while loop will initiate the iteration and later second while loop will start its first iteration and
till second while loop complete its all iterations the control will not be given to first while loop and
statements of inside while loop will be executed.
• Once all iterations of inside while loop are completed than statements of outside while loop will be
executed and next iteration from first while loop will begin.
• It is also possible that if first condition in while loop expression is False then second while loop will
never be executed.
LOOPING STATEMENTS
• Example1: Program to show nested while loop
• p=1 • Output:
• while p • 1
• 22
• q=1
• 333
• while q<=p:
• 4444
• print (p, end=" ") • 55555
• q+=1 • 666666
• p+=1 • 7777777
• print (" ") • 88888888
• 999999999
LOOPING STATEMENTS
• Exampleb2: Program to nested while loop
• x=10 • Output:
• while x>1: • 10
• y=10 • 99
• while y>=x: • 888
• print (x, end=" ") • 7777
• y-=1 • 66666
• x-=1 • 555555
• 4444444
• print(" ")
• 33333333
• 222222222
CONTROL STATEMENTS
• Control statements in python are used to control the order of execution of the program based on
the values and logic.
• Python provides us with three types of Control Statements:
• Continue
• Break
• Terminating loops:
• The break statement is used inside the loop to exit out of the loop. It is useful when we want to
terminate the loop as soon as the condition is fulfilled instead of doing the remaining iterations.
• It reduces execution time. Whenever the controller encountered a break statement, it comes out of that
loop immediately.
• Syntax of break statement
• for element in sequence:
• if condition:
• break
Python Programming : Lecture Two
Dr. Khalil Alawdi 38
CONTROL STATEMENTS
• Example of control statement
• for num in range (10):
• if num > 5:
•print ("stop processing.")
• break
• print(num)
• Output:
• 0 1 2 3 4 5 stop processing.
CONTROL STATEMENTS
• skipping specific conditions
• The continue statement is used to skip the current iteration and
continue with the next iteration.
• if condition:
• continue
CONTROL STATEMENTS
• Example of a continue statement
• for num in range (3, 8):
• if num == 5:
• continue
• else:
• print(num)
• Output:
•3
•4
•6
•7
5 SUMMARY
• In this chapter we studied conditional statements like if, if-
else, if- elif-else and nested if-else statements for solving
complex problems in python.
REFERENCES
• Think Python by Allen Downey 1st edition.
• Python Programming for Beginners By Prof. Rahul E. Borate, Dr. Sunil Khilari,
• www.programiz.com
• https://itvoyagers.in
• https://www.softwaretestinghelp.com
• https://pynative.com