In Python, we use conditional expressions to enable decision-making within our programs.
Conditional Expressions Recapped
Generally speaking, an expression is a combination of values, variables, operators, and function calls that the Python interpreter evaluates to produce another value.
Conditional expressions use operators to evaluate states and conditions within a program. These operators include comparison operators (<, >, ==, !=, <=, >=) and logical operators (and, or, not) to produce a Boolean.
For instance:
age = 20
is_teenager = age > 12 and age < 20
Here, is_teenager evaluates to False because, while age > 12 is True, age < 20 is False. Since both conditions need to be True with the and operator, the overall expression returns False.
The comparison operators are the following:
==
: Equal to
!=
: Not equal to
>
: Greater than
<
: Less than
>=
: Greater than or equal to
<=
: Less than or equal to
print(10 == 10) # Outputs True
print(10 != 10) # Outputs False
Understanding the if/else Statement in Python
So how do our computer's make decisions using conditional expressions
? The answer is through the __if/else __statement.
The if/else statement is a fundamental control structure in Python that allows developers to execute certain blocks of code based on specific conditions.
Syntax of if/else
At its core, the if/else statement checks a condition and executes an indented block of code if the condition is True
. If the condition is False
, it executes a different block of code under the else
clause.
Here's the basic syntax:
if condition:
# Execute this block if the condition is true statements
else:
# Execute this block if the condition is false statements
The condition in the if statement is any expression that evaluates to True
or False
, such as comparisons or other Boolean expressions.
if/else in Use
age = 18
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote yet.")
Explanation: This example checks if a person is old enough to vote. It uses a basic comparison operator to determine eligibility.
is_sunny = False
if not is_sunny:
print("It is not sunny.")
else:
print("It is sunny.")
Explanation: This snippet processes user input and reacts accordingly, showcasing a practical use in interactive programs.
user_input = input("Enter yes or no: ")temperature = 40
if temperature < 15 or temperature > 35:
print("Temperature is extreme.")
else:
print("Temperature is mild.")
Explanation: Checks if the temperature is either too low or too high.
user_input = input("Enter yes or no: ")
if user_input.lower() == "yes":
print("You entered Yes")
else:
print("You entered something other than Yes")
Explanation: This code using a special statement that outputs
"Enter yes or no: "
to the terminal. The user is than prompted to type their answer answer.When the user types their answer and presses Enter, the program saves whatever they typed into the user_input variable. Remember, variables are a sort of container that holds some value so that the program can use it later.
Next, the program checks the user's input. It converts the input to all lowercase letters, just in case the user typed "YES," "Yes," or any other combination of uppercase and lowercase letters. The program wants to be sure it can recognize "yes" no matter how it’s typed. It then compares the user’s input to the word "yes."
If the user's input matches "yes," the program prints the message "You entered Yes" on the screen. This tells the user that the program understood their response correctly.
However, if the user typed anything other than "yes" (for example, "no" or "maybe"), the program goes to the else part, which is a backup plan for when the answer isn't "yes." In this case, it prints "You entered something other than Yes" to let the user know their input was different from what the program was checking for.
This is your first glimpse into how programs make decisions based on user actions.
Multiple Conditions
You can chain multiple conditions using elif
, which stands for "else if." This allows for more complex decision structures:
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
else:
print("Grade: C")
Here, elif
checks an additional condition if the first if condition fails. This pattern can continue with multiple elif clauses.
Let's say you have a program that suggests an activity based on the day of the week. Using if, elif, and else, you can assign different activities for different days:
day_of_week == "Sunday": # Create variable, assign the value 'Sunday'
if day_of_week == "monday":
print("Start the week with some exercise!")
elif day_of_week == "tuesday":
print("Time for team meetings.")
elif day_of_week == "wednesday":
print("Work on a personal project.")
elif day_of_week == "thursday":
print("Prepare for the end of the week.")
elif day_of_week == "friday":
print("Wrap up work and plan for the weekend.")
elif day_of_week == "saturday":
print("Relax and enjoy some time off.")
elif day_of_week == "sunday":
print("Spend time with family and prepare for the week ahead.")
else:
print("That's not a valid day of the week!")