【问题标题】:Trouble with return between functions [duplicate]函数之间的返回问题[重复]
【发布时间】:2021-03-26 22:44:06
【问题描述】:

我是 python 和一般编码的初学者,不知道为什么下面代码中的 return 不会跨函数移动。不应该存储 n 的值以供所有函数使用吗? print(n) 在那里只是为了我自己看它是否有效,显然不是。

def main():
    print("This program tests the Goldbach's conjecture")
    get_input()
    print(n)


def get_input():
    n = 0
    while n == 0:
        try:
            v = int(input("Please enter an even integer larger than 2: "))
            if v <= 2:
                print("Wrong input!")
                continue
            if v%2 == 1:
                print("Wrong input!")
                continue
            if v%2 == 0:
                n = v
        except ValueError:
            print("Bad input!")
            continue
    return n

【问题讨论】:

  • 标记的重复是多余的。但是,几乎所有有关 Python 函数的教程都提供了此范围信息。请从intro tour 重复on topichow to ask。 Stack Overflow 无意取代现有的文档和教程。

标签: python return goldbach-conjecture


【解决方案1】:

您没有将get_input 返回的值存储在任何地方,您应该将其保存在变量中(或直接打印),例如 -

def main():
    print("This program tests the Goldbach's conjecture")
    val = get_input()
    print(val)

n是一个内部变量,只存储在get_input的范围内。

【讨论】:

  • 哦,好的,所以 return 仅根据调用函数以响应的变量来存储变量。谢谢!
猜你喜欢
  • 2020-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-12
  • 1970-01-01
  • 2015-10-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多