4 IntroToPython-ControlFlowStatements
4 IntroToPython-ControlFlowStatements
Introduction to Python
Control Flow Statements
Kevyn Stefanelli
2023-2024
Additionally, we can include an 'else' statement if we want to execute an operation only when
the same condition is not satisfied.
Furthermore, we can add sequences of 'else if' (known as 'elif' in Python) statements in case we
want to specify different conditions and execute operations only when one of these conditions is
met.
4.1.1 if statement
# Define two variables
a = 4
b = 4
if b>a:
print("b is greater than a")
# it prints the string only if the condition is met!
When using conditional statements, such as 'if', 'elif', and 'else', it is essential to maintain
consistent indentation. Each indented block under these statements represents a separate code
branch. Incorrect or inconsistent indentation can lead to syntax errors or unintended behavior.
4.1.2 else if (elif) statement
# re-define two variables
a= 3
b=3
if b>a:
print("b is greater than a")
elif a==b:
print("b is equal to a")
b is equal to a
if b>a:
print("b is greater than a")
elif a==b:
print("b is equal to a")
else:
print("b is lower than a")
b is lower than a
# and
if a>b and c>a:
print("Great job!")
# or
if a>b or c>b:
print("The 'or' works fine!")
4.1.5 Nested if
Running a if statement into anothor if statement
# define a variable
x=15
if x>10:
print("x is greater than 10")
if x>20:
print("x is also greater than 20")
else:
print("x is greater than 10, but lower than 20")
x is greater than 10
x is greater than 10, but lower than 20
Define a catalogue of four goods (e.g. “Coffee”, “Cappuccino”, “Tea”, and “Hot Water”) and
assign them the relative prices (e.g. 1, 1.50, 0.80, 0.05).
Using the conditional statements, write a function that given a string of character containing one
of the four goods returns its price. If the input is different from those four products the function
returns "Sorry, product not available.".
Try to order a Coffee, a Tea and a Ginseng. (Remember: Python is case sensitive: a ̸=A)
The following table contains a list of groceries which sell tomatoes, potatoes, zucchinis, and
eggplants along with their prices per kg.
• 2 kg of tomatoes;
• 3 kg of potatoes;
• 5 kg of zucchinies;
• 4 kg of Eggplants.
Shops Tomatoes Potatoes Zucchinis Eggplants
TheLaughing 0.99 0.23 0.54 0.34
Tomato
PoorZucchini 0.98 0.28 0.50 0.34
BadApple 1.07 0.17 0.48 0.39
ToPearOrNot 0.93 0.22 0.57 0.33
ToPear
Write a Python function that takes as input a dataframe called Grocery, which is a copy of the
table above, and returns a string containing the name of the cheapest grocery shop.
4.2 Loop
Loops are fundamental constructs in programming that enable the repetition of a set of
instructions multiple times.
• for
• while
The while loop is particularly useful for situations where the exact number of iterations is not
known beforehand, allowing for flexible and responsive programming solutions.
However, careful consideration of the loop's termination condition is essential to avoid potential
infinite loops that can hang or crash a program.
Note: if I don't increment the counter, the while loop never stops!
1
2
3
while i<6:
print(i)
i+=1
else:
print("now, i is not lower than 6")
1
2
3
4
5
now, i is not lower than 6
In this game, you and your friend will take turns guessing a secret number between 1 and 20.
If you guess the correct number, you'll be rewarded with a prize of 10.
But here's the twist: if your guess is off the mark, you'll need to pay a fee of 2.
Let's see who can crack the code and come out on top! Use a while loop to keep the game going
until someone guesses the secret number.
import numpy as np
from numpy import random
# Initialize variables
player_score = 0
guesses = 0
if player_guess == secret_number:
print("Congratulations! You guessed the secret number!")
player_score += 10
break
else:
print("Oops! That's not the right number. Try again.")
player_score -= 2
Unlike the 'while' loop, which operates based on a condition, the 'for' loop follows a
predetermined iteration pattern. It systematically moves through each item in the sequence,
executing a specified block of code for each item. This makes the 'for' loop an ideal choice when
you know the exact number of iterations required.
Python's 'for' loop simplifies the process of handling collections of data, performing repetitive
tasks efficiently, and applying the same operation to each element within the sequence.
soccer
tennis
swimming
for k in a:
print(k)
s
w
i
m
m
i
n
g
# also:
for j in "fencing":
print(j)
f
e
n
c
i
n
g
soccer
Iterate with 'range'
# iterare con range:
for k in range(6): # it goes from 0 to 5
print(k)
0
1
2
3
4
5
2
3
4
5
3
9
15
21
printed 0 /9
printed 1 /9
printed 2 /9
printed 3 /9
printed 4 /9
printed 5 /9
printed 6 /9
printed 7 /9
printed 8 /9
printed 9 /9
The loop is concluded!
Nested for loops
# define two lists
locations = ["beach", "mountain", "countryside"]
accommodations = ["hotel", "residence", "campground", "B&B", "hostel"]
beach hotel
beach residence
beach campground
beach B&B
beach hostel
mountain hotel
mountain residence
mountain campground
mountain B&B
mountain hostel
countryside hotel
countryside residence
countryside campground
countryside B&B
countryside hostel
Note: there are more efficient techniques to execute if-else statements and loops. Those
methods won't be covered in this course to prioritize providing clear and understandable
material.
Example
Calculate the Sum of the First N Numbers
Write a program that asks the user to input a positive integer N. Then, using a for loop, calculate
the sum of the first N positive integers and print the result.
# Calculate the sum of the first N positive integers using a for loop
for number in range(1, N + 1):
sumfirst += number
You have a dictionary of meals and their total calorie counts for each day.
Write a program that calculates and displays your total daily calorie intake for each day of the
week.
# Dictionary of meals and their total calorie counts for each day
meals = {
"Monday": {"Breakfast": 300, "Lunch": 500, "Dinner": 600, "Snack":
150},
"Tuesday": {"Breakfast": 350, "Lunch": 550, "Dinner": 620,
"Snack": 130},
"Wednesday": {"Breakfast": 320, "Lunch": 480, "Dinner": 590,
"Snack": 170},
"Thursday": {"Breakfast": 290, "Lunch": 510, "Dinner": 580,
"Snack": 160},
"Friday": {"Breakfast": 280, "Lunch": 490, "Dinner": 610, "Snack":
140},
"Saturday": {"Breakfast": 330, "Lunch": 520, "Dinner": 560,
"Snack": 180},
"Sunday": {"Breakfast": 310, "Lunch": 540, "Dinner": 570, "Snack":
120}
}
Monday:
Breakfast: 300 calories
Lunch: 500 calories
Dinner: 600 calories
Snack: 150 calories
Total Calories for Monday: 1550 calories
Tuesday:
Breakfast: 350 calories
Lunch: 550 calories
Dinner: 620 calories
Snack: 130 calories
Total Calories for Tuesday: 1650 calories
Wednesday:
Breakfast: 320 calories
Lunch: 480 calories
Dinner: 590 calories
Snack: 170 calories
Total Calories for Wednesday: 1560 calories
Thursday:
Breakfast: 290 calories
Lunch: 510 calories
Dinner: 580 calories
Snack: 160 calories
Total Calories for Thursday: 1540 calories
Friday:
Breakfast: 280 calories
Lunch: 490 calories
Dinner: 610 calories
Snack: 140 calories
Total Calories for Friday: 1520 calories
Saturday:
Breakfast: 330 calories
Lunch: 520 calories
Dinner: 560 calories
Snack: 180 calories
Total Calories for Saturday: 1590 calories
Sunday:
Breakfast: 310 calories
Lunch: 540 calories
Dinner: 570 calories
Snack: 120 calories
Total Calories for Sunday: 1540 calories