Python - 一周中不正确的打印

时间:2015-02-13 00:43:56

标签: python

下面我有一个代码,应该要求用户输入该月的某一天。我们假设月份从星期一开始,有31天。如果用户输入的月份日期不是该月的有效日期(小于1或大于31),则打印"无效日期"。否则打印当天的那一天。

例如,第二个是星期二,第十个星期三是等等。

我遇到的问题是,每当我输入一周中的任何数字时,它会继续打印。如果我输入第一个,它应该打印星期一,如果我输入第二个,它应该打印出星期二,依此类推,直到我进入第31个。

我想知道为什么它只在星期三显示。

#Description: Ask user to enter a day in the month.
#The dayof the month can not be less than 1 
#or greater than 31 or it's invalid.

#Enter the day of the week
#Description: Ask user to enter a day in the month.
#The dayof the month can not be less than 1 
#or greater than 31 or it's invalid.


DayofMonth = int(input("Enter the day of the month: "))

if DayofMonth >= 1 and DayofMonth <= 31:    
    days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] 
    DayofMonth = 31
    dx = DayofMonth + 1 
    #print (days [dx % 7]) 


    print("The day of the week is: ", days [dx % 7])
else:
    print("Invalid day")

1 个答案:

答案 0 :(得分:1)

这是因为您在接受输入后立即将DayofMonth分配给硬编码值31:

DayofMonth = int(input("Enter the day of the month: "))

if DayofMonth >= 1 and DayofMonth <= 31:
    days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] 


    dx = DayofMonth + 1 # omitted extra line 
    print("The day of the week is: ", days [dx % 7])