0% found this document useful (0 votes)
30 views21 pages

Unit 3

Uploaded by

Manik Rajput
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views21 pages

Unit 3

Uploaded by

Manik Rajput
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

UNIT-III

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 Program Flow Control


Flow control in Python refers to the order in which statements are executed or evaluated in a
Python program. Python provides several flow control mechanisms to manage the execution
of code blocks based on conditions, loops, and function calls.
Python Conditional Statements
If-Else statements in Python are part of conditional statements, which decide the control of
code.
There are situations in real life when we need to make some decisions and based on these
decisions, we decide what we should do next. Similar situations arise in programming also
where we need to make some decisions and based on these decisions we will execute the next
block of code.
Conditional statements in Python languages decide the direction(Control Flow) of the flow
of program execution.
Types of Control Flow in Python
Python control flow statements are as follows:
1. The if statement
2. The if-else statement
3. The nested-if statement
4. The if-elif-else ladder

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

Example of Python if Statement

i = 10

if (i > 15):
print("10 is less than 15")
print("I am Not in if")

Python If-Else Statement


The if statement alone tells us that if a condition is true it will execute a block of statements
and if the condition is false it won’t. But if we want to do something else if the condition is
false, we can use the else statement with the if statement to execute a block of code when the
if condition is false.
Syntax of Python If-Else:
if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false
Flowchart of Python if-else statement

Using Python if-else statement

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

Flowchart of Python Nested if Statement

Example of Python Nested if statement

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")

Python if-elif-else Ladder


Here, a user can decide among multiple options. The if statements are executed from the top
down.
As soon as one of the conditions controlling the if is true, the statement associated with that
if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then
the final “else” statement will be executed.
Syntax:
if (condition):
statement
elif (condition):
statement
.
.
else:
statement
Flowchart of Python if-elif-else ladder

Example of Python if-elif-else ladder


i = 20
if (i == 10):
print("i is 10")
elif (i == 15):
print("i is 15")
elif (i == 20):
print("i is 20")
else:
print("i is not present")

For Loops in Python


Python For loop is used for sequential traversal i.e. it is used for iterating over an iterable
like String, Tuple, List, Set, or Dictionary.

For Loops Syntax

for var in iterable:


# statements
Flowchart of for loop

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

Python For Loop with a step size


This code uses a for loop in conjunction with the range() function to generate a sequence of
numbers starting from 0, up to (but not including) 10, and with a step size of 2. For each
number in the sequence, the loop prints its value using the print() function. The output will
show the numbers 0, 2, 4, 6, and 8.
for i in range(0, 10, 2):
print(i)
Output:
0
2
4
6
8

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

print("Printing list items\


using while loop")
size = len(list1)
# Implement while loop to print list items
while(i < size):
print(list1[i])
i = i+1

i=0

print("Printing list items\


using do while loop")

# Implement do while loop to print list items


while(True):
print(list1[i])
i = i+1
if(i < size and len(list1[i]) < 10):
continue
else:
break

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:

While loop with Boolean values


One common use of boolean values in while loops are to create an infinite loop that can
only be exited based on some condition within the loop.
Example:
In this example, we initialize a counter and then use an infinite while loop (True is always
true) to increment the counter and print its value. We check if the counter has reached a
certain value and if so, we exit the loop using the break statement.
# Initialize a counter
count = 0

# Loop infinitely
while True:
# Increment the counter
count += 1
print(f"Count is {count}")

# Check if the counter has reached a certain value


if count == 10:
# If so, exit the loop
break

# This will be executed after the loop exits


print("The loop has ended.")

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:

# Python program to demonstrate


# break statement

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

print("Out of for loop")


print()

i=0

# Using while loop


while True:
print(s[i])

# break the loop as soon it sees 'e'


# or 's'
if s[i] == 'e' or s[i] == 's':
break
i += 1

print("Out of while loop")


Output:
g
e
Out of for loop

g
e
Out of while loop

Continue Statement in Python


Continue is also a loop control statement just like the break statement. continue statement is
opposite to that of the break statement, instead of terminating the loop, it forces to execute
the next iteration of the loop. As the name suggests the continue statement forces the loop
to continue or execute the next iteration. When the continue statement is executed in the
loop, the code inside the loop following the continue statement will be skipped and the next
iteration of the loop will begin.
Syntax of Continue Statement
The continue statement in Python has the following syntax:
for / while loop:
# statement(s)
if condition:
continue
# statement(s)
Working of Python Continue Statement
The working of the continue statement in Python is depicted in the following flowchart:
Example:
In this example, we will use Python continue statement with for loop to iterate through a
range of numbers and to continue to the next iteration without performing the operation on
that particular element when some condition is met.
# Python program to
# demonstrate continue
# statement

# 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

# No error will be raised


fun()

# 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.

Flowchart of Python Assert Statement

Flowchart of Python Assert Statement

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.

Python assert keyword without error message


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

# using assert to check for 0


print("The value of a / b is : ")
assert b != 0
print(a / b)

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:

Python assert keyword with an error message

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.

# Python 3 code to demonstrate


# working of assert

# initializing number
a=4
b=0

# using assert to check for 0


print("The value of a / b is : ")
assert b != 0, "Zero Division Error"
print(a / b)
Output:
AssertionError: Zero Division Error

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 −

• Take a variable to store the first input number.


• Take another variable to store the second input number(Here the second number should
be 0).
• Divide the first number by the second number and print the result.
Example

The following program returns the runtime error if we divide a number with zero −

# First Input Number


firstNumb = 11
# Second Input Number (Here it is 0)
secondNumb = 0
# Dividing the first Number by the second Number
print(firstNumb/secondNumb)
Output

On executing, the above program will generate the following output −

Traceback (most recent call last):


File "main.py", line 6, in <module>
print(firstNumb/secondNumb)
ZeroDivisionError: division by zero

Because the second number is 0 and no number can be divided by 0, we get a runtime error.

Performing an operation on incompatible types


This error occurs when we perform operations like addition, multiplication, and so on on
incompatible data types.

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

On executing, the above program will generate the following output −

Traceback (most recent call last):


File "main.py", line 6, in <module>
print(inputString + inputNumber)
TypeError: must be str, not int

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 −

# Printing undefined identifier


print(tutorialsPoint)
Output
On executing, the above program will generate the following output −

Traceback (most recent call last):


File "main.py", line 2, in <module>
print(tutorialsPoint)
NameError: name 'tutorialsPoint' is not defined
Because we did not define the tutorialsPoint identifier and are accessing it by printing it, a
runtime error occurs (Name error).

Accessing a list element, dictionary value, or object attribute which doesn’t


exist
This runtime error occurs when we attempt to access a non-existent list,string,dictionary
element/index.

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 −

•Create a list and assign some random values to it.


• Access the list element by index by giving the index that doesn’t exist and printing it.
Example

The following program returns the index error if we access an element out of range −

# input list
inputList =[1, 4, 8, 6, 2]

# printing the element at index 10 of an input list


# throws an IndexError as the index 10 doesn't exist in the input list
print("Element at index 10:", inputList[10])
Output
On executing, the above program will generate the following output −

Traceback (most recent call last):


File "main.py", line 6, in <module>
print("Element at index 10:", inputList[10])
IndexError: list index out of range

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.

You might also like