DJ Joel
DJ Joel

Reputation: 23

Multiply items in range in Python

I am brand new to Python, and I'm currently taking a free online course.

I'm stuck trying to figure out how to code this simple optional problem found in my course:

[ ] using range(x) multiply the numbers 1 through 7

1x2x3x4x5x6x7 = 5040

I have made a variable for the range, 7, and a variable for the product used in the loop:

x = 7
product = 0

for item in range(x):

This is where I'm stuck. I try things in the loop like:

product = item * item

which doesn't even make any sense. I'm having a total mental block right now. I realize this should be an easy thing to do, but can't for whatever reason. I've tried making other variables like "number" and "previous_number" to make things easier for me, but I just get confused.

I need to use a for loop in this solution. I'm just not understanding the logic right now. A solution and explanation would be great! Please help!

Upvotes: 0

Views: 18932

Answers (7)

Inchbrayock
Inchbrayock

Reputation: 1

Try this:

user_number = int(input("Please enter a number: "))

number = 1

for i in range(1,user_number + 1):
    number = number * i

print(number)

Upvotes: 0

3asniper
3asniper

Reputation: 1

from functools import reduce

some_list = range(1, 8)

print(reduce(lambda x, y: x * y, some_list))

Upvotes: 0

Scott Tomassetti
Scott Tomassetti

Reputation: 11

multiplication = 1
for number in range(1,8):
    multiplication *= number
digits = list(range(1,8))
print("Multiply these numbers in sequence: ", digits, "=", multiplication)

Upvotes: 0

Abhishek Sharma
Abhishek Sharma

Reputation: 1

digit = range(1,8)    
print("digit", list(digit))  
product = 1   
for item in digit:  
    product = product * item  
    print("product is",product)  

Upvotes: 0

AChampion
AChampion

Reputation: 30258

You need to initialise product = 1 (as 1 is the multiplicative identity) and inside your loop you simply need:

product *= item

which is short hand for:

product = product * item

In python there is also a reduce function that handles these types of questions:

In []:
import operator as op
import functools as ft

x = 7
ft.reduce(op.mul, range(1,x+1))

Out:
5040

Upvotes: 2

inspectorG4dget
inspectorG4dget

Reputation: 113915

Check this out:

answer = 1

for i in range(1,8):
    print("Right now, answer is", answer)
    print("Right now, i      is", i)
    print("I am going to multiply answer ({}) with i ({}) and store the result in answer".format(answer, i))
    answer = answer * i
    print("Now, answer is", answer)

print("Finally, answer is", answer)

Upvotes: 2

LeopoldVonBuschLight
LeopoldVonBuschLight

Reputation: 911

Try something like this:

x = 7
product = 1

for item in range(1, x + 1):
    product = item * product

print(product)

Note that product starts at one and the range function starts at one as well. Otherwise item will continue to be multiplied by zero.

Upvotes: 1

Related Questions