对于一个学校项目,我一直在制作一个游戏,允许用户猜测足球比赛的最终结果,并能够在那里下注预测。如果他们的余额小于或等于零但我无法这样做,我一直试图打破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")
答案 0 :(得分:1)
当你打电话给休息时,它会突破你当前的循环。
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")
在你的例子中,我相信你指的是平衡低于赌注的循环,你试图结束游戏?
为此,您可以将此逻辑转换为函数并返回&#34;结果&#34;赌注。或者,如果您希望保留当前结构,则可以引发异常并捕获以打印最终的&#34;破产&#34;消息。
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")
答案 1 :(得分:0)
&#34;我一直试图打破while循环,如果他们的余额小于或等于零但是无法这样做。&#34;
如果余额小于或等于零,你试图打破哪个while循环?我假设&#34;最大&#34;你发布的一个,因为人们可以继续用负余额进行投注是没有意义的。
为此,您必须将其设置为初始条件。尝试:
// Ajax Success function
$.playSound('../static/sounds/cash-register', 'next_page');
// Play sound function
(function($){
$.extend({
playSound: function(){
var $ele = $("<embed src='"+arguments[0]+".mp3' hidden='true' autostart='true' loop='false' class='playSound'>" + "<audio autoplay='autoplay' style='display:none;' controls='controls'><source src='"+arguments[0]+".mp3' /><source src='"+arguments[0]+".ogg' /></audio>").appendTo('body');
$ele.on('ended', function() {
window.location.replace(arguments[1]);
});
}
});
})(jQuery);
通过此,您的投注流程&#34;当用户达到负余额或资金不足时,嵌套在此循环下的将停止。
答案 2 :(得分:0)
感谢您的帮助!!
在看完答案之后,我看到这只是我错误地提前打破了陈述。对不起,问题就在这了。
再次感谢:)