【问题标题】:Can't convert 'nonetype' object to str implicitly - Python3无法将“nonetype”对象隐式转换为 str - Python3
【发布时间】:2016-04-15 09:38:41
【问题描述】:

我一直在尝试创建一个简单的程序来“登录”用户并欢迎他们。我对编程很陌生,因此对 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 接受输入,在没有欢迎消息的情况下吐出时间,并给出 nonetype 错误。我的问题是,为什么会这样?非常感谢所有回答我这个非常简单的问题的人☺

干杯,卡尔

【问题讨论】:

    标签: python nonetype


    【解决方案1】:

    函数返回一个值。如果您不指定一个,它们会隐式返回None。你的timeIs 函数打印了一些东西,但没有return 语句,所以它返回None。您可以保持原样并以不同的方式调用它:

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

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

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

    【讨论】:

    • 谢谢大家!我想我会使用第一个选项,保持整洁。
    猜你喜欢
    • 1970-01-01
    • 2014-08-03
    • 1970-01-01
    • 1970-01-01
    • 2019-04-11
    • 1970-01-01
    • 2017-07-21
    • 2013-05-17
    • 1970-01-01
    相关资源
    最近更新 更多