【问题标题】:while loop not breaking in the endwhile循环最终没有中断
【发布时间】:2019-02-27 13:39:15
【问题描述】:

我制作了这个刽子手游戏:

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 如果你想结束但结果相同。也许缩进有问题?

【问题讨论】:

  • input("Input: ") 返回一个字符串。您需要将其转换为 int(或与 '0' 进行比较)。
  • @Dominique 不,break 的级别正确

标签: python while-loop


【解决方案1】:

问题在于输入没有将输入存储为整数。所以你最终会得到比较

if '0' == 0

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

if int(inp)==0:

【讨论】:

    【解决方案2】:

    我会在第一个 while 中包含条件:

    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: "))
    

    【讨论】:

    • 是的,编辑得到输入的整数。谢谢
    【解决方案3】:

    正如其他人所说,input 返回一个字符串。

    将输入解析为整数

    if int(inp) == 0:
    

    或者你可以对比'0'

    if inp == '0':
    

    【讨论】:

      【解决方案4】:

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

      【讨论】:

        猜你喜欢
        • 2017-03-19
        • 2017-01-05
        • 2017-03-10
        • 2023-02-03
        • 1970-01-01
        • 2013-04-22
        • 1970-01-01
        • 2020-10-04
        • 2017-11-14
        相关资源
        最近更新 更多