-1

So i shortened my code to make it easier to read

g = True

def welcome_message():
  print("welcome")

while g == True:
  g = False
  print(welcome_message())
  c = input("Do you understand ('yes' or 'no')")
  if c == "yes":
   print("okay")
  elif c == "no":
   g = True 
  else:
   print("That is not a valid input. Please try again.")
   g = True

However, when I run this code, I expect the code to print "welcome" and ask the person running the code if they understand. However, this is the result:

welcome
None
Do you understand ('yes' or 'no') 

Why does my code show a "None" at that location?

Rubikzzz
  • 9
  • 2

3 Answers3

0

It's because you're printing the output of welcome_message(), and since the function never returns anything, it defaults to none.

To fix this, just don't print the function, and instead just call it with welcome_message().

duckboycool
  • 2,425
  • 2
  • 8
  • 23
0

The line print(welcome_message()) executes welcome_message() function and prints it's returned value. Since this function has no returned value, None is printed.

To avoid printing None, you can do:

def welcome_message():
  print("welcome")

while g == True:
  g = False
  welcome_message()
  c = input("Do you understand ('yes' or 'no')")

or

def welcome_message():
  return "welcome"

while g == True:
  g = False
  print(welcome_message())
  c = input("Do you understand ('yes' or 'no')")
Gabio
  • 9,126
  • 3
  • 12
  • 32
0

First to correct the code you need to change the welcome function as below:

def welcome_message():
    return("welcome")

or to just call the welcome_message() without print

Why it gives you None is because of the type of object a print returns. Which is <class 'NoneType'> and your second print prints it like print(None)

Basically you we doing :

print(print("Welcome"))

The inner print shows the "Welcome" message and the outer print outputs None because of the result of inner print

Ehsan
  • 711
  • 2
  • 7
  • 21