0

When I'm doing this:

def pencil():
   print("pencil")

print("A", pencil())

Output showing:

pencil
A None

I tried some things but nothing worked.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
T2D
  • 13
  • 4
  • It's because the function "pencil" is returning None. Instead of printing "pencil" inside your function, return "pencil". – gtj520 Dec 02 '22 at 02:25
  • It would help to show what you want to happen. Best guess is you want a single line `A pencil`. Correct? – tdelaney Dec 02 '22 at 02:34
  • Does this answer your question? [What is the purpose of the return statement? How is it different from printing?](https://stackoverflow.com/questions/7129285/what-is-the-purpose-of-the-return-statement-how-is-it-different-from-printing) – mkrieger1 Dec 02 '22 at 02:35

3 Answers3

1
def pencil():
    return "pencil"


print("A", pencil()) # A pencil

Or

def pencil():
    print("pencil")


print("A") # A
pencil()   # pencil
Leo
  • 369
  • 5
0

When you do

print("A", pencil())

you are basically asking python to print "A" and the return value of the function named pencil.

Because you do not specify a return statement in your function definition, python returns None, hence the unwanted result.

As stated by other people, you just need to return "pencil" from the function so that the desired outcome can be achieved

subparry
  • 333
  • 2
  • 9
0

The default return value of a function is None Your function doesn't have a return statement, so it will return None Furthermore, print returns None to as it prints its input to the sys.stdout stream. So returning print("pencil") would also give you None

In order for you to get a value from a function you need to use the return statement and return a value. In your case "pencil":

def pencil():
    return "pencil"

print("A", pencil())
Wolric
  • 701
  • 1
  • 2
  • 18