python 新手求指导习题.#根据给定的年月日以数字形式打印出日期months = ['January''February''March''April''May''June''July''August''September''October''November''December']#以1~31的数字作为结尾的列表endingds = ['st','n
来源:学生作业帮助网 编辑:作业帮 时间:2024/08/17 18:09:22
![python 新手求指导习题.#根据给定的年月日以数字形式打印出日期months = ['January''February''March''April''May''June''July''August''September''October''November''December']#以1~31的数字作为结尾的列表endingds = ['st','n](/uploads/image/z/13590553-49-3.jpg?t=python+%E6%96%B0%E6%89%8B%E6%B1%82%E6%8C%87%E5%AF%BC%E4%B9%A0%E9%A2%98.%23%E6%A0%B9%E6%8D%AE%E7%BB%99%E5%AE%9A%E7%9A%84%E5%B9%B4%E6%9C%88%E6%97%A5%E4%BB%A5%E6%95%B0%E5%AD%97%E5%BD%A2%E5%BC%8F%E6%89%93%E5%8D%B0%E5%87%BA%E6%97%A5%E6%9C%9Fmonths+%3D+%5B%27January%27%27February%27%27March%27%27April%27%27May%27%27June%27%27July%27%27August%27%27September%27%27October%27%27November%27%27December%27%5D%23%E4%BB%A51%7E31%E7%9A%84%E6%95%B0%E5%AD%97%E4%BD%9C%E4%B8%BA%E7%BB%93%E5%B0%BE%E7%9A%84%E5%88%97%E8%A1%A8endingds+%3D+%5B%27st%27%2C%27n)
python 新手求指导习题.#根据给定的年月日以数字形式打印出日期months = ['January''February''March''April''May''June''July''August''September''October''November''December']#以1~31的数字作为结尾的列表endingds = ['st','n
python 新手求指导习题.
#根据给定的年月日以数字形式打印出日期months = [
'January'
'February'
'March'
'April'
'May'
'June'
'July'
'August'
'September'
'October'
'November'
'December'
]
#以1~31的数字作为结尾的列表
endingds = ['st','nd','rd'] + 17 * ['th']\
+['st','nd' ,'rd'] + 7 * ['th']\
+['st']
year = input('Year:')month = input('Moth (1-12):')
day = input ('Day(1-31):')
month_number = int(month)day_number = int(day)
#记得要将月份和天数减一,以获得正确的引索month_name = months[month_number-1]
ordinal = day + endings[day_number-1]
print(month_name + ' ' +ordinal + ',' + year)
最后在运行时出现了这样的错误提示,怎么改.我用的是3.3,
Year:2012
Moth (1-12):5
Day(1-31):18
Traceback (most recent call last):
File "E:/python/日历表.py",line 29,in
month_name = months[month_number-1]
IndexError:list index out of range
>>>
python 新手求指导习题.#根据给定的年月日以数字形式打印出日期months = ['January''February''March''April''May''June''July''August''September''October''November''December']#以1~31的数字作为结尾的列表endingds = ['st','n
超出索引了,month_number-1 已经不在months这个list的索引范围了,3.3我没用过,但是看你的months写个估计有问题,难道3.3支持list里面不加逗号?估计你在每个月份后面加个逗号就好了……起码这里能过去,后面过不过得去就不好说了,我用的2.7.3
给你改了下整体的代码
#根据给定的年月日以数字形式打印出日期
months = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
]
#以1~31的数字作为结尾的列表
endings = ['st', 'nd', 'rd'] + 17 * ['th']\
+['st', 'nd' ,'rd'] + 7 * ['th']\
+['st']
year = input('Year: ')
month = input('Moth (1-12): ')
day = input ('Day(1-31): ')
month_number = int(month)
day_number = int(day)
#记得要将月份和天数减一,以获得正确的引索
month_name = months[month_number-1]
ordinal = str(day) + endings[day_number-1]
print(month_name + ' ' +ordinal + ',' + str(year))
其实上面输入的day、month和year已经是int类型了,不用再转换了,下面拼接字符串要注意类型,int类型不能和str类型直接拼接,要么转成str,要么格式化输出'%s %s %s' % (year,month,day)