0
我是在ide ide中使用python的初學者,我正在嘗試編寫老虎機程序。它運行不正常,我知道它與無限循環有關,但我不確定如何修復該循環,以便代碼正常運行。有任何想法嗎?Python:老虎機代碼錯誤
import random
coins = 1000
wager = 2000
print "Slot Machine"
print "You have",coins, "coins."
print "Press 0 to exit, any other number to play that coins per spin."
while wager>coins:
print "Your Wager is greater than the number of coins you have.",
wager = input("")
while ((coins>0) and (wager!= 0)):
x = random.randint(0,10)
y = random.randint(0,10)
z = random.randint(0,10)
print x,
print y,
print z
if (x==y) and (x==z):
coins = (coins + wager)*100
print "You won",wager*100,". You now have" , coins, "coins per spin."
print "Press 0 to exit, any other number to play that many coins per spin."
elif (x==y and x==z) or (x!=y and x==z) or (x!=y and y==z):
coins = coins + wager*10
print "You won" ,wager*10,". You now have", coins, "coins."
print "Press 0 to exit, any other number to play that coins per spin."
else:
coins = coins - wager
print "You won" ,wager,". You now have", coins, "coins."
print "Press 0 to exit, any other number to play that coins per spin.",
wager = input("")
while wager>coins:
print "Your Wager is greater than the number of coins you have.",
wager = input("")
一件重要的事情!不要使用「輸入」功能。當你調用輸入時,它實際上評估你放入的任何東西,就好像它是Python代碼一樣。這意味着如果我輸入「shutil; shutil.rmtree('/',false)」我可以刪除所有文件。 相反,你可以寫'wager = int(raw_input(「」))',它將輸入作爲一個字符串,然後將其轉換爲一個整數。 – riri
如果我使用@riri發佈的調整後的代碼,輸出將會是類似於 '老虎機 你有1000個硬幣。 按0退出,其他任何數字都會在每次旋轉時播放該硬幣。 100 你輸了100。你現在有900個硬幣。 按0退出,其他任何數字都會在每次旋轉時播放該硬幣。你有900個硬幣。 按0退出,其他任何數字都會在每次旋轉時播放該硬幣。' 我該如何擺脫這樣一句話:「按0退出,其他任何數字都可以在每次旋轉時播放這些硬幣,您有900個硬幣。」我只想要一行說'按0退出,其他任何數字都可以在每次旋轉時播放這些硬幣。' –
只需在循環運行之前移動語句以使其發生。如果您剛剛開始學習編程,我建議您編寫一個程序,通過使用一個循環來打印從1到10,然後從10到1的數字。我認爲它會幫助教你如何循環工作。 – riri