Python3从列表中添加元素并打印总数
在试图找出代码中存在的问题时,我遇到了困难。 我希望输出结果为:Python3从列表中添加元素并打印总数,python,function,python-3.x,printing,element,Python,Function,Python 3.x,Printing,Element,在试图找出代码中存在的问题时,我遇到了困难。 我希望输出结果为: 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 我可以算出“列表是
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()
看起来您只是打印了错误的值:
print ('The list has', value, 'elements.')
应该是:
print ('The list has', len(mylist), 'elements.')
为什么要调用
show_multiples
两次呢?另外,print('List was created')
如果您想实际执行该行,可能应该在return语句之前执行:-)非常感谢。我将重读关于len部分的部分。我确实把“列表”放在了报税表里面,但现在打印了两次?@WillyJoe——那是因为你要调用show\u multiples
两次。:-)