Hello! In our last lesson, you learned how to represent information in Python using variables and the basic data types: strings, numbers, and booleans. This is like learning the nouns of a language. Now, we'll learn the conjunctions and decision-making verbs.
This lesson focuses on bringing your program to life by giving it the ability to make decisions. You will learn how to use comparison expressions to ask questions about your data (e.g., "is this ticket priority 'High'?") and boolean operators (and, or, not) to combine these questions. Most importantly, you'll use if, elif, and else statements to create conditional branches, which allow your program to execute different code blocks based on the answers to those questions. This is the core of application logic and is essential for building a chatbot that can react intelligently to user input.
Comparisons: The Foundation of Decisions
Programs make decisions by evaluating conditions that result in either True or False. In the previous lesson's exercise, you used a simple comparison, is_new_str == "True", to convert a string to a boolean. This is the essence of a condition. Python provides a set of comparison operators to ask questions about your data.
To start, let's formally review the building blocks of any condition. This chapter from Automate the Boring Stuff is excellent for beginners. Please read the first two sections.
Focus on the sections Boolean Values, which recaps the True and False types, and Comparison Operators, which lists the six main operators: ==, !=, <, >, <=, and >=. Pay close attention to the difference between the comparison operator == and the assignment operator = that you learned about in the last lesson.
As the reading highlights, these operators are your tools for forming questions:
==(Equal to): Is the ticket status exactly'Closed'?!=(Not equal to): Is the user input not an empty string?>(Greater than): Is the number of user messages greater than 10?<=(Less than or equal to): Is the ticket ID less than or equal to 100?
Each of these expressions evaluates to a single boolean value: True or False.
Conditional Execution: if, elif, and else
Once you have a condition that evaluates to True or False, you can use it to control which code runs. This is done with an if statement. The structure is simple: if a condition is true, the indented block of code below it is executed. If not, it's skipped.
You can also provide an alternative path with else for when the if condition is false. And for a sequence of checks, you can use elif (short for "else if").
The following video from Bro Code provides a clear, step-by-step demonstration of how to build these structures.
If statements in Python are easy (if, elif, else) 🤔
This video walks through the logic of conditional statements with practical examples.
Watch the following segments: The basic if statement, which shows how a block of code runs only when a condition is met. Adding an else statement for the alternative case. Using elif for multiple checks. Notice the important point he makes about the order of elif statements mattering.
To summarize the structure:
priority = "High"
status = "Open"
if priority == "Critical":
# This block runs if priority is 'Critical'
print("Escalating to on-call engineer immediately!")
elif priority == "High" and status == "Open":
# This block runs if the first condition is false AND this one is true
print("Adding to high-priority queue.")
elif priority == "Medium" or priority == "Low":
# This block runs if the first two conditions are false AND this one is true
print("Adding to standard queue.")
else:
# This block runs if NONE of the above conditions were true
print("Status: Uncategorized.")
Notice a few key things here:
- Colon and Indentation: Every
if,elif, andelseline ends with a colon (:), and the code to be executed is indented below it. This indentation is mandatory in Python. - One Path: In an
if/elif/elsechain, exactly one block of code will run: the one corresponding to the first true condition encountered. Once a true condition is found, the rest of the chain is skipped.
Combining Conditions: and, or, not
Sometimes a simple comparison isn't enough. You might need to check if a ticket is high priority and its status is open. For this, you use the boolean operators: and, or, and not.
condition1 and condition2: Evaluates toTrueonly if both conditions are true.condition1 or condition2: Evaluates toTrueif at least one of the conditions is true.not condition: Inverts the boolean value.not TruebecomesFalse, andnot FalsebecomesTrue.
This next video from Corey Schafer gives a great practical example of using these operators to check for user permissions.
Python Tutorial for Beginners 6: Conditionals and Booleans - If, Else, and Elif Statements
This video clearly demonstrates how to combine conditions to build more complex logic.
Watch the segment from on boolean operators. The example of checking if a user is an 'admin' and is logged_in is a perfect illustration of a common pattern in application development.
"Truthy" and "Falsy" Values
A convenient feature in Python is that it can evaluate non-boolean values in a conditional context. This allows for clean, readable shortcuts. For example, instead of writing if user_input != "":, you can simply write if user_input:.
The rule is simple:
- "Falsy" values: These are values that Python considers
Falsein anifstatement. They includeFalse,None, numeric zero (0,0.0), and any empty collection like an empty string (""), empty list ([]), or empty dictionary ({}). - "Truthy" values: Everything else. Any non-empty string, any non-zero number, any non-empty list, etc., is considered
True.
This concept is explained very concisely in the Stanford CS lecture notes.
These notes provide a compact summary of how Python handles non-boolean values in conditions.
Read the section titled Truthy Logic. The examples using the bool() function are a great way to see exactly what Python considers True or False.
Practice Exercise
Let's apply these concepts by adding some decision-making logic to the ticket_info.py script from our last lesson.
Modify your script to do the following:
-
After getting all the user input, check if the
customer_nameis empty.- If it is empty (i.e., it's a "falsy" value), print an error message like "Error: Name cannot be blank."
- Otherwise (
else), proceed with printing the summary.
-
Inside the
elseblock (where you know you have a customer name), add more logic before printing the summary:- If the
ticket_id_intis greater than 1000, print a message:Note: This is a recent ticket. - If the
is_new_boolisTrueand theticket_id_intis less than 100, print a warning:Warning: A new ticket has a very low ID. Please check for system errors.
- If the
Here is the code from the last lesson, ready for you to modify:
# --- Welcome to the Support Ticket System ---
print("--- Welcome to the Support Ticket System ---")
# Get user input
customer_name = input("Please enter your name: ")
ticket_id_str = input("Please enter your numeric ticket ID: ")
is_new_str = input("Is this a new ticket? (True/False): ")
# Type conversions
ticket_id_int = int(ticket_id_str)
is_new_bool = (is_new_str == "True")
# --- YOUR CONDITIONAL LOGIC GOES HERE ---
# 1. Check if customer_name is empty
if not customer_name:
print("Error: Name cannot be blank.")
else:
# This block only runs if a name was provided.
print("\n--- Processing Ticket ---")
# 2. Add more specific checks inside this block
if ticket_id_int > 1000:
print("Note: This is a recent ticket.")
if is_new_bool and ticket_id_int < 100:
print("Warning: A new ticket has a very low ID. Please check for system errors.")
# Print the summary
print("\n--- Ticket Information Received ---")
summary = f"Thank you, {customer_name}. Ticket #{ticket_id_int} has been recorded. New status: {is_new_bool}."
print(summary)
Run this script several times with different inputs to see how your new logic behaves. Try leaving the name blank, using a high ticket ID, and using a low ticket ID for a "new" ticket.
Conclusion
You've just learned one of the most powerful concepts in programming: conditional logic. With the ability to direct the flow of your program, you've moved from writing simple scripts that run from top to bottom to creating programs that can respond dynamically to the data they process.
Here are the key takeaways:
if,elif,elsestatements are used to create branches in your code.- Conditions are built using comparison operators (
==,!=,>,<) which evaluate toTrueorFalse. - Boolean operators (
and,or,not) allow you to create complex conditions by combining simpler ones. - Python's concept of "truthy" and "falsy" values provides a convenient way to check for things like empty user input.
In the next lesson, we will explore another fundamental aspect of program control: loops. While if statements allow you to decide whether code runs, loops will allow you to decide how many times it runs, enabling you to process collections of data efficiently.