python 初学者 - 数字的倍数(有限制)

Beginner at python - Multiples of numbers (with limit)

我正在尝试找出如何在 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()

第一个问题是,当它运行s时,它创建了比指定的l变量更多的格式,格式也不同,即[1][2][3]而不是[1, 2, 3]

第二部分我真的不知道该怎么做。我认为它与我上面的类似,但它 returns 没什么。

the format is also formatted differently, ie [1] [2] [3] instead of [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

The second part I don't really have an idea on how to do it. I thought it would be similar to what I have like above, but it returns nothing.

有点像...

您应该初始化一个数字 product = 1 并将其乘以列表中的每个数字:

product = 1                            # no need for list, just a number
for r in productlist:                  
    product = product * r              # or product *= r     
    print(product )

顺便说一句,无需重新发明轮子...您可以获得列表的产品:

from functools import reduce  # needed on Python3
from operator import mul
list = [2, 4, 6, 8, 10]  
print(reduce(mul, list, 1))