gpt4 book ai didi

python - 在 randint 参数中使用变量

转载 作者:太空宇宙 更新时间:2023-11-03 17:58:35 24 4
gpt4 key购买 nike

这里完全是初学者,

我正在编写一个为用户掷骰子的程序,我希望它能够更改每个用户输入的骰子面数。我似乎无法让变量 amount_faces 作为 randint() 函数的 int 工作,每次都会收到“TypeError:无法连接 'str' 和 'int' 对象”错误:

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。您需要分配函数返回的整数对象:

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并且不使用递归进行程序控制。

关于python - 在 randint 参数中使用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28096235/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com