0% found this document useful (0 votes)
18 views

Python Lecture 3(Conditional Statements)

Uploaded by

egilhani981
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Python Lecture 3(Conditional Statements)

Uploaded by

egilhani981
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

PYTHON PROGRAMMING

CONDITIONAL STATEMENTS, LOOPING,


CONTROL STATEMENTS
Unit 3: CONDITIONAL STATEMENTS, LOOPING,
CONTROL STATEMENTS

Python Programming : Lecture Two


Dr. Khalil Alawdi 2

Outline of This Lecture


• 3.0 Objectives

• 3.1 Introduction

• 3.2 Conditional Statements:


• 3.2.1 if statement

• 3.2.2 if-else,

• 3.2.3 if...elif...else

• 3.2.4 nested if –else

• 3.3 Looping Statements:


• 3.3.1 for loop

• 3.3.2 while loop

• 3.3.3 nested loops

• 3.4 Control statements:


• 3.4.1 Terminating loops

• 3.4.2 skipping specific conditions

• 3.5 Summary

• 3.6 References

• 3.7 Unit End Exercise


Python Programming : Lecture Two
Dr. Khalil Alawdi 3

Lecture Objectives
After reading through this chapter, you will be able to :

• To understand and use the conditional statements in python.

• To understand the loop control in python programming.

• To understand the control statements in python.

• To understand the concepts of python and able to apply it for solving the

complex problems.

Python Programming : Lecture Two


Dr. Khalil Alawdi 4

INTRODUCTION
• In order to write useful programs, we almost always need the ability to check conditions and

change the behavior of the program accordingly.

• Conditional statements give us this ability.

• The simplest form is the if statement: if x > 0: print 'x is positive'

• The Boolean expression after if is called the condition. If it is true, then the indented

statement gets executed. If not, nothing happens.

• if statements have the same structure as function definitions: a header followed by an

indented body. Statements like this are called compound statements.

Python Programming : Lecture Two


Dr. Khalil Alawdi 5

INTRODUCTION

• There is no limit on the number of statements that can

appear in the body, but there has to be at least one.

• Occasionally, it is useful to have a body with no statements.

• In that case, you can use the pass statement, which does

nothing. if x < 0: pass # need to handle negative values!

Python Programming : Lecture Two


Dr. Khalil Alawdi 6

CONDITIONAL STATEMENTS
• Conditional Statement in Python perform different computations or actions depending on

whether a specific Boolean constraint evaluates to true or false.

• Conditional statements are handled by IF statements in Python.

• Story of Two if’s: Consider the following if statement, coded in a C-like language:

• if (p > q) { p = 1; q = 2; } Now, look at the equivalent statement in the Python language:

• if p > q: p = 1 q = 2

• what Python adds

• what Python removes

Python Programming : Lecture Two


Dr. Khalil Alawdi 7

CONDITIONAL STATEMENTS
• Parentheses are optional

• if (x < y) ---> if x < y 2)

• End-of-line is end of statement:

• C-like languages
• x = 1;

• Python language

• x=1

• End of indentation is end of block

• Why Indentation Syntax?

• A Few Special Cases


• a = 1;

• b = 2;

• print (a + b)

• You can chain together only simple statements, like assignments, prints, and function calls.

Python Programming : Lecture Two


Dr. Khalil Alawdi 8

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.

• The body of if is executed only if this evaluates to True.

• 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

inside the body of if are skipped.

• The print() statement falls outside of the if block (unindented). Hence, it is


executed regardless of the test expression.
Python Programming : Lecture Two
Dr. Khalil Alawdi 11

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.

Python Programming : Lecture Two


Dr. Khalil Alawdi 12

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.

Python Programming : Lecture Two


Dr. Khalil Alawdi 14

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.

Python Programming : Lecture Two


Dr. Khalil Alawdi 15

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.

• This is called nesting in computer programming.

• Any number of these statements can be nested inside one another.

• Indentation is the only way to figure out the level of nesting.

• They can get confusing, so they must be avoided unless necessary

Python Programming : Lecture Two


Dr. Khalil Alawdi 17

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

Python Programming : Lecture Two


Dr. Khalil Alawdi 19

LOOPING STATEMENTS
• In general, statements are executed sequentially: The first

statement in a function is executed first, followed by the second, and


so on. There may be a situation when you need to execute a block
of code several number of times.

• Programming languages provide various control structures that

allow for more complicated execution paths.

• A loop statement allows us to execute a statement or group of

statements multiple times.


Python Programming : Lecture Two
Dr. Khalil Alawdi 20

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(-‫إحصاء‬-‫مسح‬
‫مقطع بلك‬-‫)مرور‬.

• Syntax of for Loop


• for val in sequence:
• Body of for

• 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

Python Programming : Lecture Two


Dr. Khalil Alawdi 22

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().

Python Programming : Lecture Two


Dr. Khalil Alawdi 23

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]

Python Programming : Lecture Two


Dr. Khalil Alawdi 24

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

Python Programming : Lecture Two


Dr. Khalil Alawdi 25

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.

Python Programming : Lecture Two


Dr. Khalil Alawdi 26

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

Python Programming : Lecture Two


Dr. Khalil Alawdi 33

LOOPING STATEMENTS
• Example 2: of nested for loop in python
• for i in range (10):
• for j in range(i):
• print ("*”, end=' ')
• print (" ")
• Output:
• *
• **
• ***
• ****
• *****
• ******
• *******
• ********
• *********

Python Programming : Lecture Two


Dr. Khalil Alawdi 34

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.

Python Programming : Lecture Two


Dr. Khalil Alawdi 35

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

Python Programming : Lecture Two


Dr. Khalil Alawdi 36

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

Python Programming : Lecture Two


Dr. Khalil Alawdi 37

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.

Python Programming : Lecture Two


Dr. Khalil Alawdi 39

CONTROL STATEMENTS
• skipping specific conditions
• The continue statement is used to skip the current iteration and
continue with the next iteration.

• Syntax of continue statement:

• for element in sequence:

• if condition:
• continue

Python Programming : Lecture Two


Dr. Khalil Alawdi 40

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

Python Programming : Lecture Two


Dr. Khalil Alawdi 41

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.

• More focuses on loop control in python basically two types


of loops available in python like while loop, for loop and
nested loop.
• Studied how to control the loop using break and continue
statements in order to skipping specific condition and
terminating loops.
Python Programming : Lecture Two
Dr. Khalil Alawdi 42

UNIT END EXERCISE

Python Programming : Lecture Two


Dr. Khalil Alawdi 43

UNIT END EXERCISE

Python Programming : Lecture Two


Dr. Khalil Alawdi 44

REFERENCES
• Think Python by Allen Downey 1st edition.

• Python Programming for Beginners By Prof. Rahul E. Borate, Dr. Sunil Khilari,

Prof. Rahul S. Navale.

• www.programiz.com

• https://itvoyagers.in

• https://www.softwaretestinghelp.com

• https://pynative.com

Python Programming : Lecture Two

You might also like