Help

Grant Edwards grant.b.edwards at gmail.com
Tue Nov 3 21:29:56 EST 2020


On 2020-11-04, Quentin Bock <qberz2005 at gmail.com> wrote:
> So, I'm newer to Python and I'm messing around with math functions and
> multiplication, etc. here is my line of code:
>
> def multiply(numbers):
>       total = 1
>              for x in numbers:
>              total *= x
>              return total
> print(multiply((8, 2, 3, -1, 7)))
>
> When I run this, my answer is 8 but it should be 336 can some help ._.

1. If you're using tabs to indent; don't. It results in hard-to
   diagnose problems. Use spaces to indent.

2. Cut/past the exact code when asking questions. The code you
   posted does not print 8. It doesn't run at all:

    $ cat bar.py
    def multiply(numbers):
      total = 1
             for x in numbers:
             total *= x
             return total
    print(multiply((8, 2, 3, -1, 7)))
    
    $ python bar.py
    
      File "bar.py", line 3
        for x in numbers:
        ^
    IndentationError: unexpected indent

3. The answer you want is not 336, it's -336:

    $ cat foo.py
    def multiply(numbers):
        total = 1
        for x in numbers:
            total *= x
        return total
    
    print(multiply((8,2,3,-1,7)))
    
    $ python foo.py
    -336
    
4. I suspect that your actual code looks like this:

    $ cat foo.py
    def multiply(numbers):
        total = 1
        for x in numbers:
            total *= x
            return total
    
    print(multiply((8,2,3,-1,7)))
    
    $ python foo.py
    8

See the difference between #3 and #4?




More information about the Python-list mailing list