【问题标题】:python 3 Value adding elements from a list and printing the totalpython 3从列表中添加元素并打印总数
【发布时间】:2014-09-02 19:42:00
【问题描述】:

我在试图找出我的代码遇到的问题时遇到了困难。 我希望输出结果为:

Enter the high integer for the range 100
Enter the low integer for the range 20
Enter the integer for the multiples 15
List was created
The list has 5 elements.
90 75 60 45 30 
Average of multiples is 60.00

我可以弄清楚“列表已创建”部分......但是它说“列表有 5 个元素”。在我的代码中,它一直返回 30 而不是 5。我想知道是否有人可以将我指向正确的方向或部分以返回正确的值。我非常感谢您在这件事上的帮助。

def main():
    x = int(input('Enter the high integer for the range: '))
    y = int(input('Enter the low integer for the range: '))
    z = int(input('Enter the integer for the multiples: '))
    mylist = show_multiples(x,y,z)
    show_multiples(x,y,z)
    show_list(mylist)

def show_multiples(x,y,z):
    mylist = []
    for num in range(x,y,-1):
        if num % z == 0:  
            mylist.append(num)
    return mylist
    print ('List was created')

def show_list(mylist): 

    total = 0  
    for value in mylist:  
        total += value 
        average = total / len(mylist)
    print ('The list has', value, 'elements.')
    print (mylist,end=' ')
    print ()
    print ('Average of multiples is', format(average, '.2f'))

main()

【问题讨论】:

  • 为什么要给show_multiples打两次电话?
  • 另外,print ('List was created') 可能应该在 返回语句之前,如果你想实际执行那一行:-)

标签: python function python-3.x printing element


【解决方案1】:

看起来您只是打印了错误的值:

print ('The list has', value, 'elements.')

应该是:

print ('The list has', len(mylist), 'elements.')

【讨论】:

  • 非常感谢。我将重新阅读有关 len 部分的部分。我确实将“列表”放在了退货中,但现在打印了两次?
  • @WillyJoe -- 那是因为您调用了两次show_multiples。 :-)
猜你喜欢
  • 1970-01-01
  • 2011-10-11
  • 2012-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多