变量名未定义

时间:2018-11-11 15:57:51

标签: python

运行该程序时,我不断收到错误消息,提示未定义fahrenheit

代码如下:

def morning():
celsius = int(input('How many degrees C is the temperature in the morning: '))
fahrenheit = 9 / 5 * celsius + 32
return fahrenheit


print('%.1f' % fahrenheit + "F")

morning()


def evening():
celsius = int(input("How many degrees C is the temperature in the evening: "))
fahrenheit = 9 / 5 * celsius + 32
return fahrenheit


print('%.1f' % fahrenheit + "F")

evening()

for i in range(0, 1):
if i is 0:
    morning()
else:
    evening()

    if fahrenheit <= 79:
        print("This morning is cold")
    else:
        if fahrenheit <= 90:
            print("It is a little warm this morning")
        else:
            print("It is quite hot today")

if fahrenheit <= 79:
    print("Tonight is cold")
else:
    if efahrenheit <= 90:
        print("It is a little warm this evening")
    else:
        print("It is quite hot tonight")

if fahrenheit and efahrenheit <= 79:
    print("It was cold today")
else:
    if fahrenheit and efahrenheit <= 90:
        print("The weather was warm today")
    else:
        print("Today was quite hot today")

2 个答案:

答案 0 :(得分:0)

问题在于您在方法内部声明了fahrenheit变量,但是您试图在它们之外使用它。 要被允许这样做,您需要在方法之外创建它。 例如,像这样:

fahrenheit = morning()

现在,您可以使用该变量了

答案 1 :(得分:0)

下面是代码,除了最后一个if / else块外,所有其他工作正常且使用单个函数。

def temp():

cel_morn = float(input("Enter morning temperature in degrees:"))
fah_morn = (9/5 * cel_morn) + 32
print("Temperature in Fahrenheit ", fah_morn)

if fah_morn <= 79:
    print("This morning is cold")
elif fah_morn <= 90:
    print("It is a little warm this morning")
else:
    print("It is quite hot today")

cel_eve = float(input("Enter evening temperature in degrees:"))
fah_eve = (9/5 * cel_eve) + 32
print("Temperature in Fahrenheit ", fah_eve)

if fah_eve <= 79:
    print("Tonight is cold")
elif fah_eve <= 90:
    print("It is a little warm this evening")
else:
    print("It is quite hot tonight")


if fah_morn and fah_eve <= 79:
    print("It was cold today")
elif 80 < fah_morn < 91 or 80 < fah_eve < 91:
    print("The weather was warm today")
else:
    print("Today was quite hot today")

temp()