【问题标题】:Calling a function with a returned integer multiple times in Python在 Python 中多次调用返回整数的函数
【发布时间】:2022-01-08 07:45:41
【问题描述】:

我正在尝试制作一个允许用户在必要时掷骰子的龙与地下城计划。我为每个掷骰子创建了函数,因为我必须多次使用它们,而且这要容易得多。

功能:

import random
def roll20():
    roll20 = randint(1,20)
    return roll20

我创建了一个 while 循环,理论上允许用户随意掷骰子多次(请原谅,代码实际上是针对几种类型的骰子编写的,但我将其删减为仅显示d20 卷,虽然都出现这个错误):

diceDecide = input("Would you like to roll a dice? 'Yes' or 'no'...")

while diceDecide.upper() != "YES" and diceDecide.upper() != "NO":
    diceDecide = input("Would you like to roll a dice? 'Yes' or 'no' only...")
while diceDecide.upper() == "YES":
    diceRoll = input("Select a dice to roll from the list above: ")
    if diceRoll == "d20":
        roll20 = roll20()
        print("\n",roll20)

当我第一次运行它时,这非常有效。但是,如果我尝试掷同一个骰子两次,我会收到一条错误消息:

TypeError: 'int' object is not callable

我相信我知道为什么会发生错误 - Python 正在将函数调用读取为之前运行时返回的整数 - 但我丝毫不知道如何修复它。

【问题讨论】:

    标签: python python-module


    【解决方案1】:

    通过将名称 roll20 用于您的变量,您将覆盖在第一次赋值后无法再使用的函数定义。只需为变量使用不同的名称。

    【讨论】:

    • 哦,当然就是这么简单,我还以为这只是一些愚蠢的事情。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-28
    • 2014-06-16
    • 1970-01-01
    • 2021-03-24
    • 2011-03-27
    • 2018-07-06
    相关资源
    最近更新 更多