Unit 3
Unit 3
1. Python Program Flow Control: Conditional blocks using if, else and elif
2. Simple for loops in python
3. For loop
4. While and do while loop in python
5. Loop manipulation using pass
6. Continue
7. Break and else
8. Assert statement
9. Introduction of run time error handling
Python if statement
The if statement is the most simple decision-making statement. It is used to decide whether
a certain statement or block of statements will be executed or not.
Syntax:
if condition:
# Statements to execute if
# condition is true
Here, the condition after evaluation will be either true or false. if the statement accepts
boolean values – if the value is true then it will execute the block of statements below it
otherwise not.
Flowchart of Python if statement
i = 10
if (i > 15):
print("10 is less than 15")
print("I am Not in if")
The block of code following the else statement is executed as the condition present in the if
statement is false after calling the statement which is not in the block(without spaces).
i = 20
if (i < 15):
print("i is smaller than 15")
print("i'm in if Block")
else:
print("i is greater than 15")
print("i'm in else Block")
print("i'm not in if and not in else Block")
Nested-If Statement in Python
A nested if is an if statement that is the target of another if statement. Nested if statements
mean an if statement inside another if statement.
Syntax:
if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here
i = 10
if (i == 10):
# First if statement
if (i < 15):
print("i is smaller than 15")
# Nested - if statement
# Will only be executed if statement above
# it is true
if (i < 12):
print("i is smaller than 12 too")
else:
print("i is greater than 15")
Here the iterable is a collection of objects like lists, and tuples. The indented statements
inside the for loops are executed once for each item in an iterable. The variable var takes
the value of the next item of the iterable each time through the loop.
Examples of Python For Loop
This code uses a for loop to iterate over a list of strings, printing each item in the list on a
new line. The loop assigns each item to the variable I and continues until all items in
the list have been processed.
l = ["riya", "kukreti", 10]
for i in l:
print(i)
output:
riya
kukreti
10
Python For Loop in Python String
This code uses a for loop to iterate over a string and print each character on a new line. The
loop assigns each character to the variable i and continues until all characters in the string
have been processed.
print("Hello World")
s = "Riya"
for i in s:
print(i)
output:
Hello world
R
i
y
a
Do while loop
Do while loop is a type of control looping statement that can run any statement until the
condition statement becomes false specified in the loop. In do while loop the statement runs
at least once no matter whether the condition is false or true.
Syntax of do while loop:
do{
// statement or
// set of statements
}
while(condition)
Examples of do while loop in Python :
Example 1 :
In this example, we are going to implement the do-while loop in Python using the while loop
and if statement in Python and comparing the while loop with the do-while loop in python.
# defining list of strings
list1 = ["riya", "C++",
"Java", "Python", "C", "MachineLearning"]
# initialises a variable
i=0
i=0
Output: The while is printing the items in the list. The Do while loop is having two
conditions for terminating.
The pointer of the list reached its last+1 position and any element of the list index having
length >=10. In this code output, we can see that-
The Do While loop is terminated, because the condition len(list1[5])<10 is not fulfilling.
Printing list items using while loop
riya
C++
Java
Python
C
MachineLearning
Printing list items using do while loop
riya
C++
Java
Python
C
Python While Loop
Python While Loop is used to execute a block of statements repeatedly until a given
condition is satisfied. When the condition becomes false, the line immediately after the loop
in the program is executed.
Syntax of while loop in Python
while expression:
statement(s)
Flowchart of Python While Loop
While loop falls under the category of indefinite iteration. Indefinite iteration means that
the number of times the loop is executed isn’t specified explicitly in advance.
Statements represent all the statements indented by the same number of character spaces after
a programming construct are considered to be part of a single block of code. Python uses
indentation as its method of grouping statements. When a while loop is executed, expr is first
evaluated in a Boolean context and if it is true, the loop body is executed. Then the expr is
checked again, if it is still true then the body is executed again and this continues until the
expression becomes false.
Python While Loop
In this example, the condition for while will be True as long as the counter variable (count)
is less than 3.
# Python program to illustrate
# while loop
count = 0
while (count < 3):
count = count + 1
print("riya")
output:
riya
riya
riya
While loop with else: while loop executes the block until a condition is satisfied. When
the condition becomes false, the statement immediately after the loop is executed. The else
clause is only executed when your while condition becomes false. If you break out of the
loop, or if an exception is raised, it won’t be executed.
Note: The else block just after for/while is executed only when the loop is NOT terminated
by a break statement.
# Python program to demonstrate
# while-else loop
i=0
while i < 4:
i += 1
print(i)
else: # Executed because no break in for
print("No Break\n")
i=0
while i < 4:
i += 1
print(i)
break
else: # Not executed as there is a break
print("No Break")
Output
1
2
3
4
No Break
1
Sentinel Controlled Statement
In this, we don’t use any counter variable because we don’t know how many times the loop
will execute. Here user decides how many times he wants to execute the loop. For this, we
use a sentinel value. A sentinel value is a value that is used to terminate a loop whenever a
user enters it, generally, the sentinel value is -1.
Python while loop with user input
Here, It first asks the user to input a number. if the user enters -1 then the loop will not
execute, i.e.
• The user enters 6 and the body of the loop executes and again asks for input
• Here user can input many times until he enters -1 to stop the loop
• User can decide how many times he wants to enter input
a = int(input('Enter a number (-1 to quit): '))
while a != -1:
a = int(input('Enter a number (-1 to quit): '))
Output:
# Loop infinitely
while True:
# Increment the counter
count += 1
print(f"Count is {count}")
output:
Count is 1
Count is 2
Count is 3
Count is 4
Count is 5
Count is 6
Count is 7
Count is 8
Count is 9
Count is 10
The loop has ended.
break, continue and pass in Python
Using loops in Python automates and repeats the tasks in an efficient manner. But
sometimes, there may arise a condition where you want to exit the loop completely, skip an
iteration or ignore that condition. These can be done by loop control statements. Loop
control statements change execution from their normal sequence. When execution leaves a
scope, all automatic objects that were created in that scope are destroyed. Python supports
the following control statements:
• Break statement
• Continue statement
• Pass statement
Break Statement in Python
The break statement in Python is used to terminate the loop or statement in which it is
present. After that, the control will pass to the statements that are present after the break
statement, if available. If the break statement is present in the nested loop, then it
terminates only those loops which contain the break statement.
Syntax of Break Statement
The break statement in Python has the following syntax:
for / while loop:
# statement(s)
if condition:
break
# statement(s)
# loop end
Working on Python Break S
Working on Python Break Statement
The working of the break statement in Python is depicted in the following flowchart:
s = 'geeksforgeeks'
# Using for loop
for letter in s:
print(letter)
# break the loop as soon it sees 'e'
# or 's'
if letter == 'e' or letter == 's':
break
i=0
g
e
Out of while loop
# loop from 1 to 10
for i in range(1, 11):
# If i is equals to 6,
# continue to next iteration
# without printing
if i == 6:
continue
else:
# otherwise print the value
# of i
print(i, end = " ")
Output:
1 2 3 4 5 7 8 9 10
Pass Statement in Python
As the name suggests pass statement simply does nothing. The pass statement in Python is
used when a statement is required syntactically but you do not want any command or code
to execute. It is like a null operation, as nothing will happen if it is executed. Pass
statements can also be used for writing empty loops. Pass is also used for empty control
statements, functions, and classes.
Syntax of Pass Statement
The pass statement in Python has the following syntax:
function/ condition / loop:
pass
Example:
In this example, we will use the pass statement with an empty for loop and an
empty Python function. We just declared a function and write the pass statement in it.
When we try to call this function, it will execute and not generate an error.
Then we use the pass statement with an if condition within a for loop. When the value of
“i” becomes equal to ‘k’, the pass statement did nothing, and hence the letter ‘k’ is printed.
# Python program to demonstrate
# pass statement
s = "geeks"
# Empty loop
for i in s:
# No error will be raised
pass
# Empty function
def fun():
pass
# Pass statement
for i in s:
if i == 'k':
print('Pass executed')
pass
print(i)
Output:
g
e
e
Pass executed
k
s
Python assert keyword
Python Assertions in any programming language are the debugging tools that help in the
smooth flow of code. Assertions are mainly assumptions that a programmer knows or always
wants to be true and hence puts them in code so that failure of these doesn’t allow the code
to execute further.
Assert Keyword in Python
In simpler terms, we can say that assertion is the boolean expression that checks if the
statement is True or False. If the statement is true then it does nothing and continues the
execution, but if the statement is False then it stops the execution of the program and throws
an error.
In Python, the assert keyword helps in achieving this task. This statement takes as input a
boolean condition, which when returns true doesn’t do anything and continues the normal
flow of execution, but if it is computed to be false, then it raises an AssertionError along with
the optional message provided.
Parameters:
• condition : The boolean condition returning true or false.
• error_message : The optional argument to be printed in console in case of
AssertionError
Returns: Returns AssertionError, in case the condition evaluates to false along with the
error message which when provided.
Output:
The value of a / b is :
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
Input In [19], in <cell line: 10>()
8 # using assert to check for 0
9 print("The value of a / b is : ")
---> 10 assert b != 0
11 print(a / b)
AssertionError:
This code is trying to demonstrate the use of assert in Python by checking whether the
value of b is 0 before performing a division operation. a is initialized to the value 4, and b is
initialized to the value 0. The program prints the message “The value of a / b is: “.The
assert statement checks whether b is not equal to 0. Since b is 0, the assert statement fails
and raises an AssertionError with the message “Zero Division Error”.
Since an exception is raised by the failed assert statement, the program terminates and does
not continue to execute the print statement on the next line.
# initializing number
a=4
b=0
Runtime Errors
• A runtime error in a program is one that occurs after the program has been successfully
compiled.
• The Python interpreter will run a program if it is syntactically correct (free of syntax
errors). However, if the program encounters a runtime error - a problem that was not
detected when the program was parsed and is only revealed when a specific line is
executed - it may exit unexpectedly during execution. When a program crashes due to
a runtime error, we say it has crashed
Some examples of Python Runtime errors
• division by zero
• performing an operation on incompatible types
• using an identifier that has not been defined
• accessing a list element, dictionary value, or object attribute which doesn’t exist
• trying to access a file that doesn’t exist
Division by zero
If we divide any number by zero, we get this error.
Algorithm (Steps)
Following are the Algorithm/steps to be followed to perform the desired task −
The following program returns the runtime error if we divide a number with zero −
Because the second number is 0 and no number can be divided by 0, we get a runtime error.
Algorithm (Steps)
Following are the Algorithm/steps to be followed to perform the desired task −
• Take a string and assign some random value to it and store it in a variable.
• Take an integer and assign some random integer value to it and store it in another
variable.
• Perform some operations such as addition on the above variables and print it.
Example
The following program returns the runtime error if we perform operation on incompatible data
types −
# Input string
inputString = "TutorialsPoint"
# Input Number
inputNumber = 11
# Adding both integer and string values
print(inputString + inputNumber)
Output
We can't add an integer to the string data type here, so we get a type error (runtime error).
Using an identifier that has not been defined
This error occurs when we attempt to access an identifier that has not been declared previously.
Example
The following program returns the runtime error if we are using undefined identifier −
When we attempt to use an index that does not exist or is too large, it throws an IndexError.
Algorithm (Steps)
Following are the Algorithm/steps to be followed to perform the desired task −
The following program returns the index error if we access an element out of range −
# input list
inputList =[1, 4, 8, 6, 2]
There are 5 elements in the list, and we are attempting to access the 10th index, which does not
exist, resulting in an index error.