What Are Conditionals?

Conditionals allow programs to make decisions based on specific criteria. In Python, conditionals are handled using the if, elif (else if), and else statements. A conditional statement evaluates a Boolean expression (True or False). If the expression is true, the code inside the if block will execute. Before we jump into conditional examples, it’s important to understand how Python evaluates conditions using Boolean operators.

Common Boolean operators

Operator Description Example
== Checks if two values are equal.
5 == 5  # True
5 == 3  # False
!= Checks if two values are not equal.
5 != 6  # True
5 != 5  # False
> Checks if the value on the left is greater than the value on the right.
5 > 3  # True
3 > 5  # False
< Checks if the value on the left is less than the value on the right.
3 < 5  # True
5 < 3  # False
>= Checks if the value on the left is greater than or equal to the value on the right.
5 >= 5  # True
3 >= 5  # False
<= Checks if the value on the left is less than or equal to the value on the right.
3 <= 5  # True
5 <= 3  # False

First Conditional Example!

age = 18

if age >= 18:
    print("You are an adult.") # Executes because 18 >= 18
else:
    print("You are a minor.")

Using Elif and Else for Multiple Conditions

The elif (else if) and else keywords are used in conditional statements to handle multiple conditions efficiently.

elif: If the condition in the if statement is not met, Python will check the condition specified in the elif block. You can have multiple elif blocks in a chain, each checked in order until one is True.

else: This fallback option will execute if none of the if or elif conditions are True. It is placed at the end of the conditional block and doesn’t need a condition. If all the previous conditions fail, the else block will execute by default.

score = 85

if score >= 90:
    print("You got an A!")
elif score >= 80:
    print("You got a B!") # Executes because 85 >= 80 and 85 < 90
elif score >= 70:
    print("You got a C!")
else:
    print("You need to work harder.")

Example:

Nested Conditionals

Nested conditionals are conditionals placed inside other conditionals, enabling more complex decision-making by checking additional conditions after an initial condition is met. This approach is useful when you need to make decisions based on multiple levels of criteria.

In a nested conditional, the if statement can be followed by additional if, elif, and/or else blocks inside it. This structure allows you to test further conditions once the first condition is satisfied.

is_berkeley_student = false
age = 11

if is_berkeley_student:
    print("You get a 50% Berkeley student discount!")
else:
    if age < 12:
        print("You get a 60% youth discount!") # Executes because person is not a Berkeley student and is under 12
    elif age >= 13 and age < 65:
        print("No discount available for this age range.")
    else:
        print("You get a 50% senior discount!")

Example:

Logical Operators in Conditionals

Logical operators like and and or are used to combine multiple conditions in a single expression. These operators help you create more complex conditions for decision-making.

and: Returns True only if both conditions are True. If either condition is False, the entire expression evaluates to False.

or: Returns True if at least one of the conditions is True. If both conditions are False, then the expression evaluates to False.

weather = "sunny"
time = "morning"

if weather == "sunny" and time == "morning":
    print("It's a great time for a walk!") # Execute because both conditions are True

if weather == "rainy" or time == "evening":
    print("You might need an umbrella or a flashlight.") # Executes because atleast one of the condition are True

Example:

Mini Challenge

Download the starter file here.

Write a program that:

1. Takes a number as input. (Hint: Use the `input()` function to get user input and convert it to an integer using `int()`.)

2. Check if the number is positive, negative, or zero.

3. Prints the result.

User Input and Type Casting

User Input: The input() function allows the program to get data from the user. By default, this data is treated as a string (text). You can then convert this string to a different type, such as an integer or float, using type casting.

Type Casting: The process of converting one data type to another. In the example, int(input()) converts the input into an integer so arithmetic operations can be performed. Similarly, you can cast data types to other types like float() for decimals or str() for text.

user_input = int(input("Enter a number: ")) # Converts string input into integer
score = 60

if score >= 90:
    print("You got an A!")
elif score >= 80:
    print("You got a B!")
elif score >= 70:
    print("You got a C!")
else:
    print("You need to work harder.") # Executes because none of the above conditions are met

Example: