Python Control Structures: Selection and Loop Programming Exercises
Python Control Structures: Practical Programming Problems
Problem 1: Find the Maximum of Three Numbers
Implement a program that reads three integers from input and determines the largest value among them.
def find_maximum():
values = list(map(int, input("Enter three numbers separated by spaces: ").split()))
max_val = values[0]
for num in values[1:]:
if num > max_val:
max_val = num
print(f"The maximum value is: {max_val}")
find_maximum()
Problem 2: Armstrong Number Checker
Check if a given three-digit number is an Armstrong number (also known as narcissistic number). An Armstrong number satisfies the condition where the sum of each digit raised to the power of 3 equals the original number.
def is_armstrong():
num_str = input("Enter a three-digit number: ")
if len(num_str) != 3 or not num_str.isdigit():
print("Invalid input")
return
digits = [int(d) for d in num_str]
total = sum(d ** 3 for d in digits)
if total == int(num_str):
print("YES")
else:
print("NO")
is_armstrong()
Problem 3: Monkey and Peaches
A monkey eats half of the peaches plus one each morning. On the 10th morning, only one peach remains. Calculate the initial number of peaches.
def calculate_initial_peaches():
peaches = 1
for day in range(9, 0, -1):
peaches = (peaches + 1) * 2
print(f"Initial number of peaches: {peaches}")
calculate_initial_peaches()
Problem 4: Exchange Deal Calculation
Calculate the total amount exchanged in a deal where: - A stranger gives $100,000 daily for 30 days - A wealthy person gives double the previous day's amount starting from $0.01
def exchange_calculation():
stranger_total = 0
wealthy_total = 0
daily_wealthy = 0.01
for day in range(30):
stranger_total += 100000
wealthy_total += daily_wealthy
daily_wealthy *= 2
print(f"Stranger gives: ${stranger_total:,.2f}")
print(f"Wealthy gives: ${wealthy_total:,.2f}")
exchange_calculation()
Problem 5: Ball Bouncing Physics
A ball falls from 100 meters. After each bounce, it reaches half the previous height. Calculate the total distance traveled after the 10th bounce and the height of the 10th bounce.
def ball_physics():
height = 100
total_distance = height
for bounce in range(1, 11):
height /= 2
total_distance += height * 2
print(f"Total distance: {total_distance:.2f} meters")
print(f"10th bounce height: {height:.2f} meters")
ball_physics()
Problem 6: Collatz Sequence
Generate and display the Collatz sequence starting from a given positive integer. The sequence follows: if even, divide by 2; if odd, multiply by 3 and add 1.
def collatz_sequence():
try:
num = int(input("Enter a positive integer: "))
if num <= 0:
print("Please enter a positive integer")
return
except ValueError:
print("Invalid input")
return
while num != 1:
if num % 2 == 0:
num //= 2
else:
num = num * 3 + 1
print(num, end=" ")
print()
collatz_sequence()
Problem 7: Dice Roll Combinations
Display all unique combinations when rolling two dice (1,2 and 2,1 are considered the same combination).
def dice_combinations():
combinations = []
for die1 in range(1, 7):
for die2 in range(die1, 7):
combinations.append(f"{die1}+{die2}")
print(", ".join(combinations))
dice_combinations()
Problem 8: Day of Year Calculator
Calculate which day of the year a given date represents (input format: YYYY-MM-DD).
def day_of_year():
date_input = input("Enter date (YYYY-MM-DD): ")
try:
year, month, day = map(int, date_input.split('-'))
except:
print("Invalid date format")
return
days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if (year % 400 == 0) or (year % 4 == 0 and year % 100 != 0):
days_in_month[1] = 29
day_number = sum(days_in_month[:month-1]) + day
print(f"Day of year: {day_number}")
day_of_year()
Problem 9: Compound Interest Calculator
Calculate the final amount after 5 years with an initial principal of 10,000 and an annual interest rate of 0.3%.
def compound_interest():
principal = 10000
rate = 0.003
years = 5
amount = principal * ((1 + rate) ** years)
print(f"Amount after {years} years: ${amount:.2f}")
compound_interest()
Problem 10: Even-Digit Numbers
Find all numbers between 1000 and 3000 (inclusive) where every digit is even. Display results separated by commas.
def even_digit_numbers():
result = []
for num in range(1000, 3001):
if all(int(digit) % 2 == 0 for digit in str(num)):
result.append(str(num))
print(",".join(result))
even_digit_numbers()