[英]Issue with dice roll simulator
今天,我正在为骰子模拟器编写一些代码,但是遇到了一个问题。
这是我的代码:
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'
非常感谢您提供有关代码的帮助,
谢谢。
print ("""You have rolled a """, +dice+ """ ... """)
^ you have a spurious comma here,
这会导致Python解释器将+dice
解释为一元+
运算符,这不适用于字符串。
尝试这个:
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)))
首先,您需要将用户输入( 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.")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.