简体   繁体   English

无法弄清楚无限循环的原因

[英]Can't figure out the reason of Infinite loop

I programmed the Hangman game using python.我使用 python 编写了 Hangman 游戏。 I'm getting an Infinite loop after no more chances remaining.在没有更多机会之后,我得到了一个无限循环。

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)

The outer while loop is executed and remaining working is proper.执行外部 while 循环,其余工作正常。 When there are no more chances the outer while still execute irrespective of the loop value.当没有更多机会时,无论循环值如何,外部 while 仍然会执行。

After removing all the errors There were two errors the loop was typecasted to string and the outer while loop was not having chances = 3. After a few tweaks it is working file the correct code is below and also the GitHub code has been updated as well.删除所有错误后,有两个错误将循环类型转换为字符串,而外部 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)


I have also created a GitHub repository of this program click here .我还创建了该程序的 GitHub 存储库,请单击此处

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

This line is your culprit you are setting loop to the string "True" or "False" not a boolean value这一行是你将循环设置为字符串“True”或“False”而不是布尔值的罪魁祸首

A Simple fix would be something like :一个简单的修复是这样的:

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

Which compares the input to a string value and returns a boolean value.它将输入与字符串值进行比较并返回一个布尔值。

There are at least two logical mistakes with your loops.你的循环至少有两个逻辑错误。

The first mistake is that you asked the user to enter True or False in this line:第一个错误是您要求用户在此行中输入 True 或 False:

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

But this will be entered as a string, not a Boolean, so the outer loop will continue forever regardless of what the user enters.但这将作为字符串输入,而不是布尔值,因此无论用户输入什么,外循环都将永远继续。 You need to convert it to a Boolean eg using您需要将其转换为布尔值,例如使用

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

The second mistake is that if the user does want to play again, you need to reset chances , otherwise it will still be zero, and the user will never get the opportunity to make a guess on the next game.第二个错误是,如果用户确实想再次玩,则需要重置chances ,否则仍然为零,用户将永远没有机会对下一场比赛进行猜测。 So you should move chances = 3 to the start of the first loop, instead of before it.因此,您应该将chances = 3移动到第一个循环的开头,而不是在它之前。

Your main loop using the condition while loop .您的主循环使用条件while loop However, in your code:但是,在您的代码中:

  • You never break that loop你永远不会break那个循环
  • You change the loop value using loop = input("Would you like to continue(True/False only):")您使用loop = input("Would you like to continue(True/False only):")更改循环值

The input will return a string, and in you while assertion:输入将返回一个字符串,并在你的while断言:

  • If the string is "", then it is equivalent to False如果字符串是"",那么就等价于False
  • Otherwise, if the string is anything else, it is equivalent to True否则,如果字符串是其他任何东西,则等价于True

Therefore, if your user inputs ANYTHING, it will be treated as "loop is still true".因此,如果您的用户输入任何内容,它将被视为“循环仍然为真”。

To fix your problem, you must handle the user input要解决您的问题,您必须处理用户输入

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM