《python基础教程(第二版)》里给出的打印日期的代码为什么运行时总是出现list index out of range

代码如下
刚开始学python…可能描述的不清楚…

months = [
    'January'
          'February'
          'March'
          'April'
          'may'
          'June'
          'July'
          'September'
          'August'
          'October'
          'November'
          'December'
]
endings = ['st','nd','rd'] + 17 * ['th']\
        + ['st','nd','rd'] + 7 * ['th']\
        + ['st']
year  = raw_input('Year:')
month = raw_input('Month(1-12):')
day   = raw_input('Day(1-31):') 
month_number = int(month)
day_nubmber = int(day) 
month_name = months[month_number-1]
ordinal = day + endings[day_number-1]
print month_name + ' ' + ordinal + ',' + year

----------------分割线----------------
回@lohocla4dam
我修改以后是这样的……
NameError: name 'day_number' is not defined

代码如下

months = [
'January',
      'February',
      'March',
      'April',
      'may',
      'June',
      'July',
      'September',
      'August',
      'October',
      'November',
      'December'
]

endings = ['st','nd','rd'] + 17 * ['th']\
    + ['st','nd','rd'] + 7 * ['th']\
    + ['st']
year  = raw_input('Year:')
month = raw_input('Month(1-12):')
day   = raw_input('Day(1-31):')

month_number = int(month)
day_nubmber = int(day)

month_name = months[month_number-1]
ordinal = day + endings[day_number-1]
print month_name + ' ' + ordinal + ',' + year
阅读 4.3k
3 个回答

你没有发现你给months赋值的时候少写了逗号吗。。。

题主试试这段代码就明白了

s = ['January'
     'February']

t = ['January',
     'February']

print(s, t)
新手上路,请多包涵

day_nubmber 你拼错了吧。。。

新手上路,请多包涵

day_number 拼写错了 = =

推荐问题
logo
101 新手上路
子站问答
访问
宣传栏