用户输入循环

User input loop

我无法让这段简短的代码工作。我想做的是要求用户输入一个 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")

使用if-else代替try-except:

while True:
    word=input("Please enter a four letter word: ")

    if len(word) == 4:
        print("Thanks")
        break
    else:
        print("That's not a four letter word. Try again: ")