[英]Can't figure out the reason of Infinite loop
我使用 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 存储库,请单击此处。
loop = input("Would you like to continue(True/False only):")
这一行是你将循环设置为字符串“True”或“False”而不是布尔值的罪魁祸首
一个简单的修复是这样的:
loop = (input("Would you like to continue(True/False only):") == "True")
它将输入与字符串值进行比较并返回一个布尔值。
你的循环至少有两个逻辑错误。
第一个错误是您要求用户在此行中输入 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
移动到第一个循环的开头,而不是在它之前。
您的主循环使用条件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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.