Python: Make Decisions with If, Elif, and Else

Python Decision Making with If, Elif, and Else

Python Decision Making with If, Elif, and Else

This tutorial introduces you to the concept of conditional execution in Python using `if`, `elif`, and `else` statements. These statements allow your program to make decisions based on the values of variables, executing different blocks of code depending on specific conditions. We’ll explore these concepts through practical examples, building upon each other to solidify your understanding.

Understanding If, Elif, and Else

The fundamental structure is as follows:

  • if: Executes a block of code only if the condition is true.
  • elif: (Short for “else if”) Executes a block of code only if the previous `if` or `elif` conditions were false. You can have multiple `elif` statements.
  • else: Executes a block of code if none of the preceding `if` or `elif` conditions were true.

All blocks of code within these conditional statements must be indented to indicate their belonging to the conditional structure.

Example 1: Simple Temperature Check

Let’s create a program that determines whether a temperature is cold, moderate, or hot based on a given value.

python
def check_temperature(temperature):
“””
Checks the temperature and prints whether it is cold, moderate, or hot.
“””
if temperature < 10:
print("It's cold!")
elif temperature < 25:
print("It's moderate.")
else:
print("It's hot!")

# Get input from the user
try:
temp = float(input("Enter a temperature between 0 and 30: "))
if temp 30:
print(“Invalid temperature. Please enter a value between 0 and 30.”)
else:
check_temperature(temp)
except ValueError:
print(“Invalid input. Please enter a number.”)


def check_temperature(temperature):
    """
    Checks the temperature and prints whether it is cold, moderate, or hot.
    """
    if temperature < 10:
        print("It's cold!")
    elif temperature < 25:
        print("It's moderate.")
    else:
        print("It's hot!")

# Get input from the user
try:
    temp = float(input("Enter a temperature between 0 and 30: "))
    if temp  30:
        print("Invalid temperature. Please enter a value between 0 and 30.")
    else:
        check_temperature(temp)
except ValueError:
    print("Invalid input. Please enter a number.")

Explanation:

  1. We define a function `check_temperature` that takes a temperature as input.
  2. Inside the function, the `if` statement checks if the temperature is less than 10. If it is, it prints “It’s cold!”.
  3. The `elif` statement checks if the temperature is less than 25. If it is, it prints “It’s moderate”.
  4. The `else` statement handles all other cases, printing “It’s hot!”.
  5. We use `input()` to get the temperature from the user.
  6. We convert the input to a float using `float()`.
  7. We use a `try-except` block to handle potential `ValueError` if the user enters non-numeric input.
  8. Input validation checks if the temperature is within the range of 0 to 30. If it’s not, an error message is printed.
  9. Finally, we call the `check_temperature` function with the validated temperature.

Output:


Enter a temperature between 0 and 30: 15
It's moderate.

Enter a temperature between 0 and 30: 5
It's cold!

Enter a temperature between 0 and 30: 30
It's hot!

Enter a temperature between 0 and 30: abc
Invalid input. Please enter a number.

Enter a temperature between 0 and 30: -5
Invalid temperature. Please enter a value between 0 and 30.

Example 2: Grade Calculation

Now let’s create a program that calculates a letter grade based on a numerical score (0-100).

python
def calculate_grade(score):
“””
Calculates the letter grade based on a score.
“””
if score >= 90:
return “A”
elif score >= 80:
return “B”
elif score >= 70:
return “C”
elif score >= 60:
return “D”
else:
return “F”

# Get input from the user
try:
score = int(input(“Enter a score between 0 and 100: “))
if score 100:
print(“Invalid score. Please enter a value between 0 and 100.”)
else:
grade = calculate_grade(score)
print(f”Your grade is: {grade}”)
except ValueError:
print(“Invalid input. Please enter a number.”)


def calculate_grade(score):
    """
    Calculates the letter grade based on a score.
    """
    if score >= 90:
        return "A"
    elif score >= 80:
        return "B"
    elif score >= 70:
        return "C"
    elif score >= 60:
        return "D"
    else:
        return "F"

# Get input from the user
try:
    score = int(input("Enter a score between 0 and 100: "))
    if score  100:
        print("Invalid score. Please enter a value between 0 and 100.")
    else:
        grade = calculate_grade(score)
        print(f"Your grade is: {grade}")
except ValueError:
    print("Invalid input. Please enter a number.")

Explanation:

  1. We define a function `calculate_grade` that takes a score as input.
  2. Inside the function, we use a series of `if` and `elif` statements to determine the letter grade based on the score ranges.
  3. We use `return` to return the corresponding letter grade from the function.
  4. Similar to the previous example, we get the score from the user, validate it, and call the `calculate_grade` function.

Output:


Enter a score between 0 and 100: 85
Your grade is: B

Enter a score between 0 and 100: 92
Your grade is: A

Enter a score between 0 and 100: 65
Your grade is: D

Enter a score between 0 and 100: 0
Your grade is: F

Enter a score between 0 and 100: abc
Invalid input. Please enter a number.

Enter a score between 0 and 100: -10
Invalid score. Please enter a value between 0 and 100.

Example 3: Even or Odd

Let’s create a simple program that determines if a number is even or odd.

python
def check_even_odd(number):
“””
Checks if a number is even or odd.
“””
if number % 2 == 0:
print(f”{number} is even.”)
else:
print(f”{number} is odd.”)

# Get input from the user
try:
num = int(input(“Enter an integer: “))
check_even_odd(num)
except ValueError:
print(“Invalid input. Please enter an integer.”)


def check_even_odd(number):
    """
    Checks if a number is even or odd.
    """
    if number % 2 == 0:
        print(f"{number} is even.")
    else:
        print(f"{number} is odd.")

# Get input from the user
try:
    num = int(input("Enter an integer: "))
    check_even_odd(num)
except ValueError:
    print("Invalid input. Please enter an integer.")

Explanation:

  1. We define a function `check_even_odd` that takes a number as input.
  2. Inside the function, we use the modulo operator (`%`) to get the remainder when the number is divided by 2.
  3. If the remainder is 0, the number is even, and we print a message indicating this.
  4. Otherwise, the number is odd, and we print a message indicating this.
  5. We get the number from the user, validate it, and call the `check_even_odd` function.

Output:


Enter an integer: 4
4 is even.

Enter an integer: 7
7 is odd.

Enter an integer: abc
Invalid input. Please enter an integer.

Leave a Reply

Your email address will not be published. Required fields are marked *

We use cookies and similar technologies to enhance your experience on wobizdu.com, analyze site traffic, personalize content, and deliver relevant ads. Some cookies are essential for the site to function, while others help us improve performance and user experience. You may accept all cookies, decline optional ones, or customize your settings. Review our Privacy Policy to learn more.