Python中模块化算术计算出错

时间:2017-07-22 11:40:12

标签: python csv newline

我有以下代码,其中一个特定条目组合存在神秘错误:

它*似乎“除了输入之外还能正常工作:”星期五“和”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)更优雅的方法,通过验证,解决问题(或许使用更简单的结构)

1 个答案:

答案 0 :(得分:4)

 modanswer=int(numberofdays)%7
 answer=modanswer+dow

modanwer介于0和6(含)之间,dow介于1和7(含)之间,因此answer介于0和13之间(含)。您应该在添加后应用模运算。这可能有效:

answer = (int(numberofdays) + dow - 1) % 7 +1

-1+1是必需的,因为answer介于1和7之间,但模数会返回0到6之间的数字。

你可以简单地使用一个列表,0-index day_number和modulo:

days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']

day_number = days.index('Friday') # 4
offset = 1000
print(days[(day_number + offset) % 7])
# Thursday