繁体   English   中英

检查有效输入

[英]Checking valid inputs

我对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

我假设您正在使用python 3。

输入采用用户输入的“字符串”,即“字符串”-您的字典键为“ ints”,因此只需在每个输入调用的开头添加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)

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

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

这是一个完整的代码示例,可以帮助您。 您可以使用range(1,13),但是如果您想复制同一代码以用于其他用途,则months.items()会更好。 同样,“如果不在”则以更有效的方式消除了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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM