⬅ Previous Topic
Python OperatorsNext Topic ⮕
Python Loops⬅ Previous Topic
Python OperatorsNext Topic ⮕
Python LoopsIn real life, we make decisions all the time:
Python also lets us make decisions in our code using conditional statements.
They let your program choose what to do depending on certain conditions.
In Python, we use:
This runs a block of code only if a condition is true.
x = 10
if x > 5:
print("x is greater than 5")
x is greater than 5
Why? Because x
is 10, and 10 is greater than 5.
This adds an "otherwise" case when the condition is false.
age = 16
if age >= 18:
print("You can vote.")
else:
print("You cannot vote.")
You cannot vote.
Why? Because 16 is less than 18, so the else
block runs.
Use elif
when you have more than two choices.
marks = 75
if marks >= 90:
print("Grade: A")
elif marks >= 70:
print("Grade: B")
elif marks >= 50:
print("Grade: C")
else:
print("Grade: F")
Grade: B
Why? 75 is not >= 90, but it is >= 70, so the second block runs.
You can also put one if
inside another. This is called nesting.
num = 10
if num > 0:
if num % 2 == 0:
print("Positive even number")
Positive even number
Why? First, num > 0
is true. Then, 10 % 2 == 0
(means even), so the inner print runs.
:
) after if
, elif
, and else
.==
, !=
, >
, <
, >=
, <=
.Change the values in the examples and see how the output changes. Try your own conditions too!
Conditional statements help your programs make decisions, just like you do in real life. Mastering these will let you build smarter and more interactive Python programs.
⬅ Previous Topic
Python OperatorsNext Topic ⮕
Python LoopsYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.