neolee / pilot

进入编程世界的第一课
584 stars 840 forks source link

关于 return 和 print 的区别。 #1496

Closed xu-kai-xu closed 2 years ago

xu-kai-xu commented 2 years ago

第一阶段课程大作业 1,机器人。 看了 bilibili 上大作业的视频,对照着敲代码,然后发现 Bot 类方法 _say() 中用的是 print,我修改成了 return,然后就无法打印问题,也无法打印回复。代码如下:

import random
import re
import time

class Bot:

    wait = 1

    def __init__(self):
        self.q = ''
        #self.a = ''

    def _think(self, s):
        return s

    def _say(self, s):
        #time.sleep(wait)  # NameError: name 'wait' is not defined
        time.sleep(Bot.wait)  
        #print(s)  # print 可以得到问题和回复。
        return s  # return 得不到问题和回复。

    def run(self):
        self._say(self.q)
        self.a = input()
        self._say(self._think(self.a))

class HelloBot(Bot):

    def __init__(self):
        self.q = "Hi, what's your name?"

    def _think(self, s):
        return(f"Hello, {s}!")

class GreetingBot(Bot):

    def __init__(self):
        self.q = "How are you today?\n你今天怎么样呀?"

    def _think(self, s):
        feeling = s.lower()
        test = re.search('goo+d', feeling) or \
               re.search('nice', feeling) or \
               re.search('excellent', feeling)
        if test:
            return("I am feeling good, too!")
        else:
            return("Sorry to hear that.")

class FavoriteColorBot(Bot):

    def __init__(self):
        self.q = "What is your favorite color?"

    def _think(self, s):
        colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'purple']
        return (f"You like {s}? Tha's great color. My favorite color is {random.choice(colors)}")

h = HelloBot()
g = GreetingBot()
f = FavoriteColorBot()
h.run()
g.run()
f.run()

然后又试了试下面的代码:

q = 'How are you today?'
def say(s):
    return s

say(q)

这样用是没问题的。所以,就搞不清楚为什么在类方法 _say() 中用 return 函数会出问题。谢谢老师 @neolee

neolee commented 2 years ago

先搞清楚 returnprint() 分别是什么、做什么的……

xu-kai-xu commented 2 years ago

我的理解,return 是返回函数的执行结果。print 是将特定内容输出到控制台。区别在于函数返回值不会直接被输出到控制台。

然后,想了想发现 run 中只是调用了 _say' ,所以相当于只是返回_say` 的结果,并没有打印的命令。

之后分别在 jupyter notebook 中 和 cmd 中执行了代码:

q = 'How are you today?'
def say(s):
    return s

say(q)

发现命令行执行时(另存为 *.py 文件)不会输出结果,而 jupyter notebook 中执行时会有单引号括起来的结果。 所以,之前感到困惑的原因在于,同样的代码,在命令行中执行没有输出结果,在 jupyter notebook 中执行却看到了输出结果。虽然还不知道具体原因,但进一步搞清楚了 returnprint 的区别。谢谢老师

neolee commented 2 years ago

return 是语言本身的特性,定义函数的返回值,如果后面没有值,实质上等于该函数返回 Noneprint() 是个内置函数,没有返回值,但会在系统控制台输出内容。完全不同的两个东西。所以你要做什么?该选择哪个?

xu-kai-xu commented 2 years ago

程序中,机器人说的话需要打印到控制台中让我们看见才行,所以必须要有print 才可以。懂了。