None Output in for loop

Question:

I am trying to loop a string using for loop, but instead, the "None" output popup.

how do I get rid of "none" output? thank you

def name(a):
    for b in a:
        print (b)

print (name("hello123"))

output:

h
e
l
l
o
1
2
3
None
Asked By: Kevin

||

Answers:

Your name function doesn’t return anything explicitly, so its return value is None, which you then print.

In this case, there’s no point in printing the return value of name at all.

def name(a):
    for b in a:
        print(b)

name("hello123")

As an added note, this does not require a loop at all.

Instead we can expand a out to print, supplying newline as a separator.

>>> def name(a):
...     print(*a, sep='n')
... 
>>> name("hello123")
h
e
l
l
o
1
2
3
>>>

This is equivalent to writing:

print('h', 'e', 'l', 'l', '0', '1', '2', '3', sep='n')
Answered By: Chris

Since the print command is used for each character within the name() function, there is no need to call it again with the final print(name()) call.

In your code, the name() function prints each letter, and then the final print(name()) function tries to print something as well. But since name() does not return any values, it prints "None"

This modified code should work perfecetly:

def name(a):
    for b in a:
        print (b)

name("hello123")

Incidentally, in this alternate version:

def name(a):
    for b in a:
        print (b)
    return "Done"

print(name("hello123"))

It will print another line, "Done", because the name() function returns a value when it finished, which is passed to the final print() function.

Answered By: Soup

Simple answer:

def name(a):
    for b in a:
        return(b)
print(name("hello123"))

Return function won’t generate any "None" past the iteration.

Answered By: Sanchit Goyal
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.