我已经通过堆栈搜索了一个答案,但所有的答案都太复杂了,我无法理解(我刚刚开始学习 Python 编程)。我想要做的就是生成一个随机数,比如在 20 到 30 之间,然后命名该随机数(因此,如果随机数为 25,则 shotDistance = 25)。以下是我目前的 mt 随机数代码,但我不断收到错误消息,例如“TypeError:不支持的操作数类型-:‘int’和‘method’”或“TypeError:不支持的操作数类型”对于 -: 'int' 和 'srt'"。因为在返回 randomNumber 后,我将其计算(totalDistanceRemaining = totalDistanceRemaining - shotDistance),这就是错误所在。
def calculateDriverShot ():
import random
random.randint(24, 36)
shotDistance = random.randint
return shotDistance
下面是带有计算的代码,其中我需要以名称 shotDistance 返回的随机数。
elif clubSelection == 'd':
calculateDriverShot ()
shotDistance = calculateDriverShot()
hitsNumber = hitsNumber + 1
totalDistanceRemaining = totalDistanceRemaining - shotDistance
print("Your shot went " + str(shotDistance) + "m. You are " + str(totalDistanceRemaining) + " from the hole, after " + str(hitsNumber) + " shot/s.")
先感谢您!
首先,你的函数空格是错误的,你不应该在函数内部导入模块。修复此问题以防止将来出现错误。接下来,在calculateShotDistance
函数中,您正在调用 randint,但是您shotDistance
通过再次调用 randint来创建一个完全不同的数字,没有任何参数(这是一个错误,因为您要求它打印一个类对象。)。再说一次,你不需要shotdistance
在函数中。这是缩短的代码,您可以修复您需要的部分。
from random import *
def calculateDriverShot()
return randint(20, 30)
shotDistance = calculateDriverShot()
我还建议您阅读一些关于函数和模块的教程(如对问题的评论)。这是一个很好的链接:http : //rwet.decontextualize.com/book/functions/
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句