我正在用Python执行一项任务,即根据输入的月份和月份中的某天来创建一个十二生肖日历。
我制作了一个成功的日历,但是,如果我输入了错误的月份名称或不存在的日期,我不知道如何解决该问题。
我尝试了很多事情:创建不同的层次结构,或者在我写的else: print ('Entering an incorrect date')
的每个十二生肖下。我什至试图用if day <0 and day> 31 or month! = 'March' or month! = 'April'
进行注册,等等……最终结果是一个巨大的无用功能,也没有任何作用。
我觉得这里有一种单行解决方案,可以检测到<0和> 31天以及不正确的月份名称,但是我听不懂。有人可以帮忙吗?
month = input('Enter the month: ')
day = int(input ('Enter the date of month: '))
if day >= 21 and day <= 31 and month.lower() == 'march' or day >=1 and day <= 19 and month.lower() == 'april':
zodiac='Aries'
if day >= 20 and day <= 30 and month.lower() == 'april' or day >=1 and day <= 19 and month.lower() == 'may':
zodiac='Taurus'
if day >= 21 and day <= 31 and month.lower() == 'may' or day >=1 and day <= 20 and month.lower() == 'june':
zodiac='Gemini'
if day >= 21 and day <= 30 and month.lower() == 'june' or day >=1 and day <= 22 and month.lower() == 'july':
zodiac='Cancer'
if day >= 23 and day <= 31 and month.lower() == 'july' or day >=1 and day <= 22 and month.lower() == 'august':
zodiac='Leo'
if day >= 23 and day <= 31 and month.lower() == 'august' or day >=1 and day <= 22 and month.lower() == 'september':
zodiac='Virgo'
if day >= 23 and day <= 30 and month.lower() == 'september' or day >=1 and day <= 22 and month.lower() == 'october':
zodiac='Libra'
if day >= 23 and day <= 31 and month.lower() == 'october' or day >=1 and day <= 21 and month.lower() == 'november':
zodiac='Scorpio'
if day >= 22 and day <= 30 and month.lower() == 'november' or day >=1 and day <= 21 and month.lower() == 'december':
zodiac='Sagittarius'
if day >= 22 and day <= 31 and month.lower() == 'december' or day >=1 and day <= 19 and month.lower() == 'january':
zodiac='Capricorn'
if day >= 20 and day <= 31 and month.lower() == 'january' or day >=1 and day <= 18 and month.lower() == 'february':
zodiac='Aquarius'
if day >= 19 and day <= 28 and month.lower() == 'february' or day >=1 and day <= 20 and month.lower() == 'march':
zodiac='Pisces'
print('Conclusion:')
print(zodiac)
答案 0 :(得分:1)
您可能想研究datetime模块。有了它,您可以轻松地在日期和时间之间进行比较,而无需多余的if语句。
例如,如果要执行以下操作:
import datetime
dt = datetime.datetime.today()
print dt.month
那么您会得到:
3
因此,您不必索要以字符串格式输入数月的信息,只需索要月份的数字即可帮助更轻松地创建datetime对象。或者,您可以执行以下操作:
month_input = input("What is the month?")
months = ["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"]
month_input = month_input.lower().strip() #convert to lowercase and remove whitespace
month_num = months.index(month_input) + 1 #Add one because lists start at index 0
这样,您可以获取使用datetime对象从那里进行比较和评估的月份数。