while循环最终没有中断

时间:2019-02-27 13:39:16

标签: python while-loop

我做了这个《 Hangman Game》:

wordsList = ["Lampe", "Pflanze", "Bauernhof", "Katze", "Monster", 
"Weihnachtsmann", "Recycling", "Gymnastik", "Metapher", "Zyklop", "YouTube", 
"Playstation", "Artikel 13", "Kokosnuss", "Variable", "Naruto", "Musik", 
"Wandtattoo", "Taschenrechner", "Sonnenblume", "Bilderrahmen", "Videospiel"] 
 #wordslist

while True:
  x = random.randint(0,21) #Random number for choosing a word
  word = []

  print("your word: ", end='')  #show length of the word
  for y in wordsList[x]:
        if y == " ":
            print(" ", end='')
            word.append(" ")
        else:
           print("_ ", end='')
           word.append(0)

  print("")

  fails=0  #number of fails
  rdy=0    #rdy=1 if word is guessed

  while fails<=8:
        hit=0  #if hit=1 a letter was guessed, else fail++
        cnt=0
        inp = input("Input: ")
        for y in wordsList[x]:
            if (inp == y or inp.upper() == y) and word[cnt]==0:
                word[cnt]=y
                hit=1
            cnt+=1
        if hit==0:
            fails+=1
        drawHangman(fails) #draw hangman
        rdy=drawWord(word) #show guessed letters
        if rdy==1: #if rdy=1, finished
            print("")
            print("Well done!!!")
            break

  if rdy==0: #if rdy=0 and not in while-loop, lost
      print("")
      print("Game Over!!!")
      print("The word was: " + wordsList[x])

  print("Again?") #asked if wanna play again, 1=yes 0=no
  print("1: Yes")
  print("0: No")
  inp=input("Input: ")
  if inp==0:
        break

现在我遇到的问题是,最后,当我问是否要再次玩并且输入0代表否时,while循环不会中断。有人看到问题了吗?我尝试使用变量作为while-loop-condition并将其设置为False(如果您想结束但结果相同)。缩进可能有问题吗?

4 个答案:

答案 0 :(得分:3)

问题是输入不将输入存储为整数。因此,您将获得比较结果

if '0' == 0

您需要将0强制转换为字符串或将输入强制转换为整数

if int(inp)==0:

答案 1 :(得分:0)

我会在第一时间加入该条件:

inp = 0
while inp == 0:
   your_code()
   print("Again?") #asked if wanna play again, 1=yes 0=no
   print("1: Yes")
   print("0: No")
   inp=int(input("Input: "))

答案 2 :(得分:0)

其他人已经说过,input返回一个字符串。

将输入解析为整数

if int(inp) == 0:

或者您可以与'0'

进行比较
if inp == '0':

答案 3 :(得分:0)

您只需要将if inp==0:更改为if inp=="0":if inp=='0':。您需要使用字符0而不是值0进行比较。