在Python中返回外部函数错误 [英] Return outside function error in Python

查看:148
本文介绍了在Python中返回外部函数错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是问题:
假设用户在Python中输入以下程序,则用户从键盘输入数字4。

pre $ n $ int $(input(输入一个正整数:))
将返回的值是什么?

计数器= 1
(N> 0):
计数器=计数器* N
N = N - 1
返回计数器

然而,当我运行系统
时,我不断收到外部函数错误,我做错了什么?
Thanks!

解决方案

您只能从函数内部返回,而不能从循环中返回。 b
$ b

看起来你的回报应该在while循环之外,并且你的完整代码应该放在一个函数中。

  def func():
N = int(输入(输入正整数:))
计数器= 1
while(N> 0):
计数器=计数器* N
N - = 1
返回计数器#将这4个空格解除缩进到左侧。

print func()

如果这些代码不在函数内部,那么你完全不需要 return 。只需在 while循环之外打印 counter 的值。


This is the problem: Given the following program in Python, suppose that the user enters the number 4 from the keyboard. What will be the value returned?

N = int(input("enter a positive integer:"))
counter = 1
while (N > 0):
    counter = counter * N
    N = N - 1
    return counter

Yet I keep getting a outside function error when I run the system what am I doing wrong? Thanks!

解决方案

You can only return from inside a function and not from a loop.

It seems like your return should be outside the while loop, and your complete code should be inside a function.

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()

And if those codes are not inside a function, then you don't need a return at all. Just print the value of counter outside the while loop.

这篇关于在Python中返回外部函数错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆