Presentation 3
Presentation 3
In Python programming, flow control is the order in which statements or blocks of code are executed at runtime
based on a condition.
1. Conditional statements
2. Iterative statements.
3. Transfer statements
Python Introduction
Python Control Flow Statements and Loops
2. Iterative statements.
for
Syntax of for loop
for i in range/sequencee:
i is the iterating variable,
statement 1
statement 2 range specifies how many times the loop should run.
statement n
• In each iteration of the loop, the variable i get the current value
Example
for num in range(10):
print(num)
Python Introduction
Python Control Flow Statements and Loops
2. Iterative statements.
for
for loop with range()
The range() function returns a
sequence of numbers starting
from 0 (by default) if the
initial limit is not specified
and it increments by 1 (by
default) until a final limit is
reached
sum = 0
for i in range(2, 22, 2):
sum = sum + i
print(sum)
Python Introduction
Python Control Flow Statements and Loops
Python for loop
2. Iterative statements.
for loop with Tuple
A tuple is similar to a list but is immutable. You can loop through it in the same way as a list.
my_tuple = (10, 20, 30, 40, 50) ; for item in my_tuple: ;print(item)
A set is an unordered collection of unique items. You can loop through a set just like a list or tuple.
my_set = {100, 200, 300, 400, 500} ;for item in my_set: ;print(item)
Note:
The loop runs till it reaches the last element in the
sequence. If it reaches the last element in the
sequence, it exits the loop. otherwise, it keeps on
executing the statements present under the loop’s
body
Python Introduction
Python Control Flow Statements and Loops
• Definite Iteration: When we know how many times we wanted to run a loop, then we use count-controlled
loops such as for loops. It is also known as definite iteration. For example, Calculate the percentage of 50
students. here we know we need to iterate a loop 50 times (1 iteration for each student).
• Reduces the code’s complexity: Loop repeats a specific block of code a fixed number of times. It reduces
the repetition of lines of code, thus reducing the complexity of the code. Using for loops and while loops
we can automate and repeat tasks in an efficient manner.
• Loop through sequences: used for iterating over lists, strings, tuples, dictionaries, etc., and perform
various operations on it, based on the conditions specified by the user.
Python Introduction
Python Control Flow Statements and Loops
num = [1, 4, 5, 3, 7, 8]
for i in num:
# calculate multiplication in future if required
pass
Python Introduction
Python Control Flow Statements and Loops
In this example, we are printing the first 5 numbers, and for i in range(1, 6):
after successful execution of a loop, the interpreter will print(i)
execute the else block. else:
print("Done")
Python Introduction
Python Control Flow Statements and Loops
• In nested loops, the inner loop finishes all of its iteration for each iteration of the outer loop
rows = 6
# outer loop
for i in range(0, rows ):
*
# inner loop
* *
* * * for j in range(1, i + 1):
* * * *
print("*", end=" ")
* * * * *
print('')
Python Introduction
Python Control Flow Statements and Loops
# outer loop
for i in range(1, 6):
print('Multiplication table of:', i)
count = 1
# inner loop to print multiplication table of current number
while count < 11:
print(i * count, end=' ')
count = count + 1
print('\n')
Python Introduction
Python Control Flow Statements and Loops
Example: Print the even numbers by adding 1 to the odd numbers in the list
odd = [1, 5, 7, 9]
even = [i + 1 for i in odd if i % 2 == 1]
print(even)
Python Introduction
Python Control Flow Statements and Loops
In Python, Using the input() function, we take input from a user, and using the print() function,
we display output on the screen. Using the input() function, users can give any information to
the application in the strings or numbers format.
• There are different types of input devices we can use to provide data to application.
For example: –
• Stems from the keyboard: User entered some value using a keyboard.
• Using mouse click or movement: The user clicked on the radio button or some drop-down
list and chosen an option from it using mouse.
Python Introduction
Python Input: Take Input from User
• The prompt argument is optional. The prompt argument is used to display a message to the user.
For example, the prompt is, “Please enter your name.”
• When the input() function executes, the program waits until a user enters some value.
• Next, the user enters some value on the screen using a keyboard.
• Finally, The input() function reads a value from the screen, converts it into a string, and returns it
to the calling program.
Note: If you enter an integer or float number, still, it will convert it into a string.
Python Introduction
Python Control Flow Statements and Loops
2. Iterative statements. Python while loop
• The while loop statement repeatedly executes a code block while a particular condition is true.
count = 1
# condition: Run loop till count is less than 3
while count < 3:
print(count)
count = count + 1
• We use a while loop when the number of iteration is not known beforehand. For example, if you want to ask
a user to guess your luck number between 1 and 10, we don’t know how many attempts the user may need
to guess the correct number. In such cases, use a while loop.
• when number of iteration is not fixed always use the while loop.
Python Introduction
Python Control Flow Statements and Loops
2. Iterative statements. Python while loop
Python Introduction
Python Control Flow Statements and Loops
2. Iterative statements. Python while loop
Syntax for while loop
while condition:
# Block of statement(s)
• The while statement checks the condition. The condition must return a boolean value. Either True or False.
• Next, If the condition evaluates to true, the while statement executes the statements present inside its block.
• The while statement continues checking the condition in each iteration and keeps executing its block until the
condition becomes false.
count = 1
# run loop till count is less than 5
while count < 5:
print(count)
count = count + 1
Note: The loop with continuing forever if you forgot to increment counter in the above example
Python Introduction
Python Control Flow Statements and Loops
2. Iterative statements. Python while loop
Syntax for while loop
while condition:
# Block of statement(s)
• The while statement checks the condition. The condition must return a boolean value. Either True or False.
• Next, If the condition evaluates to true, the while statement executes the statements present inside its block.
• The while statement continues checking the condition in each iteration and keeps executing its block until the
condition becomes false.
count = 1
# run loop till count is less than 5
while count < 5:
print(count)
count = count + 1
Note: The loop with continuing forever if you forgot to increment counter in the above example
Python Introduction
Python Control Flow Statements and Loops
2. Iterative statements. Python while loop
Example:
count = 0
number = 180
while number > 10:
# divide number by 3
number = number / 3
# increase count
count = count + 1
print('Total iteration required', count)
• Automate and repeat tasks.: As we know, while loops execute blocks of code over and over again
until the condition is met it allows us to automate and repeat tasks in an efficient manner.
• Indefinite Iteration: The while loop will run as often as necessary to complete a particular task.
When the user doesn’t know the number of iterations before execution, while loop is used
instead of a for loop
count = 0
number = 180
while number > 10:
# divide number by 3
number = number / 3
# increase count
count = count + 1
print('Total iteration required', count)
Python Introduction
Python Control Flow Statements and Loops
2. Iterative statements. Python while loop
Why and When to Use while Loop in Python
• Reduce complexity: while loop is easy to write. using the loop, we don’t need to write the
statements again and again. Instead, we can write statements we wanted to execute again and
again inside the body of the loop thus, reducing the complexity of the code
• Infinite loop: If the code inside the while loop doesn’t modify the variables being tested in the
loop condition, the loop will run forever.
• Break Statement
• Continue Statement
• Pass Statement
Python Introduction
Python Control Flow Statements and Loops
2. Iterative statements. Python while loop
Nested while loops while loop inside a while loop
while expression:
while expression:
statemen(s) of inner loop
statemen(s) of outer loop
for loop inside a while loop We can also use for loop inside a while loop as a nested loop.
i = 1
# outer while loop
while i < 5:
# nested for loop
for j in range(1, i + 1):
print("*", end=" ")
print('')
i = i + 1
Python Introduction
Python Control Flow Statements and Loops
2. Iterative statements. Python while loop
Else statement in while loop
In Python, we can use the else block in the while loop, which will be executed when the loop
terminates normally. Defining the else block with a while loop is optional.
A reverse loop means an iterating loop in the backward direction. A simple example includes:
• Display numbers from 10 to 1.
• Reverse a string or list
• Built-in function
The functions which are come along with Python itself are called a built-in
function or predefined function. Some of them are listed below.
Creating a Function
• function_name: Function name is the name of the function. We can give any name to function.
• parameter: Parameter is the value passed to the function. We can pass any number of parameters. Function
body uses the parameter’s value to perform an action
• function_body: The function body is a block of code that performs some task. This block of code is nothing
but the action you wanted to accomplish.
• return value: Return value is the output of the function.
Note: While defining a function, we use two keywords, def (mandatory) and return (optional).
Python Introduction
Python Functions
Types of Functions
• User-defined function
# call function
course_func('John', 'Python')
Python Introduction
Python Functions
• User-defined function
Creating a function with parameters and return value
# function
def calculator(a, b):
add = a + b
# return the addition
return add
# call function
# take return value in variable
res = calculator(20, 5)
• User-defined function
Calling a function
• Once we defined a function or finalized structure, we can call that function by using its name.
• We can also call that function from another function or program by importing it.
# function
def even_odd(n):
# check numne ris even or odd
if n % 2 == 0:
print('Even number')
else:
print('Odd Number')
• User-defined function
Calling a function of a module
• You can take advantage of the built-in module and use the functions defined in it.