我试图弄清楚如何在python中增加数字,但我遇到了一些麻烦。
程序应该像这样运行:
Multiple of: 2 (for example)
Enter an upper limit: 10
[2, 4, 6, 8, 10]
The product of the list [2, 4, 6, 8, 10] is: 3840 (this has to be in a separate function and work for any integer)
n = int(input("Multiples of: "))
l = int(input("Upper Limit: "))
def calculation():
for x in range(0, l):
c = x * n
mylist = [c]
print(mylist, end=' ')
calculation()
def listfunction():
productlist = []
for r in productlist:
productlist = [n * l]
print(productlist)
listfunction()
第一个问题是,当它运行时,它创建的不仅仅是指定的l变量,格式的格式也不同,即[1] [2] [3]而不是[1,2,3]
第二部分我并不知道如何做到这一点。我认为它与我上面的相似,但它什么也没有返回。
答案 0 :(得分:3)
格式的格式也不同,即[1] [2] [3]而不是[1,2,3]
这是因为你的循环每次创建一个变量的列表:
for x in range(0, l): # the '0' is redundant. You can write just "for x in range(l):"
c = x * n # c is calculated
mylist = [c] # mylist is now [c]
print(mylist, end=' ') # print mylist
相反,在循环之前声明列表 ,并在其中添加元素 循环
mylist = []
for x in range(l):
c = x * n # c is calculated
mylist.append(c) # mylist is now mylist + [c]
print(mylist, end=' ') # print mylist
第二部分我真的不知道如何做到这一点。我认为它与我上面的相似,但它什么也没有返回。
它有点相同......
您应该初始化一个数字product = 1
并将其乘以列表中的每个数字:
product = 1 # no need for list, just a number
for r in productlist:
product = product * r # or product *= r
print(product )
BTW,无需重新发明轮子......你可以通过以下方式获得列表的产品:
from functools import reduce # needed on Python3
from operator import mul
list = [2, 4, 6, 8, 10]
print(reduce(mul, list, 1))