onditional Statements in Python
Conditional statements allow your program to make decisions based on certain
conditions. They execute different blocks of code depending on whether a condition
is True or False. Python uses the if, elif (short for "else if"), and else keywords
for this.
Basic Structure
if: Checks a condition. If true, runs the indented code block.
elif: Checks another condition if the previous if or elif was false.
else: Runs if all previous conditions are false (optional).
Indentation (usually 4 spaces) defines the code block—Python is strict about this!
Example: Simple Age Checker
pythonage = int(input("Enter your age: "))
if age >= 18:
print("You are an adult!")
elif age >= 13:
print("You are a teenager!")
else:
print("You are a child!")
How it works: If you enter 20, it prints "You are an adult!". For 15, "You are a
teenager!". For 10, "You are a child!".
Key Notes:
Conditions use comparison operators: == (equal), != (not equal), >, <, >=, <=.
You can chain multiple elif for more options.
Use logical operators: and, or, not for complex conditions, e.g., if age >= 18 and
age < 65:.
Looping Statements in Python
Loops repeat a block of code multiple times, either for a fixed number of
iterations or until a condition is met. Python has two main types: for (for known
iterations) and while (for unknown iterations).
1. for Loop
Iterates over a sequence (like a list, string, or range).
Great for going through items one by one.
Example: Printing Numbers 1 to 5
pythonfor i in range(1, 6): # range(start, stop) – stop is exclusive
print(i)
Output:
text1
2
3
4
5
Example: Looping Through a List
pythonfruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I like {fruit}!")
Output:
textI like apple!
I like banana!
I like cherry!
Key Notes:
range(n) generates 0 to n-1.
Use break to exit early, continue to skip an iteration.
for with else: Runs else if no break occurred (rarely used).
2. while Loop
Repeats as long as a condition is True.
Useful when you don't know how many iterations upfront (e.g., user input until
valid).
Example: Guessing Game
pythonsecret = 7
guess = 0
while guess != secret:
guess = int(input("Guess the number (1-10): "))
if guess < secret:
print("Too low!")
elif guess > secret:
print("Too high!")
print("Correct! You guessed it.")
How it works: Keeps asking until you guess 7 correctly.
Key Notes:
Beware of infinite loops (e.g., while True: without break)—always have an exit
condition!
Like for, supports break, continue, and else (runs if no break).
When to Use What?
Conditionals: For branching logic (e.g., "if this, do that").
Loops: For repetition (e.g., process a list or wait for input).
Combine them! E.g., if inside a for loop for filtering.
Practice in a Python interpreter—these are foundational for writing flexible code.
If you want examples for specific scenarios, let me know!