python - 无法将 'nonetype' 对象隐式转换为 str - Python3

标签 python nonetype

我一直在尝试创建一个简单的程序来“登录”用户并欢迎他们。我是编程新手,因此对 Python 抛出的错误感到非常困惑。我也知道有很多关于这个特定错误的问题得到了回答,但似乎没有一个与我遇到的问题完全吻合,而且因为我是新人,所以我无法调整答案。 ☺

这是我的代码...

    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,我已经列出了通过 datetime 模块获取时间的完整操作。然而,在 User1 语句中,我试图通过定义第二个语句 (timeIs) 并使用它来说明时间来缩短它。每次我“登录”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 接受输入,吐出没有欢迎消息的时间,并给出非类型错误信息。我的问题是,为什么会这样?非常感谢所有回答我非常简单的问题的人☺

干杯,卡尔

最佳答案

函数返回一个值。如果您不指定,它们将隐式返回 None。您的 timeIs 函数打印了一些内容,但没有 return 语句,因此它返回 None。您可以按原样保留它并以不同的方式调用它:

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

或者您可以用相同的方式调用它,但定义不同,返回创建的字符串而不是打印它:

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

关于python - 无法将 'nonetype' 对象隐式转换为 str - Python3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34715434/

相关文章:

python - 卡住神经网络的权重,使其输出在特定点取特定值( tensorflow )

python - 为什么我会收到 "instance has no attribute ' __getitem_ _' "错误?

c# - 将 C# 迁移到 Python - 随机类

打开pyxl+load_workbook+AttributeError : 'NoneType' object has no attribute 'date1904'

python - 对于每个原始类型,Python 将什么视为 True 或 False?

python - 回文无法通过所有测试用例

python - 迭代 json 数据由许多 None 类型对象组成

python - Python 列表初始化中的条件项

python - 在 Python 中启用和禁用调试消息

python - 我的移动网络对编码有何影响?