2014-11-14 117 views
0

我正在编写一个程序,用户将在当天月份和年份输入3个数字,并将以2014年1月2日的格式输出。这样做将用户输入日期(2014年1月4日)转换为(2014年1月4日)

year =input("what year is it") 
month=int(input("what is the numerical value of the month")) 
day=input("what number day is it") 
if month == 1: 
    January = str(month) 
    if day == 1 or 21 or 31: 
     print (day+"st January",year) 
    elif day == 2 or 22: 
     print (day+"nd January",year) 
    elif day ==3 or 23: 
     print (day+"rd January",year) 
    elif day == 4 or 5 or 6 or 7 or 8 or 9 or 10 or 11 or 12 or 13 or 14 or 15 or 16 or 18 or 19 or 20 or 24 or 25 or 26 or 27 or 28 or 29 or 30: 
     print (day+"th January",year) 

我所遇到的问题是,一天,当我输入如4将输出中的4ST一月2014 我使用python 3和已经学会了和while循环并且如果声明如果有帮助

回答

1

您运行的问题是,当您执行检查:

if day == 1 or 21 or 31: 
在Python

运算符优先级,使本声明的行为是这样的:

if (day == 1) or (21) or (31): 

和蟒蛇,像许多其他语言,非空/非零值是“true”,让你随时评估在第一次测试中为true。为了解决这个问题,修改if声明,所有下面的测试看起来更像如下:

if (day == 1) or (day == 21) or (day == 31): 
+1

或者在'[1,21,31]'' – ThinkChaos

+0

''看看我现在出错的地方现在谢谢 – Pudie12

0
year =input("what year is it") 
month=int(input("what is the numerical value of the month")) 
day=input("what number day is it") 
if month == 1: 
    January = str(month) 
    if day == 1 or day == 21 or day == 31: 
     print (day+"st January",year) 
    elif day == 2 or day == 22: 
     print (day+"nd January",year) 
    elif day ==3 or day == 23: 
     print (day+"rd January",year) 
    else: 
     print (day+"th January",year) 
2

使用库和字典,一个好的规则要记住的是,如果你需要两个以上if sa字典可能会更好。

from datetime import date 

ext_dir = {1:'st.', 2:'nd.', 3:'rd.', 
    21:'st.', 22:'nd.', 23:'rd.', 
    31:'st.' } # all the rest are th 
# prompt for the year month day as numbers remember to int them 

thedate = date(year, month, day) 
ext = ext_dir.get(day, 'th.') 
datestr = thedate.strftime('%%d%s %%M %%Y' % ext) 
相关问题