Can't convert 'nonetype' object to str implicitly - Python3

Carl picture Carl · Jan 11, 2016 · Viewed 26.6k times · Source

I've been trying to create a simple program which will 'log' a user in and welcome them. I'm very new to programming and therefore am absolutely baffled by the errors Python is throwing up. I am also aware that there have been many questions answered on this particular error, however none of them seem to coincide exactly with the problem I am getting, and because I'm new I can't adapt the answers. ☺

Here is my code...

    from datetime import datetime

    def userLogin() :
        Name = input("Please type         your Username ")
        if Name == "User1" :
            print ("Welcome User1!         " + timeIs())
        if Name == "User2" :
            print ("Welcome User2! The time is " +         datetime.strftime(datetime.now(), '%H:%M'))
                if Name == "User3" :
                    print ("Welcome User3! The time is " + datetime.strftime(datetime.now(), '%H:%M'))

    def timeIs() :
        print ("The time is " +   datetime.strftime(datetime.now(), '%H:%M'))

    print (userLogin())

As you can see, for User2 and User3 I have set out the full operation for getting the time via the datetime module. In the User1 statement however I have tried to shorten it down by defining a second statement (timeIs) and using that to state the time. Every time I 'log in' user1, python says this-

    Please type your Username> User1
    The time is 19:09
    Traceback (most recent call last):
      File "/home/pi/Documents/User.py", line 15, in <module>
print (userLogin())
   File "/home/pi/Documents/User.py", line 6, in userLogin
print ("Welcome User1! " + timeIs())
    TypeError: Can't convert 'NoneType' object to str implicity

As you can see, python takes the input, spits out the time without the welcome message, and gives the nonetype error thing. My question is, why is this happening? Thank you very much to everyone who answers my very simple question ☺

Cheers, Carl

Answer

TigerhawkT3 picture TigerhawkT3 · Jan 11, 2016

Functions return a value. If you don't specify one, they implicitly return None. Your timeIs function prints something, but doesn't have a return statement, so it returns None. You can leave it as-is and call it differently:

if Name == "User1" :
    print("Welcome User1!         ", end='')
    timeIs()

Or you can call it in the same way but define it differently, returning the created string instead of printing it:

def timeIs() :
    return "The time is " +   datetime.strftime(datetime.now(), '%H:%M')