如何修复python中的变量“t”错误?

2024-09-29 01:37:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个代码,当我试图转换成farenheit时,我得到了一个错误。它基本上是一个windchill计算器:

    import math
c = ""
f = ""
t = 0


def temp (t):
   t = (9/5 * temp_chosen) + 32
temp_chosen = float(input("What is the temperature? :"))
scale = input("Farenheit or Celsius (F/C)? ").upper()   

def wind():
   if scale == "C":
      return (t)
      print(t)

   else:
      t = temp_chosen
      print(t)

      for i in range (5, 65, 5):
         wind_chill = 35.74 + (0.6215 * t) -35.75 * (i ** 0.16) + 0.4275 * ((t)) * (i ** 0.16)
         print(f"At temperature {t}F, and wind speed {i} mph, the windchill is: {wind_chill:.2f}F")


temp (t)  
wind ()

我得到了这个错误:

Traceback (most recent call last):
  File "c:/Users/Azevedo/Documents/Codes/test.py", line 28, in <module>
    wind ()
  File "c:/Users/Azevedo/Documents/Codes/test.py", line 14, in wind
    return (t)
UnboundLocalError: local variable 't' referenced before assignment

我怎样才能解决这个问题


Tags: theininputreturnisdef错误temp
3条回答

您需要在函数顶部添加global t。因为Python在作用域中工作:在您的例子中,一个模块或脚本作用域包含直接在脚本中的所有变量、函数等(例如,完全不缩进)。以及每个函数的函数范围,每个函数都包含函数的变量。在这个例子中,您尝试引用t。作用域不是嵌套的,而是相互独立的。通过添加global t,可以使Python在模块范围而不是函数范围中查找t。请注意,全局变量被认为是糟糕的设计实践,您可以找出原因here。除此之外,您必须将return移动到打印的下方,否则它将无法执行return立即返回,之后的所有代码将永远不会执行

您试图返回一个未定义的值。它是有定义的,但你需要把它传给风。试试这段代码,修复了你的几个bug

import math
c = ""
f = ""
t = 0


def temp (t):
   t = (9/5 * temp_chosen) + 32
   return t
temp_chosen = float(input("What is the temperature? :"))
scale = input("Farenheit or Celsius (F/C)? ").upper()   
def wind(t):
   if scale == "C":
      return (t)

   else:
      t = temp_chosen
      print(t)

      for i in range (5, 65, 5):
         wind_chill = 35.74 + (0.6215 * t) -35.75 * (i ** 0.16) + 0.4275 * ((t)) * (i ** 0.16)
         print(f"At temperature {t}F, and wind speed {i} mph, the windchill is: {wind_chill:.2f}F")


t = temp (t)  
wind (t)

我只是稍微整理了一下你的代码。此外,我还修复了压痕

import math
c,f = "",""
t = 0

def wind():
    temp_chosen = float(input("What is the temperature? :"))
    scale = input("Farenheit or Celsius (F/C)? ").upper()  
    t = (9/5 * temp_chosen) + 32
    if scale == "C":
        print(t)
    else:
        t = temp_chosen
        for i in range (5, 65, 5):
            wind_chill = 35.74 + (0.6215 * t) -35.75 * (i ** 0.16) + 0.4275 * ((t)) * (i ** 0.16)
            print(f"At temperature {t}F, and wind speed {i} mph, the windchill is: {wind_chill:.2f}F")

if __name__ == "__main__":
    wind()

相关问题 更多 >