python骰子掷骰模拟器,退出并再次掷骰时出现问题
我对编程和尝试用Python制作掷骰子模拟器相当陌生。我的代码是我看到的另外两个骰子程序的组合。我在尝试辞职和重新开始工作时遇到了困难。我正在使用Python 2.7.9。有什么提示吗python骰子掷骰模拟器,退出并再次掷骰时出现问题,python,Python,我对编程和尝试用Python制作掷骰子模拟器相当陌生。我的代码是我看到的另外两个骰子程序的组合。我在尝试辞职和重新开始工作时遇到了困难。我正在使用Python 2.7.9。有什么提示吗 import random def rollDice(): return random.randint(1,6) closeProgram = 0 print "Welcome to dice simulator." print " " while closeProgram != "q":
import random
def rollDice():
return random.randint(1,6)
closeProgram = 0
print "Welcome to dice simulator."
print " "
while closeProgram != "q":
numTimes = input("Enter number of dice rolls: ")
for i in range(numTimes):
print rollDice()
print "Press 'q' to quit or 'enter' to roll again."
closeProgram = input()
您需要使用
原始输入
:
closeProgram = raw_input()
Python2中的input
基本上是eval(raw_input())
,除了它不起作用之外,这也是一种安全风险
您可以将输入转换为int,而不是使用输入:
while closeProgram != "q":
numTimes = int(raw_input("Enter number of dice rolls: "))
for i in range(numTimes):
print rollDice()
closeProgram = raw_input("Press 'q' to quit or 'enter' to roll again.")
您还应使用捕获无法强制转换的用户输入:
while closeProgram != "q":
try:
numTimes = int(raw_input("Enter number of dice rolls: "))
except ValueError:
print("Integer values only allowed")
continue
for i in range(numTimes):
print rollDice()
closeProgram = raw_input("Press 'q' to quit or 'enter' to roll again.")
@logc,是的,这是真的,只需要转换为int。