在Python中,如果变量小于或等于零,则结束while循环



对于一个学校项目,我一直在做一个游戏,允许用户猜测足球比赛的最终结果,并能够下注。我一直试图打破while循环,如果他们的平衡是小于或等于零,但一直无法这样做。整个Python代码比下面所示的要广泛得多,但这是唯一的问题。

tries = int(input("How many attempts would you like : "))
while balance > tries:
   while guesses < 2:
        print ("nYour current balance is : £",balance)
        gameresultguess = input("nWho will win - Home, Away, or Draw : ")
        bettingchoice = input("Would you like to bet this round - Yes or No : ")
        while True:
            if str.lower(bettingchoice) == "yes":
                bet = int(input("How much would you like to bet : "))
            if bet > balance: break
            print ("You have insuficient funds to bet this much, please try again")
        guesses +=1
        hometrue = random.randint(1,7)
        awaytrue = random.randint(1,5)
        if hometrue > awaytrue:
             gameresulttrue = "home"
        if awaytrue > hometrue:
             gameresulttrue = "away"
        if hometrue == awaytrue:
             gameresulttrue = "draw"
        if str.lower(gameresultguess) == gameresulttrue:
             print ("Correct! Nice guess! The final score was ",hometrue," : ",awaytrue)
             if str.lower(bettingchoice) == "yes":
                  balance = (balance + bet)
                  print ("Well played! Your bet has been doubled and added to your balance")
             if str.lower(bettingchoice) == "no":
                  print ("Unlucky... Should have placed a bet")
        else:
             print ("Unlucky! The final score was : ",hometrue," : ",awaytrue)
             if str.lower(bettingchoice) == "yes":
                  balance = (balance - bet)
                  print ("Oops... Better luck next time")
print ("Ouch... You went bankrupt. Try coming back when you have more money")

当您调用break时,它将跳出当前循环。

while True:
    if str.lower(bettingchoice) == "yes":
        bet = int(input("How much would you like to bet : "))
    if bet > balance: break
    print ("You have insuficient funds to bet this much, please try again")

在你的例子中,我相信你指的是平衡低于赌注的循环,你想结束游戏?

要做到这一点,您可以将此逻辑放入一个函数中并返回下注的"结果"。或者,如果您希望保持当前结构,则可以引发异常并捕获以打印最终的"破产"消息。

class InsufficientFundError(Exception): pass
try:
    while balance > tries:
        while guesses < 2:
            ...
            while True:
                ...
                if bet > balance:
                    raise InsufficientFundError()
except InsufficientFundError:
    print("Ouch... You went bankrupt. Try coming back when you have more money")

"我一直试图打破while循环,如果他们的余额小于或等于零,但一直无法做到这一点。"

如果余额小于或等于零,您试图打破哪个while循环?我假设是你发布的"最大"的一个,因为一个人可以继续以负余额下注是没有意义的。

要做到这一点,您必须在初始条件中设置它。试一试:
while balance > 0:

有了这个,嵌套在这个循环下的"下注过程"将在用户达到负余额时停止,或者用光了钱。

感谢您的帮助!

看完答案后,我发现这只是我早先打断陈述句的错误。很抱歉给您带来的问题。

再次感谢:)

最新更新