无法找出无限循环的原因

时间:2020-02-28 13:18:14

标签: python python-3.x

我使用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循环没有机会=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)


我还创建了该程序click here的GitHub存储库。

3 个答案:

答案 0 :(得分:2)

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

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

一个简单的修复方法是:

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

将输入与字符串值进行比较,然后返回布尔值。

答案 1 :(得分:2)

循环中至少存在两个逻辑错误。

第一个错误是您要求用户在此行中输入True或False:

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

但是这将作为字符串而不是布尔值输入,因此无论用户输入什么,外部循环将永远继续。您需要将其转换为布尔值例如使用

loop = input("Would you like to continue (True/False only):")
loop = loop.lower() == 'true' # do case-insensitive comparison to get a Boolean

第二个错误是,如果用户确实想再次玩游戏,则需要重置chances,否则它将仍然为零,并且用户将永远没有机会猜测下一个游戏。因此,您应该将chances = 3移到第一个循环的开头,而不是在它之前。

答案 2 :(得分:1)

您的主循环使用条件while loop。但是,在您的代码中:

  • 您永远不会break循环
  • 您可以使用loop = input("Would you like to continue(True/False only):")
  • 更改循环值

输入将返回一个字符串,并且在您的while断言中:

  • 如果字符串为“”,则等效于False
  • 否则,如果字符串为其他字符串,则等效于True

因此,如果您的用户输入了任何内容,它将被视为“循环仍然为真”。

要解决您的问题,您必须处理用户输入

answer = input("Do you wish to continue ? (Y/N)").upper() ?
if answer == "N":
    loop = False