Python Conditional Statements
What are Conditional Statements?
Conditional statements allow you to execute specific blocks of code based
on certain conditions. These statements control the flow of execution and
enable decision-making in programs.
if Statement
Syntax:
if condition:
# code to execute if condition is true
Example:
age = 18
if age >= 18:
print("You are an adult.")
if-else Statement
Syntax:
if condition:
# code to execute if condition is true
else:
# code to execute if condition is false
Example:
age = 16
if age >= 18:
print("You are an adult.")
else:
print("You are not an adult.")
if-elif-else Statement
Syntax:
if condition1:
# code to execute if condition1 is true
elif condition2:
# code to execute if condition2 is true
else:
# code to execute if both conditions are false
Example:
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: D")
Nested if Statements
Syntax:
if condition1:
if condition2:
# code to execute if both condition1 and condition2 are true
Example:
age = 20
gender = "male"
if age >= 18:
if gender == "male":
print("Adult male.")
else:
print("Adult female.")
else:
print("Minor.")
Python Loop Statements
What are Loop Statements?
Loop statements allow you to execute a block of code repeatedly based on
a condition. They are used to perform repetitive tasks efficiently.
while Loop
Syntax:
while condition:
# code to execute while condition is true
Example:
count = 0
while count < 5:
print(count)
count += 1
for Loop
Syntax:
for variable in iterable:
# code to execute for each item in iterable
Example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Using range() with for Loop
Syntax:
for variable in range(start, stop[, step]):
# code to execute
Example:
for i in range(1, 5):
print(i)
Nested Loops
Syntax:
for outer_variable in iterable1:
for inner_variable in iterable2:
# code to execute
Example:
for i in range(1, 4):
for j in range(1, 3):
print(i, j)
break Statement
Purpose: Terminates the loop prematurely.
Example:
for i in range(10):
if i == 5:
break
print(i)
continue Statement
Purpose: Skips the current iteration and proceeds to the next.
Example:
for i in range(10):
if i % 2 == 0:
continue
print