这是问题: 在Python中给出以下程序,假设用户从键盘输入数字4。返回的价值是多少?在Python中返回外部函数错误
N = int(input("enter a positive integer:"))
counter = 1
while (N > 0):
counter = counter * N
N = N - 1
return counter
然而,我不断收到一个外功能错误,当我运行系统 我究竟做错了什么? 谢谢!
这是问题: 在Python中给出以下程序,假设用户从键盘输入数字4。返回的价值是多少?在Python中返回外部函数错误
N = int(input("enter a positive integer:"))
counter = 1
while (N > 0):
counter = counter * N
N = N - 1
return counter
然而,我不断收到一个外功能错误,当我运行系统 我究竟做错了什么? 谢谢!
您有一个return
语句不在函数中。功能由def
关键字开始:
def function(argument):
return "something"
print function("foo") #prints "something"
return
没有意义的功能之外,所以Python会引发一个错误。
您只能从函数内部返回,而不能从循环中返回。
看起来你的回报应该在while循环之外,你的完整代码应该在函数内。
def func():
N = int(input("enter a positive integer:"))
counter = 1
while (N > 0):
counter = counter * N
N -= 1
return counter # de-indent this 4 spaces to the left.
print func()
如果这些代码是不是一个函数里面,那么你并不需要一个return
可言。只需在while loop
之外打印counter
的值。
正如其他贡献者已经解释的那样,您可以打印出计数器,然后用break语句替换返回值。
N = int(input("enter a positive integer:"))
counter = 1
while (N > 0):
counter = counter * N
N = N - 1
print(counter)
break
[Python的return语句错误 “ '回归' 之外的功能”]的可能的复制(http://stackoverflow.com/questions/7842120/python-return-statement-error-return-outside-function) – tripleee 2016-09-14 14:49:39