Python Topic
Control Flow in Python
1. Conditional Statements: if, else, elif
These statements allow your program to execute different blocks of code based on whether a condition is True or False.
The if Statement
-
Purpose: "If this condition is true, then do this."
-
Syntax: The code under the
ifstatement must be indented (usually 4 spaces). This is how Python defines code blocks.
python
age = 18
if age >= 18:
print("You are an adult.") # This line is inside the if-block
print("You can vote!") # This line is also inside the if-block
print("This line runs regardless") # This is outside the if-block
The else Statement
-
Purpose: "If the
ifcondition is false, then do this instead." -
Syntax: Must follow an
ifstatement.
python
temperature = 30
if temperature > 25:
print("It's a hot day!")
else:
print("It's not too hot today.")
The elif Statement
-
Purpose: Short for "else if". It allows you to check multiple conditions in sequence.
-
Syntax: Comes after an
ifand before anelse(if there is one).
python
x
temperature = 30
if temperature > 25:
print("It's a hot day!")
else:
print("It's not too hot today.")
Key Point: Python checks these conditions in order. As soon as one condition is True, it executes that block and skips the rest.
2. Loops
Loops allow you to execute a block of code multiple times.
for Loops
-
Purpose: Used for iterating over a sequence (like a list, string, or range) a known number of times.
-
Syntax:
for item in sequence:
python
# Iterating over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Output: apple, banana, cherry (each on a new line)
# Using range() to loop a specific number of times
for i in range(5): # range(5) generates numbers 0 to 4
print("Iteration number:", i)
# Iterating over a string
for letter in "Hello":
print(letter)
while Loops
-
Purpose: Repeats a block of code as long as a condition remains true. Use when you don't know how many iterations you'll need in advance.
-
Syntax:
while condition:
python
# Simple counter
count = 1
while count <= 5:
print("Count is:", count)
count += 1 # This is crucial! Without it, the loop would run forever.
# Output: Count is: 1, 2, 3, 4, 5
# User input until a condition is met
password = ""
while password != "secret123":
password = input("Enter the password: ")
print("Access granted!")
Warning: Be careful with while loops! If the condition never becomes false, you'll create an infinite loop that will crash your program.
3. Loop Control Statements: break and continue
These statements give you more precise control over how loops execute.
break
-
Purpose: Exit the loop immediately, before it has finished all its iterations.
python
x
# Simple counter
count = 1
while count <= 5:
print("Count is:", count)
count += 1 # This is crucial! Without it, the loop would run forever.
# Output: Count is: 1, 2, 3, 4, 5
# User input until a condition is met
password = ""
while password != "secret123":
password = input("Enter the password: ")
print("Access granted!")
continue
-
Purpose: Skip the rest of the current iteration and jump to the next one.
python
# Print only odd numbers
for i in range(10):
if i % 2 == 0: # If the number is even
continue # Skip the rest of this iteration
print(i)
# Output: 1, 3, 5, 7, 9
Simple way to remember:
-
break= STOP the entire loop -
continue= SKIP this one, go to the next
Putting It All Together: A Complete Example
Let's create a simple number guessing game that uses all these control flow concepts.
python
import random
# Generate a random number between 1 and 10
secret_number = random.randint(1, 10)
attempts = 0
max_attempts = 3
print("I'm thinking of a number between 1 and 10.")
print(f"You have {max_attempts} attempts to guess it!")
while attempts < max_attempts:
# Get user guess
guess = int(input("Enter your guess: "))
attempts += 1
# Check if guess is valid
if guess < 1 or guess > 10:
print("Please enter a number between 1 and 10.")
continue # Skip the rest of this iteration
# Check the guess
if guess == secret_number:
print(f"Congratulations! You guessed it in {attempts} attempts!")
break # Exit the loop - game over, player won
elif guess < secret_number:
print("Too low! Try again.")
else:
print("Too high! Try again.")
# Tell player how many attempts remain
remaining = max_attempts - attempts
if remaining > 0:
print(f"You have {remaining} attempt(s) left.")
else:
print(f"Game over! The secret number was {secret_number}.")
This program demonstrates:
-
whileloop for the main game cycle -
if/elif/elsefor checking the guess -
breakto exit when the player wins -
continueto skip invalid input
Control flow is what makes programs interactive and dynamic. Mastering these concepts is a huge step toward becoming a proficient programmer!
Comments (1)
nice