def repeat_message(message, times):
for i in range(times):
print(message)
# Test your function
repeat_message("Hello world", 5)
Hello world Hello world Hello world Hello world Hello world
def max_of_two(num_1, num_2):
if num_1 > num_2:
return num_1
else:
return num_2
def max_of_three(num_1, num_2, num_3):
return max_of_two(num_1, max_of_two(num_2, num_3))
# Test your function
a = int(input("First number: "))
b = int(input("Second number: "))
c = int(input("Third number: "))
result = max_of_three(a, b, c)
print(f"The max number was {result}")
First number: 8 Second number: 13 Third number: 2 The max number was 13
Write a function that asks the user for "yes" or "no" input:
True
False
return get_yes_no()
def get_yes_no():
while True:
user_input = input("Enter yes or no: ")
if user_input == "yes":
return True
elif user_input == "no":
return False
else:
print(f"Bad input: {user_input}")
# Test your function
if get_yes_no():
print(f"You chose 'yes'")
else:
print(f"You chose 'no'")
Enter yes or no: yes You chose 'yes'
Write a function that displays a menu with 3 options and returns the user's choice (1, 2, or 3) as an integer (call int(...)
).
Ask again if not 1, 2, or 3
def get_menu_option(option_1, option_2, option_3):
print("Menu:")
print(f"1. {option_1}")
print(f"2. {option_2}")
print(f"3. {option_3}")
while True:
option = input("Enter option (1,2,3): ")
if option != "1" and option != "2" and option != "3":
print(f"Invalid input: {option}")
else:
return int(option)
option = get_menu_option("left", "right", "down")
if option == 1:
print("You chose left")
elif option == 2:
print("You chose right")
elif option == 3:
print("You chose down")
else:
print(f"Invalid option: '{option}'")
Menu: 1. left 2. right 3. down Enter option (1,2,3): 2 You chose right
Write a function fibonacci that calculates the nth Fibonacci number. The Fibonacci sequence starts with 0 and 1, and each following number is the sum of the previous two.
def fibonacci(n):
if n == 0:
return 0
if n == 1:
return 1
prev_prev_fib_num = 1
prev_fib_num = 1
for i in range(1, n):
fib_num = prev_prev_fib_num + prev_fib_num
prev_prev_fib_num = prev_fib_num
prev_fib_num = fib_num
return fib_num
def fibonacci(n):
if n == 0:
return 0
if n == 1:
return 1
return fibonacci(n-1) + fibonacci(n-2)
# Test your function
print(fibonacci(0)) # Should print: 0
print(fibonacci(1)) # Should print: 1
print(fibonacci(5)) # Should print: 5
print(fibonacci(10)) # Should print: 55
0 1 5 55