Python 我的迭代在第一次之后运行时不起作用

Python 我的迭代在第一次之后运行时不起作用,python,Python,当我输入正确的单词时,它会打印祝贺,但当我第二次或第三次输入时,它就不起作用了 secret_word = "hello" tries = 1 guess_word = input("Guess a word: ") while tries < 3: if secret_word != guess_word: tries += 1 print("Sorry, word not found, you have", 4

当我输入正确的单词时,它会打印祝贺,但当我第二次或第三次输入时,它就不起作用了

 secret_word = "hello"
 tries = 1
 guess_word = input("Guess a word: ")
 while tries < 3:
        if  secret_word != guess_word:
            tries += 1 
            print("Sorry, word not found, you have", 4 - tries, "tries left")
            guess_word = input("Guess a word")
            if tries == 3:
                print("Sorry, you are out of tries, better luck next time !!!")
                break
        else:
                print("Congratulations! You've done it!")
                break
尝试永远无法达到3,正如您在尝试<3时所做的那样


在本节代码中将其更改为trys:

            print("Sorry, word not found, you have", 4 - tries, "tries left")
            guess_word = input("Guess a word")
            if tries == 3:
                print("Sorry, you are out of tries, better luck next time !!!")
在告诉用户他们输了之前,您不会检查猜测是否正确。如果将循环建立在猜测是否正确的基础上,并使用trytes计数器来决定是中断还是继续,可能会更容易:

secret_word = "hello"
tries = 0
while input("Guess a word: ") != secret_word:
    tries += 1
    if tries < 3:
        print(f"Sorry, word not found, you have {3 - tries} tries left")
    else:
        print("Sorry, you are out of tries, better luck next time !!!")
        break
else:
    print("Congratulations! You've done it!")

当你说whiletrys<3时,你只会上升到2,因为这是最后一个小于3的整数。如果你想包括3,你可以把它改成while trys如果你能把这一行

猜一个单词:

。。。在while循环中,这样就不会有两行相同的代码

您还可以将尝试次数从1改为3。设置所需的数字,并向下递减。要避免类似代码,请尝试4次

对不起,找不到单词,您有,4次尝试,剩余尝试


您当前的代码只允许进行2次尝试。第三次尝试即使你做对了,它也会被扔掉。如果我的解决方案有任何问题,请告诉我

您将永远无法在最后一次尝试中获得它,因为您将尝试次数增加到3次,请求输入,并立即告诉用户他们尝试次数不足。这意味着你只能尝试2次。第二次尝试时,您可能会正确回答。
secret_word = "hello"
tries = 3
while tries > 0:
    guess_word = input("Guess a word: ")
    if secret_word != guess_word:
        tries -= 1
        print("Sorry, word not found, you have", tries, "tries left")
        if tries == 0:
            print("Ran out of tries!")
            break
    else:
        print("Congratulations! You've done it!")
        break