0

I'm trying to get all the odd numbers from 1 to number, but I'm having some troubles. How can I fix it? Output should be like: 1, 3, 5, 7, ...

number = input("Number: ")
if number.isdigit():
number = int(number)
if number > 0:
    oddNumbers = []
    for i in range(number):
        temp = i%2
        if temp != 0:
            oddNumbers.append([str(i)])
    conc = ', '.join(oddNumbers)
    print(conc)
else:
    print("Error")
else:
    print("Error")
1

4 Answers 4

1

Do this:

oddNumbers.append(str(i))

Not this:

oddNumbers.append([str(i)])

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

Comments

1

The error message is quite clear. Let's look at the full message:

Traceback (most recent call last):
  File "script.py", line 10, in <module>
    conc = ', '.join(oddNumbers)
TypeError: sequence item 0: expected str instance, list found

So the first item (0) of the "sequence" (in this case oddNumbers) was expected to be a str, but Python found a list in its place.

Let's look at what the value of oddNumbers will be after the for-loop by putting a print statement under the for-loop:

Number: 5
[['1'], ['3']]

So we see that the first value in oddNumbers is ['1']. So it is indeed a list and not a str.

Why is it a list?

In this line you add each number as a str inside a list to oddNumbers:

oddNumbers.append([str(i)])

If you instead just add the number as a str:

oddNumbers.append(str(i))

oddNumbers will be a list of str's by the end of the for-loop and the join will succeed:

Number: 5
['1', '3']
1, 3

Comments

1

Your problem comes from the join function which is a String object method and taking an iterable type argument, like list, tuple, dict, etc..

To work correctly, the argument should contain only string type. In your case, you have a list of a list. That's what the message error trying to tell.

So remove the bracket in the append method in order to add only string in your OddNumbers list.

Comments

0

Try this code instead :

number = int(input("Number: "))


def get_odd_number(number):
    result = []
    for i in range(number):
        if i % 2 != 0:
            result.append(str(i))
    return result


print(','.join(get_odd_number(number)))


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.