检查有效输入

时间:2015-02-19 19:28:34

标签: python

我对python很新,我试图将程序作为项目的一部分。我试图让程序验证用户输入,看它是否是字典键之一。

# dictionary linking month number to month name
months = {1: 'Jan', 2: 'Feb', 3: 'Mar', 4: 'Apr', 5: 'May', 6: 'Jun',
          7: 'Jul', 8: 'Aug', 9: 'Sep', 10:'Oct', 11: 'Nov', 12: 'Dec'}
# print out all the numbers and names
for num, name in months.items():
    print (str(num) + ": " + name)
monthChosen = input("Enter the number of a month (1-12)")
valid = False
while not valid:
    # make sure the user has chosen one of the correct numbers
    if monthChosen in months.keys():
        valid = True
    else:
        monthChosen = input("Make sure you enter a number (1-12)")
# return the number (int) of the month chosen
return int(monthChosen)

但是,有时当我输入有效数字时,它会起作用,有时则不会。

编辑:我使用的是Python 3

3 个答案:

答案 0 :(得分:1)

我假设你正在使用python 3。

输入接受用户输入的“字符串”,“字符串” - 您的字典键是“整数”所以只需将int()添加到每个输入调用的开头即可修复它。

# dictionary linking month number to month name
months = {1: 'Jan', 2: 'Feb', 3: 'Mar', 4: 'Apr', 5: 'May', 6: 'Jun',
          7: 'Jul', 8: 'Aug', 9: 'Sep', 10:'Oct', 11: 'Nov', 12: 'Dec'}
# print out all the numbers and names
for num, name in months.items():
    print (str(num) + ": " + name)
monthChosen = int(input("Enter the number of a month (1-12)"))
valid = False
while not valid:
    # make sure the user has chosen one of the correct numbers
    if monthChosen in months.keys():
        valid = True
    else:
        monthChosen = int(input("Make sure you enter a number (1-12)"))
# return the number (int) of the month chosen
return int(monthChosen)

答案 1 :(得分:1)

您可以使用try block,如下所示:

try:
    if int(monthChosen) in range(1,13):   #OR  if int(monthChosen) in month.keys()
        # do your stuff
except:
     # show warning

答案 2 :(得分:0)

这是一个完整的代码示例,可以帮助您。您可以使用范围(1,13),但如果您想将此相同的代码复制用于其他用途,则months.items()可以更好地工作。此外,“if not in”以更有效的方式消除了对while循环的需要。

# dictionary linking month number to month name
months = {1: 'Jan', 2: 'Feb', 3: 'Mar', 4: 'Apr', 5: 'May', 6: 'Jun',
          7: 'Jul', 8: 'Aug', 9: 'Sep', 10:'Oct', 11: 'Nov', 12: 'Dec'}
# print out all the numbers and names
for num, name in months.items():
    print (str(num) + ": " + name)

monthChosen = input("Enter the number of a month (1-12)")

if monthChosen not in months.keys():
    monthChosen = input("Make sure you enter a number (1-12)")
    if monthChosen not in months.keys():
        print "You failed to properly enter a number from (1-12)"
    else:
        print int(monthChosen)
else:
    print int(monthChosen)