Now that you understand how to guide your program's execution using conditional statements and loops, it's time to put that knowledge into practice. The following exercises will help solidify your understanding of if
, elif
, else
, while
, for
, break
, and continue
. Working through these problems is a significant step towards writing more dynamic and useful Python programs.
Remember, the goal isn't just to get the right answer, but to understand why the code works. Don't hesitate to experiment, modify the examples, and try different approaches.
Write a Python script that asks the user for their age and then prints a message indicating whether they are a "Minor" (under 18), an "Adult" (18 to 64), or a "Senior" (65 and older).
Guidance:
input()
function to get the age from the user. Remember that input()
returns a string.int()
. You might want to wrap this in a try-except
block later (as learned in Chapter 9) to handle non-numeric input gracefully, but for now, assume valid input.if-elif-else
structure to check the age against the defined ranges.# Get input (Remember to convert to integer)
# age_str = input("Please enter your age: ")
# age = int(age_str)
# Check the age ranges using if/elif/else
# if age < 18:
# print(...)
# elif age >= 18 and age <= 64: # Or simply: elif age <= 64: since the first 'if' failed
# print(...)
# else: # Must be 65 or older
# print(...)
while
Create a script that uses a while
loop to count down from 5 to 1, printing each number. After the loop finishes, print "Blast off!".
Guidance:
count = 5
).while
loop that continues as long as the count is greater than 0.count = count - 1
or count -= 1
).count > 0
becomes false), print the final message.# Initialize counter
# counter = 5
# Loop while counter is positive
# while counter > 0:
# Print the counter
# print(counter)
# Decrement the counter
# counter -= 1
# Print the final message after the loop
# print("Blast off!")
for
Given the list numbers = [12, 7, 9, 21, 15]
, write a script using a for
loop to calculate and print the sum of all the numbers in the list.
Guidance:
total_sum = 0
).for
loop to iterate through each number
in the numbers
list.number
to the total_sum
.total_sum
.# Given list
# numbers = [12, 7, 9, 21, 15]
# Initialize sum accumulator
# current_sum = 0
# Iterate through the list
# for num in numbers:
# Add current number to the sum
# current_sum += num # Shorthand for current_sum = current_sum + num
# Print the final sum
# print("The sum is:", current_sum)
Write a program that simulates a simple number guessing game.
secret_number = 8
).for
loop to give the user a limited number of guesses (e.g., 3 attempts). The range()
function can be helpful here.input()
and convert it to an integer.break
to exit the loop immediately.Guidance:
range(3)
to loop exactly three times.guessed_correctly = False
set before the loop and changed to True
upon a correct guess can help determine the final message.# secret_number = 8
# guessed_correctly = False
# max_attempts = 3
# print("Guess the number between 1 and 10. You have 3 attempts.")
# for attempt in range(max_attempts):
# guess_str = input(f"Attempt {attempt + 1}: Enter your guess: ")
# guess = int(guess_str)
# if guess == secret_number:
# print("Correct! You guessed it!")
# guessed_correctly = True
# break # Exit the loop
# else:
# print("Sorry, that's not it.")
# After the loop, check if the user succeeded
# if not guessed_correctly:
# print(f"Sorry, you've run out of attempts. The number was {secret_number}.")
(Optional Enhancement for Exercise 4): Modify the guessing game to use continue
. If the user enters a guess outside a valid range (e.g., less than 1 or greater than 10), print an error message and use continue
to skip the rest of the current loop iteration and proceed directly to the next attempt without penalizing them for the invalid input (or perhaps still count it as an attempt, depending on your game rules).
Use nested for
loops to print the following pattern:
*
**
***
****
*****
Guidance:
i
is i
.print()
function's end
parameter (print("*", end="")
) within the inner loop to print asterisks on the same line.print()
statement to move the cursor to the next line before the outer loop starts its next iteration.# number_of_rows = 5
# Outer loop for rows
# for i in range(1, number_of_rows + 1): # range(1, 6) gives 1, 2, 3, 4, 5
# Inner loop for columns (asterisks in the current row)
# for j in range(i): # range(i) gives 0 to i-1, so it runs 'i' times
# print("*", end="")
# Move to the next line after printing all asterisks for the current row
# print()
These exercises cover the core concepts of conditional logic and looping. Try variations, combine concepts (e.g., use if
statements inside loops, as in the guessing game), and build confidence in controlling how your Python programs execute.
© 2025 ApX Machine Learning