2015-08-23 131 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=''开头,但一般来说,没有什么不对的退出比年初别的地方一环。