Conditions with if and else
Conditional statements allow us to make decisions in our Python programs. The most common conditional is the if
statement. With it, we can execute a block of code only if a certain condition is true.
The if
Statement
The basic syntax of an if
statement is:
if condition:
# block of code
- If the condition is
True
, the code inside the block runs. - If it's
False
, Python skips it.
Example:
age = 18
if age >= 18:
print("You are an adult.")
Output
You are an adult.
Adding an else
Clause
The else
clause provides an alternative block of code to run if the condition is False
.
Syntax:
if condition:
# runs if condition is True
else:
# runs if condition is False
Example:
age = 16
if age >= 18:
print("You are an adult.")
else:
print("You are underaged.")
Output
You are underaged.
Using Comparison Operators
Here are some operators you can use inside conditions:
Operator | Meaning |
---|---|
== |
Equal to |
!= |
Not equal to |
> |
Greater than |
< |
Less than |
>= |
Greater than or equal |
<= |
Less than or equal |
Example:
score = 70
if score >= 50:
print("You passed!")
else:
print("You failed.")
Output
You passed!
Indentation is Mandatory
In Python, indentation matters. Blocks of code under if
or else
must be indented.
x = 5
if x > 0:
print("Positive number") # Correct indentation
Incorrect indentation will cause an error.
Nested Conditions
You can also nest if
statements inside each other.
age = 20
if age > 0:
if age >= 18:
print("Adult")
else:
print("Child")
Exercise: Try It Yourself!
Write a program that asks the user for a number and prints:
- "Positive" if it's greater than 0
- "Zero" if it's equal to 0
- "Negative" if it's less than 0
Sample output
Enter a number: -3
Negative