无法将 'nonetype' 对象隐式转换为 str - Python3
Can't convert 'nonetype' object to str implicitly - Python3
我一直在尝试创建一个简单的程序,它将 'log' 用户加入并欢迎他们。我对编程很陌生,因此对 Python 抛出的错误感到非常困惑。我也知道有很多关于这个特定错误的问题得到了回答,但是其中 none 似乎与我遇到的问题完全吻合,而且因为我是新人,所以我无法调整答案。 ☺
这是我的代码...
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())
如您所见,对于User2和User3,我已经列出了通过日期时间模块获取时间的完整操作。然而,在 User1 语句中,我试图通过定义第二个语句 (timeIs) 并使用它来说明时间来缩短它。每次我 'log in' user1,python 说这个-
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
如您所见,python 接受输入,吐出没有欢迎消息的时间,并给出 nonetype 错误信息。我的问题是,为什么会这样?非常感谢所有回答我非常简单的问题的人☺
干杯,卡尔
函数return一个值。如果您不指定一个,它们将隐式 return None
。您的 timeIs
函数打印了一些内容,但没有 return
语句,因此它 returns None
。您可以保留它 as-is 并以不同的方式调用它:
if Name == "User1" :
print("Welcome User1! ", end='')
timeIs()
或者您可以用相同的方式调用它,但定义不同,return使用创建的字符串而不是打印它:
def timeIs() :
return "The time is " + datetime.strftime(datetime.now(), '%H:%M')
我一直在尝试创建一个简单的程序,它将 'log' 用户加入并欢迎他们。我对编程很陌生,因此对 Python 抛出的错误感到非常困惑。我也知道有很多关于这个特定错误的问题得到了回答,但是其中 none 似乎与我遇到的问题完全吻合,而且因为我是新人,所以我无法调整答案。 ☺
这是我的代码...
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())
如您所见,对于User2和User3,我已经列出了通过日期时间模块获取时间的完整操作。然而,在 User1 语句中,我试图通过定义第二个语句 (timeIs) 并使用它来说明时间来缩短它。每次我 'log in' user1,python 说这个-
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
如您所见,python 接受输入,吐出没有欢迎消息的时间,并给出 nonetype 错误信息。我的问题是,为什么会这样?非常感谢所有回答我非常简单的问题的人☺
干杯,卡尔
函数return一个值。如果您不指定一个,它们将隐式 return None
。您的 timeIs
函数打印了一些内容,但没有 return
语句,因此它 returns None
。您可以保留它 as-is 并以不同的方式调用它:
if Name == "User1" :
print("Welcome User1! ", end='')
timeIs()
或者您可以用相同的方式调用它,但定义不同,return使用创建的字符串而不是打印它:
def timeIs() :
return "The time is " + datetime.strftime(datetime.now(), '%H:%M')