0

The given python code is supposed to accept a number and make a list containing all odd numbers between 0 and that number

n = int(input('Enter number : '))
i = 0 
series = []
while (i <= n):
    if (i % 2 != 0):
        series += [i]
print('The list of odd numbers :\n')
for num in series:
    print(num)
1
  • 2
    you forgot to increment the i variable after each iteration, add i+=1 after the if statement Commented Sep 30, 2018 at 5:34

2 Answers 2

2

So, when dealing with lists or arrays, it's very important to understand the difference between referring to an element of the array and the array itself.

In your current code, series refers to the list. When you attempt to perform series + [i], you are trying to add [i] to the reference to the list. Now, the [] notation is used to access elements in a list, but not place them. Additionally, the notation would be series[i] to access the ith element, but this still wouldn't add your new element.

One of the most critical parts of learning to code is learning exactly what to google. In this case, the terminology you want is "append", which is actually a built in method for lists which can be used as follows:

series.append(i)

Good luck with your learning!

Sign up to request clarification or add additional context in comments.

1 Comment

Actually what he's doing is putting the value into a list and then concatenating the two lists using the += operator which is perfectly valid. The only issue with his code was that he forgot to increment the counter variable.
1

Do a list-comprehension taking values out of range based on condition:

n = int(input('Enter number : '))

print([x for x in range(n) if x % 2])

Sample run:

Enter number : 10
[1, 3, 5, 7, 9]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.