2014-01-06 10 views
-9

여기에이 짧은 코드가 있습니다. 그러나 그것은 무한 루프이기 때문에 파이썬을 사용하여 날개 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

코드는 결코 coins또는wager를 변경 없기 때문에 while 조건은 항상 진정한 입니다 :

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

은 아마 당신은 또한 coins에서 x 중 하나 y 또는 z을 뺄 의미 나 wager?

코드가 Wing IDE에서 인쇄되지 않는 이유는 무엇입니까? 이것은 완전히 들여 쓰기에 달려 있습니다. print 문이 루프의 일부가 아닌 경우 절대로 실행되지 않으며 절대로 실행되지 않습니다. 무한하게 돌아 가지 않는 루프를 만들어보십시오.

0

while 루프에서 차단 조건이 수정되지 않았기 때문에. wager is not 0coins > 0, 그래서 당신이 당신의 코드, 예를 들어,에 coins 또는 wager 변수 중 하나를 수정해야 할 때 경우

는 파괴 조건은 @martijn 들여로서

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 

파이썬 중요 http://en.wikipedia.org/wiki/Python_syntax_and_semantics#Indentation 참조 :

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

[출력]

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