Reputation:
I'm looking for help on the question:
So far my code has gotten me far enough to return the right answer but also the restultant multiplication along the way, i.e.: (1, 2, 2, 8, 8, 48). Can anyone reshuffle or redo the code so it just outputs the answer only, thanks in advance!
counter=1
product=1
userinput=int (input ("What number: "))
for counter in range (1, userinput):
if counter%2==0:
product=int (counter*product)
counter=counter+1
else:
counter=counter+1
print (product)
Upvotes: 5
Views: 1517
Reputation: 1625
It's simple. Just read the comments i have added to your code and the modifications.
product=1
userinput=int (input ("What number: "))
if userinput = 1: # add these
return 0 # lines
for counter in range (1, userinput + 1): # add 1 here
if counter%2==0:
product=counter*product # here you didn't need int() at all
# you also don't need to increment counter because it is getting incremented in the for loop
print (product) # decrement this line to the same level of "for counter ..."
Edit: if the user gives 0 or negative numbers you can consider this code, which is cleaner overall i guess
def main(n):
product = 1
if n == 0 or n == 1:
return 0
range_step = 1
if n < 0:
range_step = -1
for counter in range(1, n+range_step, range_step):
if counter == 0:
continue
elif counter % 2 == 0:
product = counter*product
return product
if __name__ == '__main__':
userinput = int(input("What number: "))
product = main(userinput)
print(product)
Upvotes: 0
Reputation: 3043
You need to do two modifications to your code.
1.> Change the indentation of the last line print (product)
.
2.> In the for
loop, change userinput
to userinput+1
(to get proper answer for inputs which are even numbers.)
Check the following code. =)
counter=1
product=1
userinput=int (input ("What number: "))
for counter in range (1, userinput+1): #userinput changed to userinput+1
if counter%2==0:
product=int (counter*product)
counter=counter+1
else:
counter=counter+1
print (product) #Indentation of last line changed.
Upvotes: 0
Reputation: 18763
that's because print
is executed on every iteration, you need to execute it only after the loop ends, which means print
must have the same indent level as the loop,
counter=1
product=1
userinput=int (input ("What number: "))
for counter in range (1, userinput):
if counter%2==0:
product= int(counter*product)
print(product)
Upvotes: 1
Reputation: 1434
You should fix the indent level of print(product)
if you wish to print it after finishing for loop as below. And, another important thing is that you do not need to work on counter
variable as it is incremented with for counter in range(1,counter)
:
product=1
userinput=int (input ("What number: "))
for counter in range (1, userinput):
if counter%2==0:
product=int (counter*product);
print (product)
Upvotes: 0