Story – Python if…else

As Alex continued their journey with Python, they realized that they needed a way to make decisions in their programs. That’s when they learned about if...else statements.

To understand this concept, Alex decided to create a simple program that would check if a number was even or odd.

# Program to check if a number is even or odd
# Author: Alex
# Date: 2/25/2023

# Getting user input
number = int(input("Enter a number: "))

# Checking if the number is even or odd
if number % 2 == 0:
    print("The number is even")
else:
    print("The number is odd")

In this code, Alex used an if statement to check if the number entered by the user was even. If the number was even, the program printed “The number is even”. If the number was odd, the program printed “The number is odd”.

As they ran the program, Alex noticed that it worked perfectly. They were excited to use if...else statements in their future programs.

As they continued to learn about if...else statements, Alex realized that they could add multiple conditions to their programs by using elif statements. They also learned about nested if...else statements, which allowed them to make decisions based on multiple conditions.

For example, Alex created a program that would determine the grade of a student based on their percentage.

# Program to determine the grade of a student
# Author: Alex
# Date: 2/25/2023

# Getting user input
percentage = int(input("Enter your percentage: "))

# Determining the grade
if percentage >= 90:
    print("Your grade is A")
elif percentage >= 80:
    print("Your grade is B")
elif percentage >= 70:
    print("Your grade is C")
elif percentage >= 60:
    print("Your grade is D")
else:
    print("Your grade is F")

In this code, Alex used elif statements to check multiple conditions. Depending on the percentage entered by the user, the program would print the corresponding grade.

As Alex continued to explore if...else statements, they realized how powerful this feature was in making decisions in their programs. They were excited to continue to learn and use if...else statements in their future programs.