检查有效输入

2024-04-19 10:21:18 发布

您现在位置: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)

然而,有时当我输入一个有效的数字,它的工作,而其他时候它没有

编辑:我正在使用python3


Tags: ofthenameinnumberinputnumprint
3条回答

下面是一个完整的代码示例,它将帮助您解决这个问题。您可以使用range(1,13),但是如果您想将相同的代码复制到其他用途,月.项()效果更好。而且,“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)

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

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

我假设您使用的是python3。你知道吗

Input接受用户输入的一个“string”,一个“string”-您的字典键是“int”,所以只需在每个Input调用的开头添加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)

相关问题 更多 >