Python If Statement - chrisbitm/python GitHub Wiki
An if statement in Python is a control flow structure that lets you execute a block of code only if a specific condition is true. It's how Python makes decisions.
Simple If Statement
age = 18
if age >= 18:
print("You are an adult.")
- The Code Block check if
age
is Greater Than OR Equal to18
. Since it is, Console will outputYou are an adult
.
However, if you had a value that didn't evaluate a true condition. A simple IF Block won't run.
age = 15
# Won't run if Age is less than 18
if age >= 18:
print("You are an adult.")
If-Else Statement
An If-Else lets you execute a block of code if regardless if a condition is True or False.
age = 15
if age >= 18:
print("You are an adult.")
else:
print("You are a minor")
If-Elif-Else Statement
An If-Elif-Else lets you execute a block of code that checks various conditions. You can have as many as you want, but for simplicity, it may not be wise. The else
statement executes.
score = 75
if score >= 90:
print("Excellent!")
elif score >= 75:
print("Good job.")
elif score >= 60:
print("You passed.")
else:
print("You failed.")
Nested If Statement
A nested if statement in Python is an If Statement placed inside another If statement.
age = 20
has_id = True
if age >= 18:
if has_id:
print("Access granted.")
else:
print("ID required.")
else:
print("Access denied. You must be 18 or older.")
age
is Greater Than OR Equal to 18, so the first statement executes.has_id
isTrue
and thusAccess is granted
.