Indexing does not work in my ptyhon program. Can you help me?

Question:

I don’t understand where the "none" comes from in the output of my Python program.
Can anyone help me?

Program

def printColumn(x):
    if type(x) is not list:
        x = list(range(0,5))
    for i in range(len(x)):
        print(x[i])

x = [8,24,48,2,16]  
print(printColumn(x))

Output

8
24
48
2
16
None

Thank you in advance

I just don’t understand why it doesn’t work

Asked By: hippopankutz

||

Answers:

The function prints the values 8 thru 16.

But your main-level code has print(printColumn(x)), which means that the return value of the function is also printed. And since the function has no return statement, it returns None by default.

If you want to just call the function, without printing its result, just use printColumn(x) without the outer print() call.

Answered By: John Gordon

you should just call the function without print()
like that: printColumn(x)
NOT print(printColumn(x))

Answered By: Harez

The way you deal with this depends on where you want the printing to occur.

If you want to print the return value from printColumn() then you could do this:

def printColumn(x=None):
    return x if isinstance(x, list) else range(5)

x = [8,24,48,2,16]  

print(*printColumn(x), sep='n')
print()
print(*printColumn(), sep='n')

Output:

8
24
48
2
16

0
1
2
3
4
Answered By: Cobra
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.