python骰子滚动模拟器,退出和滚动的问题再次

时间:2015-04-13 13:16:29

标签: 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":
    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()

1 个答案:

答案 0 :(得分:3)

您需要使用raw_input

closeProgram = raw_input()
python 2中的

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.")

您还应该使用try/except来捕获无法投射的用户输入:

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.")