Reputation: 23
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:
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
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
Reputation: 1
from functools import reduce
some_list = range(1, 8)
print(reduce(lambda x, y: x * y, some_list))
Upvotes: 0
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
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
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
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
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