如何阻止这种无限循环

时间:2016-03-16 05:37:39

标签: python loops while-loop infinite

我试图做一个数字猜谜游戏,如果用户匹配他们赢得现金的幸运数字,游戏继续进行,直到他们用完现金。他们为每轮比赛支付赌金。每一轮都会生成一个新的随机数。

我只想使用一个输入。 当我将输入放在循环中时,循环无限循环停止,当我将它带到循环外时,它开始无限循环。我怎么阻止这个?我需要在while循环中添加什么? 我试过休息,但我想继续游戏,直到钱不见了。

我只想使用一个输入,但是当我将输入输出循环(lucky_guess)时,它会永远持续下去。我只想让用户猜一次。

funds = 1000
stake = 1
luckyNumber = 25 #test number #random number from 1 - 30

while funds != 0:
    funds = funds - 1
    print("Your Funds", funds)
    luckyGuess = int(input("enter a number")) #this is the problem if i take this out, the loop wont stop

    if luckyNumber == luckyGuess:
        print("Number is",luckyNumber, " You Win, +35 added to your funds")
        funds = funds + 35
    else:
        print("Fail, Try Again")

3 个答案:

答案 0 :(得分:0)

我认为格式应该是这样的:

funds = 1000
stake = 1
luckyNumber = 25 #test number #random number from 1 - 30

while funds != 0:
   funds = funds - 1
   print("Your Funds", funds)
   luckyGuess = int(input("enter a number"))

   if luckyNumber == luckyGuess  :
       print("Number is",luckyNumber, " You Win, +35 added to your funds")
       funds = funds + 35
   else:
       print("Fail, Try Again")

答案 1 :(得分:0)

使用break关键字退出循环:

funds = 1000
stake = 1
luckyNumber = 25 #test number #random number from 1 - 30

while funds != 0:
    funds = funds - 1
    print("Your Funds", funds)
    luckyGuess = int(input("enter a number")) #this is the problem if i take this out, the loop wont stop

    if luckyNumber == luckyGuess:
        print("Number is",luckyNumber, " You Win, +35 added to your funds")
        funds = funds + 35

        break
    else:
        print("Fail, Try Again")

您可以在the documentation

中找到有关控制流指令的更多信息

答案 2 :(得分:0)

也许这有帮助

funds = 1000
stake = 1
luckyNumber = 25 #test number #random number from 1 - 30

while funds != 0:
    funds = funds - 1
    print("Your Funds", funds)
    play = input("play more? (y/n)")
    if( ( play == 'y') or (play == 'Y')): #condition to check for continuing gameplay
        luckyGuess = int(input("enter a number"))
    else:
        break
    if luckyNumber == luckyGuess  :
        print("Number is",luckyNumber, " You Win, +35 added to your funds")
        funds = funds + 35
    else:
        print("Fail, Try Again")