首页 > 解决方案 > 如何修复python中的变量“t”错误?

问题描述

我有这段代码,当我尝试转换为 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

我该如何解决?

标签: python

解决方案


我刚刚清理了你的代码。另外,我修复了缩进。

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

推荐阅读