在 Python 2.7 的 if 语句下返回一个值

Returning a value under if statement for Python 2.7

我正在尝试计算一个数的阶乘。如果用户输入负数,我希望循环重新运行。但是,当我在 if 语句下对负值使用 return 函数时,它会给我一个

的错误
"SyntaxError: 'return' outside function"

如果用户输入负数,我如何重新运行循环。

# Calculating the Factorial of a Number

number = input ("Please enter a positive number: ")
factorial = 1

if number > 0:
    for n in range (1, number):
        factorial = factorial * (n+1)
        print ("You entered the number of " + str(number) + ". The factorial of that number is " + str (factorial))
else:
    number = input ("You entered a negative number. Please enter a positive number: ")
    return number

您在函数外确实有一个 return 语句。

How can I rerun the loop if the user enters a negative number?

使用 while 循环:

number = -1
while number < 0:
    try:
        # since factorial applies to integers only
        number = int(input("Please enter a positive number: "))
    except ValueError: # so we don't crash if the user enters a string or a float
        pass
# here number is guaranteed to be a positive integer
factorial = 1
for n in range (1, number):
    factorial = factorial * (n+1)
print 'The factorial of {number} is {factorial}'.format(number=number,
                                                        factorial=factorial)