【问题标题】:Can't use the variables of a function in another function for Python不能在 Python 的另一个函数中使用函数的变量
【发布时间】:2018-02-05 15:29:52
【问题描述】:

我遇到了一个非常简单的问题,但我无法理解它。

我试图让用户输入所需的网站名称,然后用它来决定在另一个函数中使用的全名。这是该函数的基础知识。

def website():
    x = input("Enter url:")
    global url
    if 'Google' in x:
        url = ("www.google.com")
    else:
        "Try again!"
        website()

这只有在我有全局 url 时才有效。否则,它会破裂。在主函数中,它尝试立即使用来自 website() 的输出 url,但返回:

NameError: name 'url' is not defined

如果全局 url 不存在。下一个函数从字面上打印前一个函数的结果。它会做得更多,但由于我什至无法打印它,我还没有到那个阶段。

【问题讨论】:

  • 您可以使用return urlwebsite 函数返回 到主作用域url。然后在主作用域上,您需要将website 的调用分配给一个变量,例如my_url = website()
  • 你能再扩展一点吗?
  • @Versace 你到底尝试过什么,怎么没用?
  • @Versace 这不可能。再试一次。
  • 您一定犯了其他错误——我们看不到,因为您的问题只有原始代码。请更新您的问题以获得返回值的新代码,并包括主调用代码。

标签: python function scope


【解决方案1】:

您可以通过从函数返回变量来传递变量。如:

def foo():
    url="google.com"
    return url  #this will send the variable URL to wherever it was called from
def bar(url):
    print url

bar(foo())  #this calls the function `bar()` 

函数bar()接受一个我们称为url的变量(这不需要与函数foo()中的变量相同,但可以)。然后在括号内我们调用foo(),它返回url 内的数据。

【讨论】:

    【解决方案2】:

    我不明白也看不出你有什么尝试或没有尝试过,但我会尽力猜测:

    def website():
        x = input("Enter url:")
        if 'Google' in x:
            url = ("www.google.com")
            return url
        else:
            print("Try again!")
            return website()
    
    if __name__ == '__main__':
        url = website()
        print(url)
    

    但请注意,如果此递归调用被调用超过 1024 次(在默认实现中),则可能会给您带来麻烦(堆栈溢出)。

    最好做

    def website():
        while True:
            x = input("Enter url:")
            if 'Google' in x:
                url = ("www.google.com")
                return url
            print("Try again!")
    

    人们可能会觉得使用无限循环很难看,但它优于递归调用。

    【讨论】:

      猜你喜欢
      • 2020-06-12
      • 2016-01-16
      • 1970-01-01
      • 2012-06-06
      • 1970-01-01
      • 2014-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多