Write a Python program using a while loop to calculate and display the factorial of a user-inputnumber. Ensure your program handles invalid inputs gracefully.
Question
Write a Python program using a while loop to calculate and display the factorial of a user-input number. Ensure your program handles invalid inputs gracefully.
Solution
Sure, here is a simple Python program that calculates the factorial of a user-input number using a while loop. It also handles invalid inputs gracefully:
def calculate_factorial():
while True:
num = input("Enter a positive integer: ")
if num.isdigit():
num = int(num)
if num >= 0:
break
else:
print("Invalid input. Please enter a positive integer.")
else:
print("Invalid input. Please enter a positive integer.")
factorial = 1
while num > 1:
factorial *= num
num -= 1
print("The factorial is: ", factorial)
calculate_factorial()
In this program:
- We define a function
calculate_factorial()
. - Inside this function, we start a
while True
loop to keep asking for user input until a valid positive integer is entered. - We use the
isdigit()
method to check if the input is a number. If it is not, we print an error message and continue to the next iteration of the loop. - If the input is a number, we convert it to an integer and check if it is positive. If it is not, we print an error message and continue to the next iteration of the loop.
- Once we have a valid positive integer, we calculate its factorial using a
while
loop. - Finally, we print the factorial.
- We call the
calculate_factorial()
function to run the program.
Similar Questions
Write a C++ program to find the factorial of a given integer using recursion.sample input and outputEnter a positive integer: 5 Factorial of 5 is: 120
Write a TCL proc to find the factorial of a number where the number is passed as an argument.
What happens if you attempt to calculate the factorial of a negative number in Python?
Write a python script that accept a number from the user and display a prime number from 1 to the value:
Write down the pseudocode of the factorial of n numbers and create the best-case and worst-caserecurrence relation
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.