自从我明年在学校开始在 IST 中编码以来,我遇到了这个涉及 if/elif/else 命令的程序的名称错误

Im encountering a name error with this program involving if/elif/else commands since Im starting coding in IST next year at school

rain = input('Is it currently raining? ')
if rain == 'Yes':
print('You should take the bus.')
elif rain == 'No':
d = int(input('How far in km do you need to travel? '))
if d >= 2:
print("You should ride your bike.")
else:
print("You should walk.")

出现的错误名称: 追溯(最近一次通话): 文件 "program.py",第 6 行,位于 如果 d >= 2: NameError:名称 'd' 未定义

根据您的错误消息,您的代码可能如下所示:

rain = input('Is it currently raining? ')
if rain == 'Yes':
    print('You should take the bus.')
elif rain == 'No':
    d = int(input('How far in km do you need to travel? '))
if d >= 2: # error happens on this line because 'd' is only defined if you answer 'No' to the first question
    print("You should ride your bike.")
else:
    print("You should walk.")

这将在不抛出该错误的情况下工作:

rain = input('Is it currently raining? ')
if rain == 'Yes':
    print('You should take the bus.')
elif rain == 'No':
    # do all of this code if rain == 'No'
    d = int(input('How far in km do you need to travel? '))
    if d >= 2:
        print("You should ride your bike.")
    else:
        print("You should walk.")