Python if, elif and else: 7 Simple Examples for Beginners
Programs become interesting the moment they can make decisions. In Python that is the job of if, elif and else. Here are seven small examples, from simplest to slightly clever.
1. A single if
hp = 0
if hp == 0:
print("Game over")
Note the double equals ==. One = stores a value; two compare values.
2. if with else
coins = 7
if coins >= 10:
print("You can buy a potion")
else:
print("Not enough coins")
3. Three choices with elif
hp = 12
if hp > 20:
print("Healthy")
elif hp > 5:
print("Hurt")
else:
print("Critical!")
Python checks from top to bottom and stops at the first true condition.
4. Comparing text
element = "fire"
if element == "water":
print("Super effective!")
5. Two conditions with and
level = 5
has_key = True
if level >= 5 and has_key:
print("The door opens")
6. Either condition with or
weather = "rain"
if weather == "rain" or weather == "snow":
print("Water monsters get a bonus")
7. A decision inside a loop
for turn in range(1, 6):
if turn % 2 == 0:
print(turn, "defend")
else:
print(turn, "attack")
% gives the remainder. An even number divided by 2 has remainder 0.
Common mistakes
- Forgetting the colon at the end of the
ifline. - Writing
=instead of==. - Putting
elifafterelse(else must come last).
Practise these in the if / else and and / or lessons, where your conditions decide what your monster does in battle.