【问题标题】:Imported variable is not defined导入的变量未定义
【发布时间】:2016-12-08 00:53:02
【问题描述】:

我正在编写一个从另一个程序导入函数的简单程序。它基本上将华氏温度转换为摄氏温度,反之亦然,具体取决于您提供的输入类型。这是主程序的代码:

temp = int(input('What is the temperature? '))
print('Is this temperature in fahrenheit or celsius?')
system = int(input('Please put 1 for Fahrenheit and 2 for Celsius: '))
if system == 1:
    from tempconvert import celsius
elif system == 2:
    from tempconvert import fahrenheit
else:
    print('I dont understand.')

下面是导入函数的程序代码:

def fahrenheit():
    fahrenheit = temp * 1.8 + 32
def celsius():
    celcius = temp - 32
    celsius = celcius / 1.8

当我去做的时候,它会接受我输入的温度,它会接受华氏和摄氏之间的区别。但是它会说导入函数中的temp 没有定义。但我认为它将由主程序定义。因此,欢迎任何有关如何解决此问题的建议,因为我被困住了。

【问题讨论】:

    标签: python function python-3.x import undefined


    【解决方案1】:

    首先,您需要确保您的函数接收参数,在本例中为 temp。您还希望该函数返回一个值您的主代码块

    def fahrenheit(temp): 
        fahrenheitTemp = temp * 1.8 + 32
        return fahrenheitTemp
    
    def celsius(temp):
        celciusTemp = temp - 32
        celciusTemp = celciusTemp / 1.8
        return celciusTemp
    

    接下来您需要修改主代码块。现在您正在正确地从另一个模块导入该功能,但您没有使用它。要使用您的函数,请使用您在另一个模块中def 关键字后面指定的名称,最后是(),并将您指定的所有参数放在()

    让我们尝试获取当前温度并将其传递给您的函数,然后返回并打印转换后的温度。如下:

    temp = int(input('What is the temperature? '))
    print('Is this temperature in fahrenheit or celsius?')
    system = int(input('Please put 1 for Fahrenheit and 2 for Celsius: '))
    
    if system == 1:
        from tempconvert import celsius
        print(celsius(temp))      
    
    elif system == 2:
        from tempconvert import fahrenheit
        print(fahrenheit(temp))
    
    else:
        print('If at first you don't succeed... try try again!')
    

    【讨论】:

      【解决方案2】:

      是的,在函数中定义的名称将在模块的全局变量中查找它们被定义在中,不是它们被导入的模块。
      所有函数对象都有一个名为__globals__hidden 属性,该属性保持对包含定义 模块中可用名称的字典的引用。

      您需要使用适当的参数temp 定义您的函数,并在调用时将其传入。

      def fahrenheit(temp):
          fahrenheit = temp * 1.8 + 32
      
      def celsius(temp):
          celcius = temp - 32
          celsius = celcius / 1.8
      

      这也有一个很好的副作用,temp,作为函数的本地名称,加载速度更快:-)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-11
        • 2020-08-18
        • 2016-04-30
        • 2021-12-24
        相关资源
        最近更新 更多