从 while 循环中跳出
break from the while loop
我写了一个简单的骰子游戏,除了我正在努力解决的部分外,它按预期工作,即如何在按下特定键的情况下结束游戏。我知道我犯了一个简单的错误(嗯,我是一个初学者),但如果你能指出代码有什么问题,我会很高兴。
谢谢!
import random
def game():
while True:
userRoll = int(raw_input("Enter a number from 1 to 10 [press q to end the game]: "))
compRoll = random.randrange(1, 11)
print "You rolled " + str(userRoll)
print "Computer rolled " + str(compRoll)
if userRoll > compRoll and userRoll > 0 and userRoll < 11:
print "You win!"
elif userRoll == compRoll:
print "It's a tie!"
elif userRoll < compRoll:
print "Computer wins!"
elif userRoll == 'q':
print "bye"
break
else:
print "You must enter number from 1 to 10. Try again..."
game()
此代码没有用:
elif userRoll == 'q':
print "bye"
break
在该代码执行时,您已经将 userRoll
转换为整数。所以,如果永远不能被q
。
以下代码在转换为整数之前测试 userRoll == 'q'
:
import random
def game():
while True:
userRoll = raw_input("Enter a number from 1 to 10 [press q to end the game]: ")
if userRoll == 'q':
print "bye"
break
userRoll = int(userRoll)
compRoll = random.randrange(1, 11)
print "You rolled " + str(userRoll)_
print "Computer rolled " + str(compRoll)
if userRoll > compRoll and userRoll > 0 and userRoll < 11:
print "You win!"
elif userRoll == compRoll:
print "It's a tie!"
elif userRoll < compRoll:
print "Computer wins!"
else:
print "You must enter number from 1 to 10. Try again..."
game()
我写了一个简单的骰子游戏,除了我正在努力解决的部分外,它按预期工作,即如何在按下特定键的情况下结束游戏。我知道我犯了一个简单的错误(嗯,我是一个初学者),但如果你能指出代码有什么问题,我会很高兴。
谢谢!
import random
def game():
while True:
userRoll = int(raw_input("Enter a number from 1 to 10 [press q to end the game]: "))
compRoll = random.randrange(1, 11)
print "You rolled " + str(userRoll)
print "Computer rolled " + str(compRoll)
if userRoll > compRoll and userRoll > 0 and userRoll < 11:
print "You win!"
elif userRoll == compRoll:
print "It's a tie!"
elif userRoll < compRoll:
print "Computer wins!"
elif userRoll == 'q':
print "bye"
break
else:
print "You must enter number from 1 to 10. Try again..."
game()
此代码没有用:
elif userRoll == 'q':
print "bye"
break
在该代码执行时,您已经将 userRoll
转换为整数。所以,如果永远不能被q
。
以下代码在转换为整数之前测试 userRoll == 'q'
:
import random
def game():
while True:
userRoll = raw_input("Enter a number from 1 to 10 [press q to end the game]: ")
if userRoll == 'q':
print "bye"
break
userRoll = int(userRoll)
compRoll = random.randrange(1, 11)
print "You rolled " + str(userRoll)_
print "Computer rolled " + str(compRoll)
if userRoll > compRoll and userRoll > 0 and userRoll < 11:
print "You win!"
elif userRoll == compRoll:
print "It's a tie!"
elif userRoll < compRoll:
print "Computer wins!"
else:
print "You must enter number from 1 to 10. Try again..."
game()