骰子滚动模拟器问题

时间:2014-03-30 17:43:40

标签: python

今天我正在为骰子模拟器编写一些代码,但是我遇到了一个问题。

这是我的代码:

import random
dice = input("""Hello there!
Welcome to the dice roll simulator.
There are three types of dice which you can roll:
a 4 sided dice, a 6 sided dice and a 12 sided dice.
Please enter either 4,6 or 12 depending on which dice you would like to roll.""")

if dice : 4 or 6 or 12
print ("""You have rolled a """, +dice+ """ sided dice, with the result of : """,(random.randrange(1,dice)))

这个问题是它没有执行(random.randrange(1,dice))计算,而是给我以下错误信息:

Traceback (most recent call last):
  File "C:/Computing science/task 1 code.py", line 9, in <module>
    print ("""You have rolled a """, +roll+ """ sided dice, with the result of : """,(random.randrange(1,dice)))
TypeError: bad operand type for unary +: 'str'

我非常感谢我的代码提供任何可能的帮助,

谢谢。

3 个答案:

答案 0 :(得分:4)

print ("""You have rolled a """, +dice+ """ ... """)
                               ^ you have a spurious comma here,

导致Python解释器将+dice解释为一元+运算符,它不会对字符串起作用。

答案 1 :(得分:1)

试试这个:

import random
dice = input("""Hello there!
Welcome to the dice roll simulator.
There are three types of dice which you can roll:
a 4 sided dice, a 6 sided dice and a 12 sided dice.
Please enter either 4,6 or 12 depending on which dice you would like to roll.""")

if dice in (4 ,6,12) :
    print ("""You have rolled a """, dice, """ sided dice, with the result of : """,(random.randrange(1,dice)))

答案 2 :(得分:0)

首先,您需要将用户输入(str类型)转换为数字。其次,你应该期望,输入可能是错误的(例如字母而不是数字)。最后,最好使用字符串替换(使用.format()方法),而不是连接字符串 - 它更快,更易读,更容易处理不同类型的变量。

import random
try:
    dice = int(input("...message...:"))
    if dice in (4, 6, 12):
        print ("You have rolled a {}-sided dice, with the result of : {}".format(
            dice, random.randint(1, dice)))
    else:
        raise ValueError
except ValueError:
    print ("Wrong value for dice.")