1

I'm trying to figure out how to multiply numbers in python, but I'm having some trouble.

The program should run like this:

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()

The first problem is that when it runs, it creates more than the l variable specified, the format is also formatted differently, ie [1] [2] [3] instead of [1, 2, 3]

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.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Jacob
  • 371
  • 2
  • 18
  • `mylist = [c]` followed by `print(mylist)` will of course only print individual lists. You should make a list before the loop, then `append(c)` to it. Outside the loop, print it – OneCricketeer Apr 22 '18 at 08:33

1 Answers1

3

the format is also formatted differently, ie [1] [2] [3] instead of [1, 2, 3]

that is because your loop creates a list of one variable each time:

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

Instead, declare the list before the loop, and add elements to it inside the loop:

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.

It is kind of the same...

You should initialize a number product = 1 and multiply it by every number in the list:

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

BTW, no need to reinvent the wheel... you can get the product of a list with:

from functools import reduce  # needed on Python3
from operator import mul
list = [2, 4, 6, 8, 10]  
print(reduce(mul, list, 1))
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
CIsForCookies
  • 12,097
  • 11
  • 59
  • 124