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

时间:2015-12-12 11:25:57

标签: python if-statement return factorial

我正在尝试计算一个数字的阶乘。如果用户输入负数,我希望循环重新运行。但是,当我在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

1 个答案:

答案 0 :(得分:1)

你在函数之外有一个return语句。

  
    

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

  

使用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)