首页 > 解决方案 > 无法弄清楚无限循环的原因

问题描述

我使用 python 编写了 Hangman 游戏。在没有更多机会之后,我得到了一个无限循环。

import random
import time
import sys

# Returns a word
def get_word(): 
    words = ["apple", "sandwitch", "chance", "winner", "chicken", "dinner"]
    return random.choice(words)

# Checks whether the character is in the word or not    
def check_character(character, word, newWord):
    word = list(word)
    temp = list(newWord)
    flag = False
    for i in range(len(word)):
        if word[i] == character:
            temp[i] = character
            flag = True
        elif str(word[i]).isalpha() == True:
            pass
        else:
            temp[i] = '*'
    newWord = ''.join(temp)
    return [newWord, flag]      # flag is True if character was in word else False  


def play(name):
    chances = 3
    points = 0
    loop = True
    print("Welcome {} you have {} chances and your points are {}. ".format(name, chances, points))

    while loop:
        # This loop is getting executed infinitly after no more chances available
        word = get_word()
        print("Word is : {}".format(len(word)* '*'))
        newWord = len(word) * '*'

        while chances != 0:
            if '*' in newWord:
                character = input("Enter a character: ")
                temp = check_character(character, word, newWord)
                newWord, flag = temp[0], temp[1]
                if chances == 0:
                    print("Guess was wrong. No remaining chances .")
                    print("Your score was: {}".format(points))
                    sys.exit(0) # sys.exit() also not working after all the chances are gone
                elif flag == False and chances != 0:
                    chances = chances - 1
                    print("Guess was wrong. Chances remaining are {}".format(chances))
                else:
                    print("Word is : {}".format(newWord))
            else:
                print("Hurray!!! you have guessed the word correctly.")
                points = points + 1
                print("Your points: {}".format(points))
                print("Your remaining chances: {} ".format(chances))
                loop = input("Would you like to continue(True/False only):")
                break


print("Welcome to the Hangman Game!!!! ")
time.sleep(1)
print("Loading.", end= "")
time.sleep(1)
print(".", end= "")
time.sleep(1)
print(".", end= "")
time.sleep(1)
print(".")

name = input("Enter your Name: ")
play(name)

执行外部while循环并且剩余的工作是正确的。当没有更多机会时,无论循环值如何,外部 while 仍然执行。

删除所有错误后 有两个错误循环被强制转换为字符串,外部while循环没有机会= 3。经过一些调整后,它是工作文件,正确的代码如下,GitHub代码也已更新.

import random
import time
import sys

def get_word():
    words = ["apple", "sandwitch", "chance", "winner", "chicken", "dinner"]
    return random.choice(words)

def check_character(character, word, newWord):
    word = list(word)
    temp = list(newWord)
    flag = False
    for i in range(len(word)):
        if word[i] == character:
            temp[i] = character
            flag = True
        elif str(word[i]).isalpha() == True:
            pass
        else:
            temp[i] = '*'
    newWord = ''.join(temp)
    return [newWord, flag]        


def play(name):
    chances = 3
    points = 0
    loop = True
    print("Welcome {} you have {} chances and your points are {}. ".format(name, chances, points))

    while loop:
        chances = 3
        word = get_word()
        print("Word is : {}".format(len(word)* '*'))
        newWord = len(word) * '*'

        while chances != 0:
            if '*' in newWord:
                character = input("Enter a character: ")
                temp = check_character(character, word, newWord)
                newWord, flag = temp[0], temp[1]
                if flag == False and chances == 1:
                    print("Guess was wrong. No remaining chances .")
                    print("Your score was: {}".format(points))
                    sys.exit(0)
                elif flag == False and chances > 0:
                    chances = chances - 1
                    print("Guess was wrong. Chances remaining are {}".format(chances))
                else:
                    print("Word is : {}".format(newWord))
            else:
                print("Hurray!!! you have guessed the word correctly.")
                points = points + 1
                print("Your points: {}".format(points))
                print("Your remaining chances: {} ".format(chances))
                answer = input("Do you wish to continue ? (Y/N)").upper() 
                if answer == "N":
                    loop = False
                break    

print("Welcome to the Hangman Game!!!! ")
time.sleep(1)
print("Loading.", end= "")
time.sleep(1)
print(".", end= "")
time.sleep(1)
print(".", end= "")
time.sleep(1)
print(".")

name = input("Enter your Name: ")
play(name)


我还创建了这个程序的 GitHub 存储库,请单击此处

标签: pythonpython-3.x

解决方案


loop = input("Would you like to continue(True/False only):")

此行是您将循环设置为字符串“True”或“False”而不是布尔值的罪魁祸首

一个简单的修复将是这样的:

loop = (input("Would you like to continue(True/False only):") == "True")

它将输入与字符串值进行比较并返回一个布尔值。


推荐阅读