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

匿名 (未验证) 提交于 2019-12-03 00:56:02

问题:

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 

Cheers, Carl

回答1:

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') 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!