2014-01-06 65 views
-9

我在這裏有這個短代碼。但是它不是在使用python的wing ide 4.1中打印,因爲它是一個無限循環。任何想法,我可以添加或如何解決它,所以它打印?Python中的無限循環錯誤

import random 
coins = 1000 
wager = 2000 
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 
+3

縮進在Python中很重要;你能否正確地在'while'後面縮進行以反映你的代碼? –

回答

1

您發佈的代碼將不會做任何事情,只會選擇3個僞隨機數,直到時間結束。你必須添加一些贏/輸條件。截至目前,x,y和z只是數字。如果你想使一個賭博遊戲,你必須添加一些勝利條件,如:

if x + y + z > 10 

只是一個例子,但你的程序需要能夠告訴如果玩家贏了。那麼它需要改變球員的總金額並要求新的投注。您還可能需要添加邏輯以確保玩家不能比他們下注更多。

import random 
coins = 1000 
wager = 0 
while True: #main loop 
    print('you have {} coins'.format(coins)) 
    if coins == 0: #stops the game if the player is out of money 
     print('You are out of money! Scram, deadbeat!') 
     break 
    while wager > coins or wager == 0: #loops until player enters a non-zero wager that is less then the total amount of coins 
     wager = int(input('Please enter your bet (enter -1 to exit): ')) 
    if wager < 0: # exits the game if the player enters a negative 
     break 
    print('All bets are in!') 
    x = random.randint(0,10) 
    y = random.randint(0,10) 
    z = random.randint(0,10) 
    print(x,y,z) #displays all the random ints 
    if x + y +z > 10: #victory condition, adds coins for win 
     print('You win! You won {} coins.'.format(wager)) 
     coins += wager 
    else: #loss and deduct coins 
     print('You lost! You lose {} coins'.format(wager)) 
     coins -= wager 
    wager = 0 # sets wager back to 0 so our while loop for the wager validation will work 
2

你的代碼永遠不會改變coinswager,所以while條件總是真:

while ((coins>0) and (wager!= 0)): 
    # code that doesn't touch coins or wager 

也許你的意思是還減去coinsx一個,yzwager

至於爲什麼代碼不能在Wing IDE中打印;這完全取決於你的縮進。如果print語句不是循環的一部分,它們永遠不會被執行並且永遠不會執行。嘗試創建一個不能無限運行的循環。

0

因爲在while循環中沒有修改您的破壞條件。

在你的情況下,斷開狀態時wager is not 0coins > 0,所以你必須在你的代碼,例如修改無論是coinswager變量

import random 
coins = 1000; wager = 2000 
while coins > 0 and wager is not 0: 
    x,y,z = [random.randint(0,10)]*3 
    print x,y,z 
    wager-= 1000 
    coins-= 100 

作爲@martijn縮進是在python重要,參見http://en.wikipedia.org/wiki/Python_syntax_and_semantics#Indentation

for _ in range(10): 
    x = 'hello world' 
    print x 

[OUT]:

hello world 
hello world 
hello world 
hello world 
hello world 
hello world 
hello world 
hello world 
hello world 
hello world 

print x沒有縮進:

for _ in range(10): 
    x = 'hello world' 
print x 

[out ]:

hello world