下面的代码是一个简单的骰子投掷程序。定义x是否重要?当我定义x =' a'该程序没有按预期工作。当用户输入' n' while循环不会退出。以下是代码:
from random import randint
while x != 'N' or x != 'n':
rand = randint(1, 6)
print "Your new dice number is: " + str(rand)
x = raw_input("Do you want to roll again?(y/n): ")
答案 0 :(得分:0)
你应该这样做:
from random import randint
x = "y"
while True:
rand = randint(1, 6)
print "Your new dice number is: " + str(rand)
x = raw_input("Do you want to roll again?(y/n): ")
if(x == "Y" or x == "y"):
continue
elif( x == "n" or x == "N"):
break
else:
print "Unknown Input"
break
并且循环没有中断,因为如果用户输入“N”或“n”,则在代码中没有放置break
语句
答案 1 :(得分:0)
from random import randint
你必须在while循环之前为变量X赋值:
x='s'
你的程序的第二个问题是while循环中的逻辑(尝试思考为什么它在你的情况下不能正常工作)
while not (x == 'N' or x == 'n'):
rand = randint(1, 6)
print "Your new dice number is: " + str(rand)
x = raw_input("Do you want to roll again?(y/n): ")