【发布时间】:2017-07-22 11:40:11
【问题描述】:
我有以下代码,其中一个特定的条目组合出现了一个神秘的错误:
除了输入“Friday”和“1000”之外,它*似乎“可以正常工作,它会引发变量错误。
完整代码清单: https://repl.it/Jd6a/0
代码
#Use of Modulo Arithmetic
def main():
DAY="Monday"
print("Here's a little modulo magic for ya...")
dayofweek=input("Enter day of week (e.g. Monday, Tuesday, Wednesday, etc:")
numberofdays=input("Enter number of days from that day of the week you would like to calculate:")
if dayofweek=="Monday":
dow=1
elif dayofweek=="Tuesday":
dow=2
elif dayofweek=="Wednesday":
dow=3
elif dayofweek=="Thursday":
dow=4
elif dayofweek=="Friday":
dow=5
elif dayofweek=="Saturday":
dow=6
elif dayofweek=="Sunday":
dow=7
modanswer=int(numberofdays)%7
answer=modanswer+dow
if answer==1:
finalanswer="Monday"
elif answer==2:
finalanswer="Tuesday"
elif answer==3:
finalanswer="Wednesday"
elif answer==4:
finalanswer="Thursday"
elif answer==5:
finalanswer="Friday"
elif answer==6:
finalanswer="Saturday"
elif answer==7:
finalanswer="Sunday"
print(numberofdays,"days from -",dayofweek,"-will be-",finalanswer)
main()
测试(正确)和错误如下所示
Here's a little modulo magic for ya...
Enter day of week (e.g. Monday, Tuesday, Wednesday, etc: Monday
Enter number of days from that day of the week you would like to calculate: 1000000
1000000 days from - Monday -will be- Tuesday
main()
Here's a little modulo magic for ya...
Enter day of week (e.g. Monday, Tuesday, Wednesday, etc: Friday
Enter number of days from that day of the week you would like to calculate: 1000
Traceback (most recent call last):
File "python", line 1, in <module>
File "python", line 42, in main
UnboundLocalError: local variable 'finalanswer' referenced before assignment
我在寻找什么:
我对 a) 对问题进行解释的解决方案感兴趣 b) 更优雅的方法,通过验证来解决问题(也许使用更简单的构造)
【问题讨论】: