python - 用户输入循环

标签 python python-3.x loops user-input

我无法让这段简短的代码工作。我想做的是要求用户输入一个 4 个字母的单词,如果他们不输入,则要求他们重试,如果他们输入,则表示感谢。我添加了 while True, try & except 部分,因为它看起来是继续循环的最佳方式,但我并没有真正理解它。

while True:
    try:
        word=input("Please enter a four letter word: ")
        word_length=len(word)
    except word_length != 4:
        print("That's not a four letter word. Try again: ")
        continue
    else: 
        break

if word_length ==4:
    print("Thanks")

最佳答案

except 用于捕获异常(其他语言使用 trycatch 代替)。

在这种情况下,您只需使用一个简单的 if 来检查该值是否是您想要的:

while True:
    try:
        word = input("Please enter a four letter word: ")
        word_length = len(word)
    except TypeError:
        print('error getting word length')
    else:
        if word_length != 4:
            print("That's not a four letter word. Try again: ")
        else:
            break

if word_length == 4:
    print("Thanks")

关于python - 用户输入循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60157648/

相关文章:

python - * : 'instance' and 'float' 不支持的操作数类型

python - 如何改进 Python 中的这个循环以提高速度

python - Django 应用程序中的 UnicodeEncodeError

python - 在 Windows 10 上为 Python 3 安装 OpenCV

python - 以美分计的水量成本

python-3.x - 使用 pyspark 跟踪具有附加条件的前一行值

python - 使用 fill_ Between 函数绘制直线拟合中的不确定性 : "The truth value of an array with more than one element is ambiguous."

c - 如何使用 'while(true)' 避免 'break' 而使用 'for' 循环?

loops - 汇编8086,LOOP指令不停

javascript - Javascript/jQuery 中的 Python 部分等价物