2014-11-14 3 views
0

사용자가 월 및 일에 3 개의 숫자를 입력하고 2014 년 1 월 2 일 형식으로 출력하는 프로그램을 작성 중입니다. 지금까지 난에 실행 한이사용자 입력 날짜 (04 01 2014)를 (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 OUPUT 것으로 2014 년 1 월 나는 파이썬 3를 사용하고 있습니다 및 위해도의 경우 루프 동안 배운 입니다 문이 도움이된다면

답변

1

당신이 점검을 할 때 당신이 달린 문제는 :

0123입니다.
if day == 1 or 21 or 31: 
가 파이썬

연산자 우선 순위가 같은이 문장의 행위 일 수 있습니다 :

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

및 파이썬

이 많은 다른 언어처럼, null이 아닌/비 - 제로 값은 "을 true", 당신은 항상 평가 때문에 첫 번째 테스트에서 참. 이 문제를 해결하려면 if 문을 수정하고 다음 모든 테스트는 더 다음과 같이보고 :

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

또는 [day in [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 사전이 더 좋을 수도 있습니다.

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) 
관련 문제