Python 当用户输入除4、6或12以外的任何内容时,向用户发送错误消息
在下面的代码中,我想添加一些东西,当用户输入除4、6或12以外的任何内容时,会向用户发送错误消息:Python 当用户输入除4、6或12以外的任何内容时,向用户发送错误消息,python,Python,在下面的代码中,我想添加一些东西,当用户输入除4、6或12以外的任何内容时,会向用户发送错误消息: 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 die, a 6 sided die and a 12 sided die. Please enter either 4,
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 die, a 6 sided die and a 12 sided die.
Please enter either 4,6 or 12 depending on which die you would like to roll.""")
if dice : 4 or 6 or 12
print("You have rolled a " + dice + " sided dice, with the result of : " + str((random.randrange(1,int(dice)))))
这比我之前提到的更像Python,但是你应该记住Python中的或并不像你想象的那样直观;也就是说,x==6或7
必须写成x==6或x==7
如下所述,如果在Python2.x中使用input()
,则不必将其强制转换为int,但如果在2.x中使用raw\u input()
或在3.x中使用input()
,则必须强制转换,否则将导致类型错误
编辑:因为您使用的是输入,所以必须将其转换为int,因为input
将返回一个字符串
正如两位炼金术士所指出的,在Python2.x中,raw\u input()
相当于Python3.x中的input()
Python2.x中的input()
相当于Python3.x中的eval(input())
有关Python2.x与3.x中输入类型的差异,请参见您要查找的是else
语句
在这里开始提问之前,我建议您先做一个基本的python教程
dice = int(dice)
if dice in {4, 6, 12}:
print("..." + str(dice))
else:
print("error message")
我想你可能会对:
的意思感到困惑
:
表示这一行是块的开头,下一行或者缩进(请用4个空格),或者全部在一行上
您所写的(4或6或12
)实际上是在布尔上下文中计算这些数字。因为在Python中,任何非0的数字都是真的,所以实际计算结果为:True或True或True
当然,这没有任何作用,它只是坐在那里——因为如果骰子:
实际上就是它被评估的地方
你可能想要的是如果掷骰子(4,6,12):…
此外,它看起来像input
返回一个字符串,你想首先将输入结果转换为整数:dice=int(dice)
我想我以前从未见过如此多的重复答案。取决于Python2/Python3。Python2试图计算输入的返回值。为什么这里是一个集合而不是元组?(将做同样的事情,只是从来没有见过有人这样写。)好吧,对于3个元素,查找速度可能会慢一些。。。这只是我的代码风格。对集合进行哈希可能需要更长的时间。在这种情况下,元组比列表更快(从我读到的内容来看),不过可能更清楚一些。我的意思是,我们真正的意思是“如果结果不在包含4、6和12的集合中”,而不是某种有序的三元组,或者你通常会解释一个三元组。你需要在第一条消息中将dice
掷到str
。
dice = int(dice)
if dice in {4, 6, 12}:
print("..." + str(dice))
else:
print("error message")