n= int(input())
a= list(range(1,"x",n 1)
print(a)
b=1:
for b in a
if num % 2 != 0:
b= b*num
print(b)
This is for my into to python class and this is the question for context.
"Taking an integer value n from the user with input(). Your program will calculate the product of all odd numbers from 1 through the given n. For example: the user gave n=20. You python code will calculate the following value: 1 x 3 x 5 x 7 x 9 x 11 x 13 x 15 x 17 x 19 Your program will print out 654729075.0 back to the user. Please calculate the value for n=23 using your program?"
When I run my code, I keep getting an error saying perhaps I forgot a comma. Where would this be an issue within the code? The r in range keeps getting highlighted.
CodePudding user response:
Noticed a few issues here. First, you don’t need list()
in your definition of a. You also don’t need a var named a at all.
Also, the syntax for range
is range(start, stop, step)
. You want to start at 1, stop at n 1 (because range
is exclusive), and move forward 2 each time. Therefore, it’s range(1, n 1, 2)
. The code will look like this:
n= int(input())
b=1
for num in range(1, n 1, 2):
b *= num
print(b)
CodePudding user response:
try this: You are adding unnecessary "x" in code range should (start, end, [Step])
n= int(input())
a= list( range(1,n 1) )
print(a)
ans=1
for i in range(len(a)):
if a[i] % 2 != 0:
ans*=a[i]
else:
continue
print(float(ans)
Read: Try to go through built in functions https://docs.python.org/3/library/functions.html
Range- https://docs.python.org/3/library/functions.html#func-range
List - https://docs.python.org/3/library/functions.html#func-list
CodePudding user response:
The code has several flaws. The expert comments are already indicating that. here is one possible version of executable code that can do what you want.
n= int(input())
a=list(range(1,n 1,2))
print(a)
b = 1
for num in a:
b *= num
print(b)