【问题标题】:Trying to fix TypeError: freqRolls() missing 1 required positional argument: 'sides' python尝试修复 TypeError:freqRolls() 缺少 1 个必需的位置参数:'sides' python
【发布时间】:2019-03-12 14:39:14
【问题描述】:

我是一名新的 Python 程序员,我正在创建一个程序,该程序将随机生成骰子程序,该程序将选择要使用的骰子的面数,以便稍后我可以弄清楚如何打印骰子落在该数字上的次数。我收到“TypeError: freqRolls() missing 1 required positional argument: 'sides' 错误,当尝试打印骰子从 1 开始的面数并上升到程序决定使用的面数时。

import random
listRolls = []

#Randomly choose the number of sides of dice between 6 and 12
#Print out 'Will be using: x sides' variable = numSides
def main() :
    global numSides
    global numRolls

    numSides = sides()
    numRolls = rolls()

    rollDice()

    listPrint()

    freqRolls()

def rolls() :
    x = (random.randint(200, 500))
    print('Ran for: %s rounds' %(x))
    return x

def sides():
    y = (random.randint(6, 12))
    print('Will be using: %s sides' %(y))
    return y

def freqRolls(sides):
    for i in range(1, len(sides)) :
        print("%2d: %4d" % (i, sides[i]))

#  Face value of die based on each roll (numRolls = number of times die is 
thrown).
#  numSides = number of faces)
def rollDice():     
    i = 0
    while (i < numRolls):
        x = (random.randint(1, numSides))
        listRolls.append(x)
#            print (x)   
        i = i + 1
#        print ('Done')

def listPrint():
   for i, item in enumerate(listRolls):
      if (i+1)%13 == 0:
        print(item)
   else:
      print(item,end=', ')





main()

【问题讨论】:

  • 您定义了freqRolls 以获取一个参数sides,但您在调用freqRolls 时没有提供它。
  • 好的,我只是在调用“freqRolls”时尝试提供它,它给了我“sides()”没有 len 的错误
  • freqRolls 使用len(sides) 询问sides 似乎没有提供的长度。
  • 如果你对 Python 不够熟悉,你应该从Python tutorial开始

标签: python python-3.x


【解决方案1】:

当你在这段代码中声明了 freqrolls() 函数时

def freqRolls(sides):
    for i in range(1, len(sides)) :
        print("%2d: %4d" % (i, sides[i]))

“sides”是一个参数,这意味着函数需要一个值,并且只会在函数内部将其称为“sides”。为了你的函数工作,你需要在你调用它的那一刻传递这个值,像这样:

 freqRolls(numSides)

【讨论】:

    猜你喜欢
    • 2019-01-02
    • 1970-01-01
    • 2017-10-20
    • 2020-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-04
    相关资源
    最近更新 更多