5. If-statements#

5.1. if…#

Sometimes in your program you need to execute a block of code only if a condition is satisfied (is true). You can do this using if statement. Here is how:

if condition:

\(\qquad\) statement(s) (for when condition is true)

temp = 27 #temperature

if temp >= 25:
  print("Time to go to the beach!")
  print("Not to read a Python tutorial!")

print("Done!")
Time to go to the beach!
Not to read a Python tutorial!
Done!
location = "Amsterdam"      # the name of your location

if location == "Amsterdam":
  print("Welcome to Amsterdam!")

print("Enjoy your stay!")
Welcome to Amsterdam!
Enjoy your stay!

Note that:

  1. as a condition you can use the comparison operators discussed in section 2.2. Operators.

  2. you have to use a colon : after the condition.

  3. by using indentation* we highlight a block of code in Python. All statements with the same distance to the left belong to the if-statement.

* Indentation in Python refers to the spaces or tabs that are used at the beginning of a line of code to indicate its level of indentation within a block of code. In other words, it’s how you organize and group your code together.

Now set temp=15 and run the code again. What do you see?

5.2. if…else#

Sometimes you need to execute one block of code only if a condition is satisfied (is true) and execute another block of code if the condition is not true. To do so, you can combine an “if-statement” with an “else-statement” to create an “if-else-statement”.

if condition:

\(\qquad\) statement(s) for when condition is true

else:

\(\qquad\) statement(s) for when condition is false

# Example: checking if a number is odd or even
num = 33
if num % 2 == 0:       # % = modulus (the remainder after dividing one number by another) e.g = 13%5 = 3, 12%4 = 0
  print ("num is even")
else:
  print ("num is odd")
num is odd

5.3. if…elif…else#

You can have more than one condition in an if-statement. This can be done by using elif statements. Note that the conditions will be checked in order of appearance; and once one condition is true, the rest will be ignored.

if  condition1 :

\(\qquad\) statement(s) for when condition 1 is true

elif condition2 :

\(\qquad\)  statement(s) for when condition 1 is false but condition 2 is true

else:

\(\qquad\) statement(s) for when both conditions are false

average_height = 1.70   # meter
my_height = 1.75

if my_height > average_height:
    print("You are taller than average")
elif my_height == average_height:
    print("You are average")
else:
    print("You are shorter than average")
You are taller than average
temp = -5

if temp >= 25 :
  print("Time to go to the beach!")
elif temp >= 0 :
  print("Time to study")
else:
  print("Bundle up and stay warm!")
Bundle up and stay warm!

5.4. Useful tip: The input() function#

The input() method is an essential feature that enables your programs to accept information from users during runtime. It allows you to prompt the user for input and returns the entered text as a string.

name = input("Please enter your name: ")
print(f"Hello, {name}")

By default, input() treats all input as strings. To handle numeric input, you need to convert it using theappropriate data type casting, for example: int() and float(). You can also assign the input to a variable for further operations.

num1 = int(input("Enter a number: "))
num2 = float(input("Enter another number: "))
result = num1 + num2
print(f"The sum is: {result}")

5.4.1. Exercise: Warm-up! Largest number finder#

Create a program that finds the largest number out of two different numbers using only if-else statements.

  • Step 1: Use the input() function to ask for two different numbers as two separate inputs (as integers). Assign each of these two inputs to two different variables: num1, num2.

  • Stap 2: Compare the two numbers using if-else statements to find the largest number out of the inputs.

# ask the user for three seperate inputs
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
# compare the inputs to find the largest number
if # your code here :
    largest = # your code here
else:
    largest = # your code here

print(f"The largest number is: {largest}")

5.4.2. Exercise: If-elif-else#

Create a program that takes a numerical grade as input and classifies it into different categories based on the following criteria:

  • 90 or above: “A”

  • 80 to 89: “B”

  • 70 to 79: “C”

  • 60 to 69: “D”

  • Below 60: “F”

Hint We can start from the first criterion and move down. For “A” it’s sufficient to check if the number is larger (or equal >=) than 90. For “B” it’s sufficient to check if the number is larger than 80. Note that you don’t need to check if it is smaller than 90, because it for sure is, otherwise it would have been an “A” and the “if” would stop. The sam applies to the other options.

# Ask the user for their numerical grade and assign it to a variable.
numerical_grade = float(input("Enter the numerical grade: "))
# Use if-else statements to classify the grade
# your code here

5.5. Useful tip: in operator#

The in operator is also commonly used with if-statements. It checks if a specified item is within a list or other iteratable data structures. You can also use the not in command to check if the item is not in a list.

animal_list = ['cat', 'dog', 'monkey']

if "cat" in animal_list:
  print ("cat is an animal.")
cat is an animal.
lucky_numbers = [1, 3, 7, 9, 13, 15, 21, 25, 31, 33, 37, 43, 49, 51, 63, 67, 69, 73, 75, 79, 87, 93, 99]

my_number = int(input("Enter your favorite number: "))

if my_number in lucky_numbers:
  print("That's a lucky number!")
else:
  print("It's not a lucky number :(")

5.5.1. Exercise: Grocery item checker program#

Create a program that interacts with the user, allowing them to input a grocery item. The program should then check if the entered item is present in a predefined shopping list. To do so, complete the following steps:

  • Step 1: Define the predefined shopping list.

  • Step 2: Prompt the user to input a grocery item.

  • Step 3: Check if the entered item is present in the shopping list (use in operator!)

  • Step 4: Display a message indicating whether the item is available or not.

Hint: Since all items in the shopping list are lowercase, you can convert user input to lowercase by using input("...").lower() to make sure your comparisons are not case-sensitive.

# Step 1
shopping_list = ["apple", "banana", "milk", "bread", "eggs", "cheese", "yogurt"]
# Step 2: Prompt the user for input
user_item = input("Enter a grocery item: ").lower()
# Step 3 an 4
# Check if the entered item is in the shopping list (don't forget to use user_item.lower())
# Desplay a message

# your code here

5.5.2. Extra exercises: BMI calculator and range indicator#

Task: Write a Python program that interacts with the user, prompting them to enter their age and height. The program should then calculate and print their Body Mass Index (BMI) and indicate the BMI range: Ynderweight, Normal, Overweight, Obesity.

Program description: Write a Python program that performs the following steps:

  1. Prompt the user to enter their weight in kilograms.

  2. Prompt the user to enter their height in meters.

  3. Calculate the BMI using the formula: BMI = weight (kg) / height^2 (m^2)

  4. Determine and print the BMI range based on the following categories:

  • Underweight: BMI < 18.5

  • Normal (healthy weight): 18.5 <= BMI < 24.9

  • Overweight: 25 <= BMI < 29.9

  • Obesity: BMI >= 30

  1. Print the result.

# Step 1 & 2
# Get input for age and weight

weight = float(input("Enter your weight in kilograms: "))
height = float(input("Enter your height in meters: "))
# Step 3
# Calculate BMI
bmi = # your code here

# Print bmi to check if it works well
print(f"Your BMI: {bmi}")
# Step 4
# Determine BMI range

if # your code here:
    category = "underweight"
elif # your code here:
    category = "healthy weight"
elif # your code here:
    category = "overweight"
else:
    category = "obese"
# Step 5
# Print results
print(f"Your BMI is {bmi:.2f}, which falls in the '{category}' range.")

5.5.3. Exercise: Vowel & consonants#

Task: Write a Python program that reads a word input by the user and counts the number of vowels and consonants in that word.

Program Description:

  1. Prompt the user to enter a word (lower- or/and uppercase) and converting it to lowercase.

  2. Define the list of vowels and consonants (use only lowercase).

  3. Initialize counters for vowels and consonants to zero. This means defining two new variables (count_vowels, and count_consonants) for counting that should be zero at first and will be later increased.

  4. Iterate through each letter of the word.

  5. If the letter is a vowel increase the vowel counter by one: count_consonants += 1

  6. If the letter is s consonant increase the consonant counter by one: count_consonants += 1

  7. Display the number of vowels and consonants in the entered word.

# 1- Prompt user to enter a word (converted to lowercase)
word = # your code here

# 2- Define lists of vowels and consonants
vowels = ['a', 'e', 'i', 'o', 'u']
consonants = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z']
# 3- Initialize counters for vowels and consonants,
count_vowels = # your code here
count_consonants = # your code here
# 4- Iterate over each character in the word
#     5- Check if the character is a vowel
#          6- Check if the character is a consonant

# your code here

# 7- Print the number of vowels and consonants
print("Number of vowels:", count_vowels)
print("Number of consonants:", count_consonants)

Note

Please note that this platform does not support the use of the input() function.
To work around this, you can either define your variables manually or use Google Colab or another coding environment that supports input() for your assignments.