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-inputnumber. 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 first define a function
calculate_factorial(). - Inside this function, we start a
while Trueloop 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
whileloop. - Finally, we print the factorial.
- We call the function
calculate_factorial()to run the program.
Similar Questions
The factorial of a number is the multiplication result from 1 to the number. For example, the factorial of 5 is 1 * 2 * 3 * 4 * 5Write code that asks the user to enter a number and display its factorial. If the user enters 0, then display "Factorial value is 1". If the user enters a number greater than 0, then display its factorial value. For example, if the user enters 4, then display "Factorial value is 24"
Write a program that takes a positive integer as input and calculates its factorial using a for loop. The factorial of a number is the product of all positive integers up to that number.
Write a shell script to find factorial of an user-defined natural number.
Write a program to calculate the factorial of N.
Python Program to Find the Factorial of a Number Without Recursion
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.