在python中限制和验证输入

问题描述 投票:0回答:1

我试图限制我输入的字符长度,然后验证它是否是三个白字之一。挣扎在最后一部分。

while True:
    try:
        letter=input("Please enter a character: ") #most intuitive way for me was the assert function but very happy to hear any other ways
        assert len(letter) !=1
    except AssertionError:
        print("Please type only ONE character")
    else:
        whitespace=["\n"," ","\t"] #i believe the list specification here makes the not in code invalid? believe the two may not be compatible but errors not reached there yet
        if whitespace not in letter:
            print("Your character in lower case is: "+str(letter).lower())
        else:
            print("You typed a white space character!")
python-3.x validation user-input
1个回答
1
投票

欢迎来到Stackoverflow!

看起来错误是在 if whitespace not in letter: 行。其实应该是反过来的。if item not in list:. 你有 if list not in item:.

另外,如果我把你的代码重新格式化一下,可能会对你有帮助。

while True:
    letter = input('Please enter a character: ')

    if len(letter) != 1:
        print('Please type only ONE character')
        continue

    if letter in ['\n', ' ', '\t']:
        print("You typed a white space character!")
        continue

    lowercase_letter = letter.lower()
    print(f'Your character in lower case is: {lowercase_letter}')

如果你还没有看到 pylint我建议你看看它。它可以帮助你按照PEP8标准格式化你的代码。它还能很好地指出你代码中的一些简单错误。

Raising Exceptions是用于向调用函数的人报告错误--即由于输入或系统状态不符合函数的要求,你不能执行函数应该做的工作。

Catching Exceptions是用来处理特定的错误,你知道如何在更高层次的函数中处理。例如,如果你试图读取一个文件,但它不存在。在你的程序中,这意味着用户没有在配置文件中设置一个特定的标志......所以你可以捕获这个异常,让用户知道如何解决这个问题。

引起一个 Exception 并在同一个函数中捕获它(至少在这种情况下)只是一种非常复杂的写法。if 声明。

当写一个 if-else 声明,它是一个很好的想法,试图使。if 枝正。这意味着要避免 if not ...: else: 如果可以的话。

在你的代码中。letter 已经是一个字符串对象了--所以不需要使用 str(letter). 在python中,所有的东西都是一个对象,甚至是字面意思。

在Python中,所有的东西都是对象,甚至包括文字。continue 语句跳转到下一个循环的迭代。循环之后的 continue 在循环的当前迭代中被执行。你也可以看一下 break 语句来完成循环的执行。作为一个练习,你可以考虑在你的代码中增加一个额外的检查,看看用户是否输入了 "quit",然后再输入 break. 你认为会发生什么?

if letter.lower() == 'quit':
    break

这必须添加在单字母检查之前,否则你永远不会进入这个检查。

最后,在打印语句中不要使用字符串连接(使用 str + str). 你可以使用f-字符串,格式化字符串,就像例子中的 f'Hi my name is {name} and I am from {home}',其中 namehome 是字符串变量。

希望这对你有帮助!我建议你不要使用异常,因为它们非常不稳定。


1
投票

我建议你不要使用异常,因为它们非常不稳定。相反,我会使用ifelse条件,比如这个。

    letter = input('Please enter a character: ')
    if len(letter) == 1:
        if letter in '\n\t ':
            print('You typed a white space character!')
        else:
            print('Your character in lowercase is {}'.format(letter.lower()))
    else:
        print('Please type only ONE character')```
© www.soinside.com 2019 - 2024. All rights reserved.