Control Flow
Control Flow
md 2024-07-23
Download PDF
To access the updated handouts, please click on the following link:
https://yasirbhutta.github.io/python/docs/control-flow.html
if condition:
# code to execute if condition is True
The condition can be any logical expression. If the condition is evaluated to true, the block of statements
is executed. Otherwise, the block of statements is skipped.
Example #:
x = 10
if x > 5:
print('x is greater than 5.')
This code will print the message x is greater than 5. to the console.
You can also use elif statements to check for multiple conditions. The general syntax of the elif statement
is as follows:
1 / 15
control-flow.md 2024-07-23
if condition1:
# code to execute if condition1 is True
elif condition2:
# code to execute if condition2 is True
If the condition for the if statement is evaluated to false, the python interpreter will check the condition
for the first elif statement. If the condition for the elif statement is evaluated to true, the corresponding block
of statements is executed. Otherwise, the python interpreter will check the condition for the next elif
statement, and so on.
Example #1:
x = 3
if x > 5:
print('x is greater than 5.')
elif x < 5:
print('x is less than 5.')
This code will print the message "x is less than 5." to the console.
You can also use an else statement to check for all other conditions. The general syntax of the else statement
is as follows:
if condition1:
# code to execute if condition1 is True
elif condition2:
# code to execute if condition2 is True
else:
# code to execute if none of the conditions are True
If all of the conditions for the if and elseif statements are evaluated to false, the block of statements in the
else statement is executed.
x = 2
if x > 5:
print('x is greater than 5.')
elif x == 5:
print('x is equal to 5.')
else:
print('x is less than 5.')
2 / 15
control-flow.md 2024-07-23
This code will print the message "x is less than 5." to the console.
x = 10
if x < 0:
print("Negative")
elif x == 0:
print("Zero")
else:
print("Positive")
Example #3: Video: How to check if a number is odd or even Example #4: Video: Python Program to Find
Grade of a Student Using if elif else
Example #:
loops
There are two ways to create loops in Python: with the for-loop and the while-loop.
for loop
A for loop in Python is a programming statement that repeats a block of code a fixed number of times.
The for-loop is always used in combination with an iterable object[^1], like a list or a range.
The Python for statement iterates over the members of a sequence in order, executing the block each
time.
Syntax:
iterable is a sequence of elements such as a list, tuple, dictionary, set, or string. item is a variable that takes
on the value of each element in the sequence, one at a time. The code block is executed once for each
element in the sequence.
3 / 15
control-flow.md 2024-07-23
range() function:
We can use the range() function as an iterable in a for loop in Python. The range() function returns a
sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a
specified number.
We can also specify the starting value and the increment value of the sequence using the range()
function. For example, range(2, 10, 2) returns a sequence of numbers starting from 2, incrementing by
2, and ending at 8. read more ...
Question: Write a MATLAB program to print the numbers from 1 to 5, using a for loop.
Example #:
for i in range(6):
print(i)
Example #: Printing "Building the future, one line at a time." 5 Times Using a for Loop
Question: Write a Python program to print the string "Building the future, one line at a time." 5 times, using a
for loop.
Example #:
for i in range(5):
print("Building the future, one line at a time.")
Question: Write a python program to calculate the sum of the first N natural numbers using a for loop.
N = 10
sum = 0
for i in range(1,N+1):
sum = sum + i
print(f"Sum = {sum}")
Question: Write a Python program to display the even numbers from 2 to 10, inclusive, using a for loop.
sum = 0
for i in range(2,11):
if i%2 == 0:
sum +=i
4 / 15
control-flow.md 2024-07-23
print(i)
print(f"Sum of even numbers: {sum}")
A nested loop is a loop inside another loop. It is a powerful programming technique that can be used
to solve a wide variety of problems.
Further reading:
5 / 15
control-flow.md 2024-07-23
while loop
A while loop in python is a control flow statement that repeatedly executes a block of code until a
specified condition is met.
Syntax:
while condition:
# code block
Here, condition is a boolean expression that is evaluated before each iteration of the loop. If the condition is
True, the code block is executed. The loop continues to execute as long as the condition remains True.
Question: Write a Python program to print the numbers from 1 to 10, using a while loop?
Question: Write a Python program to print the string "Hello, world!" 5 times, using a while loop?
i = 1
while i <= 10:
print('Hello, world!')
i += 1
Question: Write a MATLAB program to calculates the sum of the numbers from 1 to 100 using a while loop.
i = 1
sum = 0
print(f'Sum = {sum}');
6 / 15
control-flow.md 2024-07-23
Question: Write a Python program to calculate the sum of the even numbers from 2 to 20 using a while loop.
Question : Write a program that prints the sum of the squares of all the numbers from 1 to 4, using a while
loop.
i = 1
while i < 5:
square = i ** 2
print(f'Square of {i} is {square}')
i += 1
Output:
Square of 1 is 1
Square of 2 is 4
Square of 3 is 9
Square of 4 is 16
Example #:
Question: Write a Python program to prompt the user to enter lines of text until the user enters a blank line.
The program should then display the message "You entered a blank line.".
inputStr = 'Start';
7 / 15
control-flow.md 2024-07-23
Question: Write a Python program to add all the numbers entered by the user until the user enters zero. The
program should display the sum of the numbers.
# While the number entered is not zero, add the number to the sum and prompt the
user to enter another number
while number != 0:
sum += number
number = int(input('Enter another number: ')) # int() Convert string input to
integer
x = 1
while True:
print("To infinity and beyond! We're getting close, on %d now!" % (x))
x += 1
See also:
8 / 15
control-flow.md 2024-07-23
break: Terminates the loop entirely. continue: Skips the current iteration and moves to the next one. pass:
Does nothing, often used as a placeholder.
break
continue
Skips the current iteration and proceeds to the next iteration of the loop.
pass
if condition:
pass # do nothing
Example #:
for x in range(3):
if x == 1:
break
Example #:
for i in range(10):
if i == 5:
break # exit the loop when i is 5
if i % 2 == 0:
continue # skip even numbers
print(i) # print only odd numbers less than 5
9 / 15
control-flow.md 2024-07-23
for x in range(3):
print(x)
else:
print('Final x = %d' % (x))
def get_fruit_color(fruit):
match fruit:
case "apple":
return "red"
case "banana":
return "yellow"
case _:
return "unknown"
Python Challenge to test your knowledge: Quiz1 | Quiz2 | Quiz3 | Quiz4 | Quiz5
Key Terms
for
while
range
pass
else
match
break
continue
f-string
10 / 15
control-flow.md 2024-07-23
1. Apple
2. Banana
3. Cherry
4. Error
for i in range(5):
print(i * 2)
a) 0 1 2 3 4 b) 2 4 6 8 10 c) 10 8 6 4 2 d) 0 2 4 6 8
a) 3 b) 4 c) 1 d) Infinitely
What is the primary purpose of a for loop in Python? a. To define a function b. To iterate over a sequence c. To
create a conditional statement d. To perform mathematical operations
In Python, what does the range() function do when used in a for loop? a. Generates a sequence of numbers b.
Defines a list c. Calculates the average d. Determines the length of a string
How is the syntax for a for loop in Python? a. for x in range(10): b. while x < 10: c. loop for x in 10: d. for x = 0;
x < 10; x++:
In a for loop, what is the role of the loop variable? a. It is used to define the loop b. It holds the result of the
loop c. It is the counter for the loop iterations d. It is optional and can be omitted
Which of the following is the correct way to iterate over elements in a list using a for loop? a. for item in
my_list: b. for i = 0; i < len(my_list): c. for element = my_list: d. for (i, item) in enumerate(my_list):
How can you iterate over both the index and elements of a list using a for loop? a. for i in my_list: b. for (i,
element) in enumerate(my_list): c. for element in range(my_list): d. for index, element in my_list:
11 / 15
control-flow.md 2024-07-23
numbers = [1, 2, 3, 4, 5]
for x in numbers:
print(x * 2)
a. 2 4 6 8 10 b. 1 2 3 4 5 c. 1 4 9 16 25 d. 2 4 8 16 32
while loop
count = 0
while count < 3:
print(count)
count += 1
What will happen if you try to modify the loop variable within the body of a while loop?
(a) The loop will continue as normal. (b) The loop will terminate immediately. (c) The loop may behave
unexpectedly, depending on how the variable is modified. (d) The loop will always run indefinitely.
(a) while (condition): (b) while condition {} (c) while condition: (d) while (condition) {}
x = 10
while x > 0:
print(x)
x -= 2
(a) To execute a block of code if the loop condition is never true. (b) To execute a block of code if the loop
completes without being terminated by a break statement. (c) To execute a block of code if the loop
encounters an error. (d) The else clause cannot be used with a while loop.
if statement:
Which of the following correctly represents the syntax of an if statement in Python? a) if condition { block of
code } b) if(condition) { block of code } c) if condition: block of code
12 / 15
control-flow.md 2024-07-23
What is the syntax for a simple if statement in Python? a. if x == 10: b. for x in range(10): c. while x < 10: d. if (x
== 10) then:
a) To execute a code block when the if condition is True b) To execute a code block when the if condition is
False c) To create an infinite loop d) To define a function
What happens when none of the conditions in an if-elif-else chain are True, and there is no else block?
a) The program raises an error. b) The program executes the first if block. c) The program executes the last elif
block. d) The program does nothing and continues to the next statement.
x = 10
y = 5
if x < y:
print("x is greater than y")
a) "x is greater than y" b) "x is less than y" c) Nothing will be printed d) An error will occur
What happens if none of the conditions in an if-elif chain are True, and there is no else block?
a) The program raises an error b) The program executes the first if block c) The program does nothing and
continues to the next statement d) The program executes the last elif block
a) Indentation is optional b) Indentation is used to define code blocks c) Indentation is four spaces wide d)
Both b and c
number = 10
if number % 2 == 0:
print("Number is even")
else:
print("Number is odd")
Which of the following is the correct way to compare if two variables are equal in an if statement? a. if x
equals 5: b. if x == 5: c. if x = 5: d. if x := 5:
if x > 0:
print("Positive")
elif x < 0:
13 / 15
control-flow.md 2024-07-23
print("Negative")
else:
print("Zero")
a. Prints "Positive" if x is greater than 0, "Negative" if x is less than 0, and "Zero" if x is 0. b. Prints "Positive" if x
is less than 0, "Negative" if x is greater than 0, and "Zero" if x is 0. c. Prints "Positive" if x is 0, "Negative" if x is
greater than 0, and "Zero" if x is less than 0. d. Causes an error because the conditions are conflicting.
Exercises
if statement
Review Questions
for loop:
What is the difference between a for loop and a while loop in Python?
Can you use a for loop to iterate over a string?
if statement:
Which of the following correctly fixes the syntax error in the code below?
if x == 10 # Missing colon
print("x is 10")
A) Remove the comment. B) Add a colon after if x == 10. C) Add parentheses around x == 10. D) Indent
the print statement correctly.
A)
1st_variable = 10
14 / 15
control-flow.md 2024-07-23
B)
if x == 10:
print("x is 10")
C)
print("Hello World!"
D)
15 / 15