Python:(可能非常简单)基本函数的问题:如何使这组函数工作?

2024-09-25 02:37:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Python非常陌生,正在尝试将这组函数编写为“快乐测试”,输入您的名字,它会告诉您“您测试过快乐”,但如果您的名字是Anthony(我朋友的名字),它会说“you tested sad”。 每次我尝试运行它时(在Eclipse中,使用Pydev、语法版本3.8和解释器Python 3.8),它都会立即在控制台上方显示一条终止消息,控制台中没有显示任何内容。我查看了它,只是不确定如何正确地实现这一点

def HappyTest(n):
    n = input('What is your name?')
    def message1():
        return 'You tested sad'
    def message2():
        return 'You tested happy'
    the_bad_news = n+message1()
    the_good_news = n+message2()
    if str(n) == 'Anthony':
        return the_good_news
    else:
        return the_bad_news

Tags: the函数youreturndef名字anthonynews
2条回答

您刚刚定义了HappyTest,因此应该调用您的函数。n参数无效,请删除它: 试试这个:

def HappyTest():
    n = input('What is your name?')
    def message1():
        return 'You tested sad'
    def message2():
        return 'You tested happy'
    the_bad_news = n+message1()
    the_good_news = n+message2()
    if str(n) == 'Anthony':
        return the_good_news
    else:
        return the_bad_news
HappyTest()

您可以用更好的方式编写此代码:

def HappyTest():
n = input('What is your name?')
if str(n) == 'Anthony':
    print(str(n)+' You tested positive happy')
else:

    print(str(n)+' You tested sad')

相关问题 更多 >