我正在尝试编写一个python脚本,它将采用一周的天数和输入的天数。它将返回一天。例如,如果今天是星期一,那么天数是2,天数是2,它应该返回类似的输出" 2天后,它是星期三。 我尝试了以下代码
# Take the user inputs -->
today = int(input('What number day is today?(1 for Sunday, 2 for Monday and so on...) --> '))
days_after = int(input('After how many days are you coming back?'))
days_extra = days_after % 7
final_temp=today + days_extra
# Assign days based on conditions -->
if final_temp > 7:
final = final_temp-7
final_day = 1+final
elif days_extra <= 7:
final_day_o = today + days_extra
else:
pass
#Print the Results -->
if final_day == 1 or final_day_o == 1:
print('You\'ll come back on Sunday.')
elif final_day == 2 or final_day_o == 2:
print('You\'ll come back on Monday.')
elif final_day == 3 or final_day_o == 3:
print('You\'ll come back on Tuesday.')
elif final_day == 4 or final_day_o == 4:
print('You\'ll come back on Wednesday.')
elif final_day == 5 or final_day_o == 5:
print('You\'ll come back on Thursday.')
elif final_day == 6 or final_day_o == 6:
print('You\'ll come back on Friday.')
elif final_day == 7 or final_day_o == 7:
print('You\'ll come back on Saturday.')
else:
pass
但是它给出了一个错误 -
NameError:name&#39; final_day&#39;没有定义 很明显,这个名字是#final_day&#39;未分配任何值。我该如何解决这个问题?
答案 0 :(得分:0)
您未在elif
else
final_day = 0 # define final_day if first condition is not met
final_day_o = 0 # define final_day_o if second condition is not met
if final_temp > 7:
final = final_temp-7
final_day = 1+final
elif days_extra <= 7:
final_day_o = today + days_extra
else:
pass
条件之前完全声明变量。
{{1}}
答案 1 :(得分:0)
变量未定义:)所以你没有定义变量 这是正确的代码:
# Take the user inputs -->
today = int(input('What number day is today?(1 for Sunday, 2 for Monday and so on...) --> '))
days_after = int(input('After how many days are you coming back?'))
days_extra = days_after % 7
final_temp=today + days_extra
final_day = 0
final_day_o = 0
# Assign days based on conditions -->
if final_temp > 7:
final = final_temp-7
final_day = 1+final
elif days_extra <= 7:
final_day_o = today + days_extra
else:
pass
# Print the Results -->
if final_day == 1 or final_day_o == 1:
print('You\'ll come back on Sunday.')
elif final_day == 2 or final_day_o == 2:
print('You\'ll come back on Monday.')
elif final_day == 3 or final_day_o == 3:
print('You\'ll come back on Tuesday.')
elif final_day == 4 or final_day_o == 4:
print('You\'ll come back on Wednesday.')
elif final_day == 5 or final_day_o == 5:
print('You\'ll come back on Thursday.')
elif final_day == 6 or final_day_o == 6:
print('You\'ll come back on Friday.')
elif final_day == 7 or final_day_o == 7:
print('You\'ll come back on Saturday.')
else:
pass
您可以根据需要更改它,但必须在if语句
之前设置这些变量