2015-08-23 132 views
1

我得到一個無限while循環蟒蛇這裏的代碼爲我擲骰子 它使擲骰子一遍又一遍 代碼:無限循環,當在Python

#!usr/bin/python 
# -*- coding: utf-8 -*- 
import random 
import time 
import sys 
print ("") 
print ("This is a dice rolling simulator ") 
x=raw_input("press Enter to launch the dice ") 
def dice(): 
    print("\nRolling the dice...\n") 
    time.sleep(1) 
    n=random.randint(1, 6) 
    if n == 1: 
     print ''' 
1 
      ''' 
    if n == 2: 
     print ''' 

      ''' 
    if n == 3: 
     print ''' 
3 
      ''' 
    if n == 4: 
     print ''' 
4 
      ''' 
    if n == 5: 
     print ''' 
5 
      ''' 
    if n == 6: 
     print ''' 
6 
      ''' 

dice() 
x=raw_input("press Enter to restart the or type q to quit") 
while x!= ("q"): 
    dice() 
if x== ("q"): 
     print ("see you later ") 
+0

你應該把代碼直接放在問題上,而不是通過一個鏈接到外部資源 –

+0

看來你修改了你的循環之外的x檢查x值。 – Baart

+0

@AnandSKumar @AnandSKumar我是一個初學者,並且在輸入代碼時出現錯誤我會嘗試 –

回答

1

您必須將raw_input()函數放入第40行的while循環中。

x=raw_input("press Enter to restart the or type q to quit") 
while x!= ("q"): 
    dice() 
    x=raw_input("press Enter to restart the or type q to quit") 
2

你是不是讀取輸入在while循環中。您應該在while循環中讀取它,因此在每次迭代中您都可以更改它,否則它將始終執行相同的計算。

你循環應該liek這樣的:

x=raw_input("press Enter to restart the or type q to quit") 
while x!= ("q"): 
    dice() 
    x=raw_input("press Enter to restart the or type q to quit") 
2

你需要得到while循環中用戶輸入...而不是

x = raw_input("press Enter to restart the or type q to quit") 
while x != ("q"): 
    dice() 

嘗試:

x = raw_input("press Enter to restart the or type q to quit") 
while x != ("q"): 
    dice() 
    x = raw_input("press Enter to restart the or type q to quit") 
0

所有的答案告訴你重複你的代碼是不好的。 Python化的解決方案是

while True: 
    dice() 
    x = ... 
    if x == 'q': break 

在這種情況下,你也可以只設置x=''開頭,但一般來說,沒有什麼不對的退出比年初別的地方一環。