在 randint 参数中使用变量
Use variable in randint argument
这里是初学者,
我正在编写一个为用户掷骰子的程序,我希望它能够根据用户输入更改骰子的面数。我似乎无法让变量 amount_faces 用作 randint() 函数的 int,我每次都会收到 "TypeError: cannot concatenate 'str' and 'int' objetcts" 错误:
from sys import exit
from random import randint
def start():
print "Would you like to roll a dice?"
choice = raw_input(">")
if "yes" in choice:
roll()
elif "no" in choice:
exit()
else:
print "I can't understand that, try again."
start()
def roll():
print "How many faces does the die have?"
amount_faces = raw_input(">")
if amount_faces is int:
print "The number of faces has to be an integer, try again."
roll()
else:
print "Rolling die...."
int(amount_faces)
face = randint(1,*amount_faces)
print "You have rolled %s" % face
exit()
start()
有什么线索吗?
int(amount_faces)
不会就地更改 amount_faces
。您需要为整数对象分配函数 returns:
amount_faces = int(amount_faces)
amount_faces
不是可迭代对象,因此您不能在此处使用 *arg
语法:
face = randint(1,*amount_faces)
您必须删除 *
:
face = randint(1, amount_faces)
您在这里也没有正确测试整数:
if amount_faces is int:
int
是一个类型对象,amount_faces
只是一个字符串。您可以捕获 int()
抛出的 ValueError
来检测输入不可转换,而是:
while True:
amount_faces = raw_input(">")
try:
amount_faces = int(amount_faces)
except ValueError:
print "The number of faces has to be an integer, try again."
else:
break
print "Rolling die...."
face = randint(1, amount_faces)
print "You have rolled %s" % face
您可能想查看 Asking the user for input until they give a valid response 而不是使用递归进行程序控制。
这里是初学者,
我正在编写一个为用户掷骰子的程序,我希望它能够根据用户输入更改骰子的面数。我似乎无法让变量 amount_faces 用作 randint() 函数的 int,我每次都会收到 "TypeError: cannot concatenate 'str' and 'int' objetcts" 错误:
from sys import exit
from random import randint
def start():
print "Would you like to roll a dice?"
choice = raw_input(">")
if "yes" in choice:
roll()
elif "no" in choice:
exit()
else:
print "I can't understand that, try again."
start()
def roll():
print "How many faces does the die have?"
amount_faces = raw_input(">")
if amount_faces is int:
print "The number of faces has to be an integer, try again."
roll()
else:
print "Rolling die...."
int(amount_faces)
face = randint(1,*amount_faces)
print "You have rolled %s" % face
exit()
start()
有什么线索吗?
int(amount_faces)
不会就地更改 amount_faces
。您需要为整数对象分配函数 returns:
amount_faces = int(amount_faces)
amount_faces
不是可迭代对象,因此您不能在此处使用 *arg
语法:
face = randint(1,*amount_faces)
您必须删除 *
:
face = randint(1, amount_faces)
您在这里也没有正确测试整数:
if amount_faces is int:
int
是一个类型对象,amount_faces
只是一个字符串。您可以捕获 int()
抛出的 ValueError
来检测输入不可转换,而是:
while True:
amount_faces = raw_input(">")
try:
amount_faces = int(amount_faces)
except ValueError:
print "The number of faces has to be an integer, try again."
else:
break
print "Rolling die...."
face = randint(1, amount_faces)
print "You have rolled %s" % face
您可能想查看 Asking the user for input until they give a valid response 而不是使用递归进行程序控制。