gpt4 book ai didi

Python,分隔if语句

转载 作者:太空宇宙 更新时间:2023-11-04 09:00:46 25 4
gpt4 key购买 nike

我一直在做一些 python 编码,遇到了一个恼人的问题。我在一个相当大的脚本中有两个 if 语句:

    from datetime import datetime
answer_simpl = "worded_date"
if answer_simpl == "worded_date":
now = datetime.now()
day = now.day
month = now.month
year = now.year
if day == "1":
num_th = "st"
elif day == "21":
num_th = "st"
elif day == "31":
num_th = "st"
elif day == "2":
num_th = "nd"
elif day == "22":
num_th = "nd"
elif day == "32":
num_th = "nd"
elif day == "3":
num_th = "rd"
elif day == "23":
num_th = "rd"
else: num_th = "th"
if month == "1":
month_word = "January"
elif month == "2":
month_word = "Febuary"
elif month == "3":
month_word = "March"
elif month == "4":
month_word = "April"
elif month == "5":
month_word = "May"
elif month == "6":
month_word = "June"
elif month == "7":
month_word = "July"
elif month == "8":
month_word = "August"
elif month == "9":
month_word = "September"
elif month == "10":
month_word = "October"
elif month == "11":
month_word = "November"
elif month == "12":
month_word = "December"
print("The date is {}{} of".format(day,num_th),month_word,year)

当我运行它时,它会一直工作,直到它尝试打印“month_word”。它说它没有定义,但超过 24 行代码却说不对。我已经尝试了很多东西,但仍然找不到任何东西来修复它。我似乎找不到定义“month_word”的方法,因为它认为它是最后一个“else:”语句的一部分。是否有某种命令可以分隔语句?我说的是真的,它是最后一个“else:”的一部分。我真的需要一些帮助,关于这方面的任何信息都会非常有帮助!

最佳答案

您的问题是因为 daymonthyear 是整数,并且您将它们与字符串值进行比较,所以基本上您的第二个 if 语句不会执行任何 month_word = ...,因此变量 month_word 不会被定义。

将您的条件更改为整数,例如elif month == 5:.

更新

也试着想一个比这更好的实现,比如:

import calendar
from datetime import datetime

now = datetime.now()
day = now.day
month = now.month
year = now.year

num_th = {1: 'st',
21: 'st',
31: 'st',
2: 'nd',
22: 'nd',
3: 'rd'}.get(day, 'th')
month_word = calendar.month_name[month]

print("The date is {}{} of".format(day, num_th), month_word, year)

关于Python,分隔if语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25709738/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com