无法跳出 While 循环 [英] Can't Break Out of While Loop

查看:46
本文介绍了无法跳出 While 循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了以下python代码.它需要我在互联网上找到的英语单词列表,并将它们列成一个列表,以便我可以将它们用于刽子手.那么我的问题是,每次我运行这个程序并成功猜出这个词时,它都没有跳出 while 循环.它只是继续前进.我无法弄清楚为什么我的生活.任何人都知道为什么不向获胜者打印最终消息?

I wrote the following python code. It takes a list of English words I found on the internet and makes them a list so that I can use them for hangman. Well my problem is that every time I run this program and successfully guess the word, it doesn't break out of the while loop. It just keeps going. I can't figure out why for the life of me. Anyone have any clue as to why it isn't printing the final message to the winner?

import random

words = []

lettersGuessed = []

isGuessed = 0



wordFile = open(r'C:\Users\Sarah\PycharmProjects\hangman\words.txt')

for word in wordFile:
    words.append(word.rstrip(wordFile.readline()))


mysteryWord = random.choice(words)

while len(mysteryWord) <= 1:
    mysteryWord = random.choice(words)

for letter in mysteryWord:
    print("?", end = "")
print("\n")

def isWon():
    #win conditions
    count = 0
    for letter in mysteryWord:
        if letter in lettersGuessed:
            count += 1

        if count == len(mysteryWord):
            isGuessed = 1



count = 0

while isGuessed == 0:


    guess = input("Guess a letter \n")

    if guess.upper() or guess.lower() in mysteryWord:
        lettersGuessed.append(guess)
        for letter in mysteryWord:
            if letter in lettersGuessed:
                print(letter, end ='')
            else:
                print("?", end = '')
    print("\n")
    count = 0
    isWon()
    if isGuessed == 1:
        break

print("Congratulations, you correctly guessed ", mysteryWord)

推荐答案

isGuessed 在您的顶级代码中,isGuessedisWon 函数中是两个不同的变量.一个函数是一个单独的命名空间(否则一个函数使用一个具有通用名称的变量,如 i 会在其他代码中造成严重破坏).

isGuessed in your top-level code and isGuessed in isWon function are two different variables. A function is a separate namespace (else a function using a variable with common name like i would wreak havoc in other code).

这可以通过global 声明来解决,但这是一种非常糟糕的风格.同样适用于 mysteryWordlettersGuessed 等变量.

This can be solved by a global declaration, but it's a very bad style. Same applies to variables like mysteryWord and lettersGuessed.

相反,您应该从 isWon 函数返回值:

Instead, you should return the value from the isWon function:

def isWon(mysteryWord, lettersGuessed):
   # do your counting...
   return isGuessed

# main code
victory = False
while not victory:
   # ...
   victory = isWon(mysteryWord, lettersGuessed)
   # you don't even need the if ... break statement

顺便说一句,您对所有猜出的字母的检查都可以单行:

BTW your check for all letters being guessed can be made a one-liner:

def isWon(mysteryWord, lettersGuessed):
    return set(lettersGuessed) == set(mysteryWord)

这篇关于无法跳出 While 循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆