无法摆脱循环

时间:2017-04-29 04:30:04

标签: python while-loop

我编写了以下python代码。它需要我在互联网上找到的英文单词列表,并将它们列为一个列表,以便我可以将它们用于刽子手。我的问题是,每次我运行这个程序并成功猜出这个词时,它都不会突破while循环。它只是继续前进。我无法弄清楚为什么对我的生活。任何人都有任何线索,为什么它不打印最终消息给赢家?

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)

5 个答案:

答案 0 :(得分:0)

当前的问题是isWon()未设置isGuessed,无论输入如何。如果您猜测字符串&#34; foo&#34;然后

lettersGuessed.append(guess)

lettersGuessed列为一个包含一个项目的列表。我想你要做的是

lettersGuessed.extend(list(guess))

guess中的每个字母添加到lettersGuessed列表中。

还有两点值得一提:

  • isWon()如果您在问题中猜出单词的字谜,则会认为游戏赢了&#34; OOF&#34;如果单词是&#34; foo&#34;
  • ,将被视为正确的解决方案
  • words.append(word.rstrip(wordFile.readline()))正在读取输入文件的每个偶数行,并在删除与下一个单词共有的任何字符后将其添加到words列表中。您希望改为words.append(word.strip())

答案 1 :(得分:0)

您的顶级代码中的

isGuessedisGuessed函数中的isWon是两个不同的变量。函数是一个单独的命名空间(否则使用常见名称如i的变量的函数会在其他代码中造成严重破坏)。

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

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

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

顺便说一句,你所检查的所有字母的支票都可以单行:

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

答案 2 :(得分:0)

一切都与范围有关。 isWon()中使用的isGuessed在本地范围内定义。如果您想影响全局范围内声明的isWon(),则必须将其作为参数传递给global,或在修改isGuessed之前使用def isWon(): #win conditions count = 0 for letter in mysteryWord: if letter in lettersGuessed: count += 1 if count == len(mysteryWord): global isGuessed isGuessed = 1 关键字。见下文:

python3 test.py
?????

Guess a letter
1
?????

Guess a letter
2
?????

Guess a letter
3
????3

Guess a letter
4t
????3

Guess a letter
t
t??t3

Guess a letter
e
te?t3

Guess a letter
s
test3

Congratulations, you correctly guessed  test3

使用此更改输出:

#loading

答案 3 :(得分:0)

您尝试使用全局变量is_guessed进行通信,但isWon函数没有给出global is_guessed行,因此它设置了一个本地变量到isWon is_guessed而不是全局变量。

我的建议是,不是将global is_guessed添加到isWon(),而是从True返回FalseisWon()(取决于是否用户赢了)并使用它来结束循环。

以下是您的代码的替代版本:

import random

words = []
with open(r'C:\Users\Sarah\PycharmProjects\hangman\words.txt') as wordFile:
    for word in wordFile:           # assuming one word per line
        words.append(word.strip())  # iterating a file reads one line per iteration

mysteryWord = random.choice(words)
mysteryLetters = set(mysteryWord.lower())
lettersGuessed = set()

def isWon():
    return mysteryLetters == (lettersGuessed & mysteryLetters)

while not isWon():
    for letter in mysteryWord:
        if letter in lettersGuessed:
            print(letter, end ='')
        else:
            print("?", end = '')
    print()

    guess = input("Guess a letter \n")[:1].lower()

    if guess in mysteryWord:
        lettersGuessed.add(guess)

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

答案 4 :(得分:0)

嗯,我知道我的答案有点晚了,但这是我的解决方案:

#!/usr/bin/env python3

import random

word_file_name = "/usr/share/dict/canadian-english"

with open(word_file_name) as word_file:
    # I'm assuming your input file has one word per line and that
    # you want to keep only words that has more than one letter
    words = [word.rstrip() for word in word_file if len(word) > 1]

mystery_word = random.choice(words)

# Using sets helps to remove duplicate letters and eases membership tests 
letters_mystery = set(mystery_word.upper())
letters_guessed = set()

not_guessed = True

while not_guessed:
    # We create a list with all the letters found or not
    letters_to_show = [letter if letter.upper() in letters_guessed else "?"
                       for letter in mystery_word]
    # We join them before printing them
    print("".join(letters_to_show), "\n")

    guess_received = input("Guess a letter :")
    if guess_received.strip():
        # We only keep the first letter received
        guess_kept = guess_received[0].upper()

        if guess_kept in letters_mystery:
            letters_guessed.add(guess_kept)

    # We determine if we need to continue
    not_guessed = letters_guessed != letters_mystery

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

关键点:

  • list comprehension用于将单词放入列表中
  • Sets用于保留一组没有重复的字母。
  • conditional expression用于选择是显示字母还是?
  • Truth testing可用于简化某些信息的验证
  • 你在C中使用类似isGuessed == 1的表达式,其中True等于1,False等于0.在Python中,变量可以是布尔值。您可以直接在if声明
  • 中使用它