【发布时间】:2021-04-18 06:32:23
【问题描述】:
这里是 Python 新手。
我的任务是创建一个包含月份的字典,然后要求用户输入数字。如果数字是 1-12,则返回月份名称,如果用户输入了任何其他数字,则返回“请输入 1-12 范围内的有效数字”,如果用户输入了其他任何内容(fe“什么?”) - 返回 ' {input} 不是数字!'
到目前为止,我的第一个问题是默认情况下输入是字符串。我决定更改类型,但是当用户输入除整数以外的任何内容时出现问题 - 我得到 ValueError: invalid literal for int() with base 10: 'd' 但是如果我留下类型字符串,当用户输入 12..
时我会遇到问题这是我目前所拥有的:
# 1. Create dictionary
months = {
1: 'January',
2: 'February',
3: 'March',
4: 'April',
5: 'May',
6: 'June',
7: 'July',
8: 'August',
9: 'September',
10: 'October',
11: 'November',
12: 'December'
}
# 2. Create input
answer = input('Please input a number of the month: ')
answer = int(answer)
# 3. Create possible outcomes
if answer == 1:
print(months[1])
if answer == 2:
print(months[2])
if answer == 3:
print(months[3])
if answer == 4:
print(months[4])
if answer == 5:
print(months[5])
if answer == 6:
print(months[6])
if answer == 7:
print(months[7])
if answer == 8:
print(months[8])
if answer == 9:
print(months[9])
if answer == 10:
print(months[10])
if answer == 11:
print(months[11])
if answer == 12:
print(months[12])
if answer < 1 or answer >12:
print('Please input valid number in range 1-12!')
提前谢谢你!
【问题讨论】:
-
欢迎来到 SO。这里的问题是针对特定问题提出的,并得到特定的答案。虽然无论如何你都会得到一般性的建议,但提出具体问题可以帮助人们在遇到相同问题时找到这个问题。例如,一个更好的问题标题应该是“如何将用户输入解释为整数?”
标签: python dictionary if-statement input types