The intent of this program is to allow a user to enter an integer and then print the factorial of that integer. The user must be notified of the sentinel value. The user will continue to be prompted to enter an integer and see the associated factorial until the sentinel value is entered at which point the program will stop. Use a while loop for getting inputs and a for loop to calculate and output the factorial.
Here's a Python program that meets your requirements for calculating the factorial of an integer using a while loop for input and a for loop for calculating the factorial. The sentinel value chosen for this program is -1
, which will terminate the program when entered by the user.
# Program Header
print("########## Program #3 – Factorial Calculator ###########")
# Sentinel value
sentinel = -1
while True:
# Prompt user for input
user_input = input("Please enter a non-negative integer (or -1 to exit): ")
# Convert input to integer
try:
number = int(user_input)
except ValueError:
print("Invalid input. Please enter an integer.")
continue
# Check for sentinel value
if number == sentinel:
print("Exiting the program.")
break
elif number < 0:
print("Please enter a non-negative integer.")
continue
# Calculate factorial using a for loop
factorial = 1
for i in range(1, number + 1):
factorial *= i
# Output the result
print(f"The factorial of {number} is {factorial}.")
-1
, which will be used to exit the loop.-1
to exit the program.