Introduction: Why Do We Need Conditions?
Chapter 1: Introduction – Why Do We Need Conditions?
Welcome to Lesson 3 of our Python and FastAPI course. In the previous lesson, we learned about variables and data types. Now, we are going to make our programs smarter. Have you ever used an app that asks you to log in? If you enter the correct password, it lets you in. If you enter the wrong password, it shows an error. How does the app know which action to take? It uses conditions.
Conditions are the way we tell the computer: "If this is true, do this; otherwise, do something else." Without conditions, our programs would run the same way every single time, with no ability to react to different inputs or situations. In this chapter, we will learn why conditions are essential and how to use them in Python.
What is a Condition?
A condition is a logical statement that can be either True or False. For example:
- "The temperature is greater than 30 degrees" – this can be true or false.
- "The user's age is 18 or older" – this can be true or false.
- "The file exists" – this can be true or false.
In Python, we use the if statement to check a condition. If the condition is true, the code inside the if block runs. If it is false, the code is skipped.
Why Do We Need Conditions in a Real API?
Imagine you are building a Task Manager API (which is the final project of this course). You will need conditions for many things:
- Check if a task belongs to the current user before showing it.
- Check if a task status is "completed" before allowing deletion.
- Validate that a user's email is not empty before saving it.
- Return different HTTP status codes based on success or failure.
Without conditions, your API would be unable to make decisions. It would treat every request the same way, which is not useful for a real-world application.
Basic Syntax of if in Python
Let's look at the simplest form of a condition. The syntax is:
if condition:
# code to run if condition is True
print("Condition is true!")
Notice the colon (:) at the end of the if line. Also notice the indentation (4 spaces) before the print statement. In Python, indentation is very important. It tells Python which code belongs to the if block.
Practical Example: Checking User Age
Let's write a simple program that checks if a user is old enough to use our app. We will use a variable called age and compare it to 18.
# Example: Check if user is an adult
age = 20
if age >= 18:
print("You are an adult. Welcome!")
print("You can create tasks.")
else:
print("Sorry, you must be 18 or older.")
print("Please come back later.")
Step-by-step explanation:
- We set the variable
ageto 20. - The condition
age >= 18is checked. Since 20 is greater than or equal to 18, the condition isTrue. - The code inside the
ifblock runs: it prints "You are an adult. Welcome!" and "You can create tasks." - The
elseblock is skipped because the condition was true.
If we change age to 15, the condition becomes False, and the else block runs instead.
Using elif for Multiple Conditions
Sometimes you need to check more than two possibilities. For example, you might want to give different messages based on a score: "Excellent", "Good", or "Needs Improvement". In Python, you use elif (short for "else if") to add more conditions.
# Example: Grade checker
score = 85
if score >= 90:
print("Excellent! You got an A.")
elif score >= 75:
print("Good job! You got a B.")
elif score >= 50:
print("You passed. You got a C.")
else:
print("Needs improvement. You failed.")
How it works:
- First, it checks
score >= 90. If true, it prints "Excellent" and stops checking the rest. - If false, it moves to the next
elifand checksscore >= 75. If true, it prints "Good job" and stops. - If false, it checks the next
elif. - If none of the conditions are true, the
elseblock runs.
In this example, score = 85 is not >= 90, so the first condition is false. It then checks 85 >= 75, which is true, so it prints "Good job! You got a B."
Comparison Operators You Should Know
To write conditions, you need to compare values. Here are the most common comparison operators in Python:
==: equal to (careful: two equals signs, not one)!=: not equal to>: greater than<: less than>=: greater than or equal to<=: less than or equal to
Here is a quick example using each operator:
a = 10
b = 5
print(a == b) # False
print(a != b) # True
print(a > b) # True
print(a < b) # False
print(a >= 10) # True
print(b <= 4) # False
Common Mistakes Beginners Make
Let's look at some errors you might encounter when writing conditions.
Mistake 1: Using a single equals sign = instead of double == for comparison.
# Wrong:
if age = 18: # This will cause an error!
print("You are 18.")
# Correct:
if age == 18:
print("You are 18.")
A single = is for assignment, not comparison. Python will give you a SyntaxError if you try this.
Mistake 2: Forgetting the colon at the end of the if, elif, or else line.
# Wrong:
if age > 18
print("Adult")
# Correct:
if age > 18:
print("Adult")
Mistake 3: Inconsistent indentation.
# Wrong:
if age > 18:
print("Adult")
print("You can vote.") # This indentation is wrong!
# Correct:
if age > 18:
print("Adult")
print("You can vote.")
All lines inside the same block must have the same indentation level. Python uses indentation to group code, so mixing spaces and tabs or using different numbers of spaces will cause an IndentationError.
Practical Callout: Why This Matters for Your API
Real-world connection: In your final Tasks API, you will use conditions to check if a task exists before updating it. For example:
if task_id in tasks_database:
# update the task
return {"message": "Task updated"}
else:
# return an error
return {"error": "Task not found"}
This pattern is used in almost every API endpoint. Without conditions, your API would not know how to handle missing data or invalid requests.
Your Turn: Practice Task
Now it's time to write your own code. Open your Python editor (like VS Code or the Python IDLE) and create a new file called lesson3_practice.py.
Task: Write a program that asks the user to enter a number. Then, check the number and print one of the following messages:
- If the number is greater than 0, print "The number is positive."
- If the number is less than 0, print "The number is negative."
- If the number is exactly 0, print "The number is zero."
Hint: To get input from the user, use the input() function. Remember that input() returns a string, so you need to convert it to a number using int() or float().
Here is a starting template:
# Practice: Positive, Negative, or Zero
number = int(input("Enter a number: "))
# Write your conditions here
if number > 0:
print("The number is positive.")
elif number < 0:
print("The number is negative.")
else:
print("The number is zero.")
Run your program and test it with different numbers: 5, -3, 0. Make sure you see the correct message for each case.
Bonus challenge: Modify your program to also check if the number is even or odd. Print "The number is even." or "The number is odd." after the positive/negative/zero message. (Hint: use the modulo operator % to check if a number is divisible by 2.)
Summary
In this chapter, you learned:
- Why conditions are essential for making decisions in code.
- How to use
if,elif, andelseto control program flow. - Common comparison operators like
==,!=,>,<,>=,<=. - Common mistakes to avoid, such as using
=instead of==and forgetting the colon. - How conditions will be used in your future Tasks API.
Conditions are the foundation of intelligent programs. In the next lesson, we will build on this knowledge and learn about loops, which allow us to repeat actions multiple times. Keep practicing, and you will be building your API before you know it!
Loading ratings...