Python Beginner

Python Control Structures: If Statements and Loops

CodingerWeb
CodingerWeb
20 views 25 min read

Controlling Program Flow in Python

Control structures allow you to control the flow of your program. We'll learn about conditional statements and loops.

If Statements

If statements allow you to execute code based on conditions:


# Basic if statement
age = 18

if age >= 18:
    print("You are an adult")
    print("You can vote")

# If-else statement
temperature = 25

if temperature > 30:
    print("It's hot outside")
else:
    print("It's not too hot")

# If-elif-else statement
score = 85

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
elif score >= 60:
    grade = "D"
else:
    grade = "F"

print(f"Your grade is: {grade}")

Comparison Operators

Used to compare values in conditions:


a = 10
b = 5

print(a == b)  # Equal to: False
print(a != b)  # Not equal to: True
print(a > b)   # Greater than: True
print(a < b)   # Less than: False
print(a >= b)  # Greater than or equal: True
print(a <= b)  # Less than or equal: False

Logical Operators

Combine multiple conditions:


age = 25
has_license = True

# AND operator
if age >= 18 and has_license:
    print("You can drive")

# OR operator
day = "Saturday"
if day == "Saturday" or day == "Sunday":
    print("It's weekend!")

# NOT operator
is_raining = False
if not is_raining:
    print("Let's go for a walk")

For Loops

For loops iterate over sequences:


# Loop through a range of numbers
for i in range(5):
    print(f"Number: {i}")

# Loop through a string
name = "Python"
for letter in name:
    print(letter)

# Loop through a list
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
    print(f"I like {fruit}")

# Loop with range and step
for i in range(0, 10, 2):  # Start, stop, step
    print(i)  # Prints: 0, 2, 4, 6, 8

While Loops

While loops continue as long as a condition is true:


# Basic while loop
count = 0
while count < 5:
    print(f"Count: {count}")
    count += 1  # Same as count = count + 1

# While loop with user input
password = ""
while password != "secret":
    password = input("Enter password: ")
    if password != "secret":
        print("Wrong password, try again")

print("Access granted!")

Loop Control Statements


# Break statement - exits the loop
for i in range(10):
    if i == 5:
        break
    print(i)  # Prints: 0, 1, 2, 3, 4

# Continue statement - skips current iteration
for i in range(5):
    if i == 2:
        continue
    print(i)  # Prints: 0, 1, 3, 4

Practice Exercise

Create a number guessing game:


import random

# Generate random number between 1 and 100
secret_number = random.randint(1, 100)
attempts = 0
max_attempts = 7

print("Welcome to the Number Guessing Game!")
print(f"I'm thinking of a number between 1 and 100. You have {max_attempts} attempts.")

while attempts < max_attempts:
    try:
        guess = int(input("Enter your guess: "))
        attempts += 1
        
        if guess == secret_number:
            print(f"Congratulations! You guessed it in {attempts} attempts!")
            break
        elif guess < secret_number:
            print("Too low!")
        else:
            print("Too high!")
            
        remaining = max_attempts - attempts
        if remaining > 0:
            print(f"You have {remaining} attempts left.")
    except ValueError:
        print("Please enter a valid number.")

if attempts == max_attempts and guess != secret_number:
    print(f"Game over! The number was {secret_number}")