python - 无法弄清楚无限循环的原因
问题描述
我使用 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")
它将输入与字符串值进行比较并返回一个布尔值。
推荐阅读
- php - 字符串与 . 操作员
- reactjs - npm 包“watch”给出“没有这样的文件或目录”错误
- java - 尝试从下拉列表中添加到数据库
- batch-file - 从字符串中删除子字符串
- android - 在本机反应中为垂直和水平方向添加启动画面
- javascript - 为什么主进程和渲染进程调用的window.maximize()和macos上的动画不一样?
- sql - 如何根据上一个观察日期的某些标准选择最近的观察
- teradata - 代码 = 3504:选定的非聚合值必须是关联组的一部分。输出定向到答案集选项卡
- android - Flutter app gradle 构建异常失败
- ubuntu - 没有 ssh-tunnel 的 vagrant-vm 的 Hotmodule 自动重新加载 chrome