Every program has to make decisions. If the user is 18 or older, show one message. If not, show another message. In Python, we make decisions with conditions. In this guide, you will learn if, elif and else with simple examples. If you do not know how to take input yet, read Python Input and Output: print(), input() and f-strings first.
- What a condition is, and what True and False mean
- How to compare values with
==,!=,>,<,>=and<= - How to use
if,elseandelif - Why spaces (indentation) are important in Python
- How to join conditions with
and,orandnot
What Is a Condition?
A condition is a question that Python answers with True or False. For example, "Is 20 bigger than 18?" The answer is True. Python can show you this answer:
print(20 > 18)
print(5 == 7)
You should see this output:
True
False
To ask these questions, we use comparison operators:
==means "is equal to"!=means "is not equal to">means "is bigger than"<means "is smaller than">=means "is bigger than or equal to"<=means "is smaller than or equal to"
= saves a value in a variable. Two equal signs == compare two values. Do not mix them.Step 1: Your First if Statement
- Open VS Code and open your python-practice folder.
- Click the New File icon and name the file
condition.py. - Type the code below.
- Press
Ctrl + Sto save the file. - Click the triangle (Play) button at the top right to run it.
age = 20
if age >= 18:
print("You are an adult")
print("Program finished")
You should see this output:
You are an adult
Program finished
Python checks the condition age >= 18. It is True, so Python runs the line under the if. If you change age to 15, the condition is False. Then Python skips that line and shows only Program finished.
Step 2: Colon and Indentation
Look at the if line again. It has two important parts:
- The colon
:at the end of the line. Python needs it. - The 4 spaces before the next line. This is called indentation. It tells Python that this line is inside the
if.
The line print("Program finished") has no spaces at the start. So it is outside the if, and it always runs.
Tab key to make 4 spaces. VS Code usually adds them for you after you type the colon and press Enter.Step 3: Use else for the Other Choice
What if the condition is False? Use else. It runs when the if condition is not True.
age = 15
if age >= 18:
print("You are an adult")
else:
print("You are a minor")
You should see this output:
You are a minor
Python runs only one of the two blocks, never both. Also remember that else does not have a condition. Just write else:.
Step 4: Use elif for More Choices
Sometimes you have more than two choices. Use elif. It means "else if". Python checks the conditions from top to bottom and stops at the first True one.
marks = 72
if marks >= 80:
print("Grade A")
elif marks >= 60:
print("Grade B")
elif marks >= 40:
print("Grade C")
else:
print("Fail")
You should see this output:
Grade B
Here, 72 >= 80 is False, so Python goes down. Then 72 >= 60 is True, so it shows Grade B and skips the rest. You can use many elif lines, but only one if and one else.
marks >= 40 first, then 72 would get Grade C, because that condition is True first.Step 5: Join Conditions with and, or, not
You can check more than one thing in one line.
andis True only when both conditions are True.oris True when at least one condition is True.notchanges True to False, and False to True.
age = 20
has_ticket = True
if age >= 18 and has_ticket:
print("You can enter")
day = "Sat"
if day == "Sat" or day == "Sun":
print("It is the weekend")
You should see this output:
You can enter
It is the weekend
Notice that we wrote day == "Sat" or day == "Sun". Do not write day == "Sat" or "Sun". Python does not understand it the way you think.
Step 6: Practice Program
Now let us use input(), int(), f-strings and conditions together. Create a new file named grade.py and type this:
name = input("Your name: ")
marks = int(input("Your marks: "))
if marks >= 80:
grade = "A"
elif marks >= 60:
grade = "B"
elif marks >= 40:
grade = "C"
else:
grade = "Fail"
print(f"{name}, your grade is {grade}")
If you type Ali and 72, you will see this output:
Your name: Ali
Your marks: 72
Ali, your grade is B
Run it again with different marks like 90, 45 and 20. This is the best way to learn.
Common Errors and How to Fix Them
Error 1: IndentationError: expected an indented block
You forgot the spaces under the if:
if age >= 18:
print("Adult")
Add 4 spaces before print:
if age >= 18:
print("Adult")
Error 2: SyntaxError: expected ':'
You forgot the colon at the end of if, elif or else. Write if age >= 18:, not if age >= 18.
Error 3: SyntaxError: invalid syntax (using = in a condition)
You used one equal sign inside the if:
if age = 18:
To compare values, use two equal signs: if age == 18:.
Error 4: TypeError: '>=' not supported between instances of 'str' and 'int'
You compared text with a number. Remember that input() always gives text. Change it into a number first:
age = int(input("Your age: "))
Common Mistakes Beginners Make
- Using = instead of ==. One equal sign saves a value. Two equal signs compare values.
- Forgetting the colon. Every
if,elifandelseline ends with:. - Forgetting the indentation. The lines inside the block need 4 spaces.
- Mixing spaces in one block. Use the same number of spaces for all lines in one block.
- Comparing input() text with a number. Use
int()first. - Writing a condition after else. The
elseline has no condition. Useelifif you need one. - Wrong capital letters.
"Ali"and"ali"are not equal in Python.
Practice Time
Try these small tasks on your own. Click a question to open the code box, write your Python code and press Run. If your code is correct, you will see a green message. If there is an error, you will see the error, the line number, the mistake and how to fix it.
- Print "Adult" if the age is 18 or more.
- Check if a number is even or odd.
- Give a grade from marks with
elif. - Check a username and a password with
and.
What to Learn Next
Now your programs can make decisions. The next step is loops. You will learn how to repeat a task many times with for and while, without writing the same line again and again. In the next post, we will learn them with simple examples. If you missed the full learning plan, read my Python roadmap for beginners.
Frequently Asked Questions (FAQs)
What is the difference between = and == in Python?
One equal sign = saves a value in a variable, like age = 20. Two equal signs == compare two values and give True or False, like age == 20.
Why does Python need indentation?
Python uses spaces to know which lines are inside the if block. Other languages use curly brackets for this. In Python, the 4 spaces at the start of the line do the same job.
Can I use more than one elif?
Yes. You can use as many elif lines as you need. But you can have only one if at the start and only one else at the end.
Is else always needed?
No. You can write an if without else. Use else only when you want to do something when the condition is False.
Final Thoughts
Conditions make your programs smart. Remember the three big ideas: a condition is True or False, if, elif and else choose which code to run, and indentation is very important. Practice a little every day, and try to change the numbers and messages in the examples to see what happens.




Comments
Post a Comment