0
def factorial(number):
    number = int(number)

    if number == 1:
        return 1
    elif number == 0:
        return 1
    elif number < 0:
        return('TRY AGAIN')
    else:
        return number*factorial(number-1)



user_input = input("Enter a non-negative integer to take the factorial of: ")
factorial_of_user_input = factorial(user_input)
print(factorial_of_user_input)

input('Press ENTER to exit')
4

2 回答 2

1
def factorial(number):
    number = int(number)

    if number in (0, 1):
        return 1
    elif number < 0:
        return('TRY AGAIN')
    else:
        return number*factorial(number-1)

while True: # Keep asking till you get nothing as input.
    try:
         question = "Enter a non-negative integer to take the factorial of (enter nothing to exit): "
         user_input = input(question)
         factorial_of_user_input = factorial(user_input)
         print(factorial_of_user_input)
    except:
         break # Closes the program
于 2013-11-14T04:27:03.483 回答
0

我不是 100% 确定你的问题,也许你想要这个:

def factorial(number):
    number = int(number)
    if number > 0:
        return number * factorial(number - 1)
    elif number == 0 or number == 1:
        return 1
    else:
        return('TRY AGAIN')

user_input = None
while type(user_input) != int or user_input < 0:
    user_input = input("Enter a non-negative integer to take the factorial of: ")

factorial_of_user_input = factorial(user_input)
print(factorial_of_user_input)
于 2013-11-14T04:26:55.293 回答