简体   繁体   English

我很困惑为什么返回函数在程序的控制台上打印一个值。 它不只是应该返回一个值吗?

[英]I am confused why is the return function printing a value on the console in my program. Isn't it just supposed to return a value?

My program overloads the + operator to calculate the average GPA of 2 students. 我的程序使+运算符超载,以计算2个学生的平均GPA。 In my definition of the add function, I expect the return statement to return the average value. 在我对add函数的定义中,我期望return语句返回平均值。 I then want to print this 'returned value' using print(). 然后,我想使用print()打印此“返回值”。

However, the return statement also seems to print the average value along with the print statement. 但是,return语句似乎也将平均值与print语句一起打印。

The output was: 输出为:

8.0 
8.0

I don't understand why the return statement prints the value. 我不明白为什么return语句会显示该值。 Isn't is just supposed to return the value? 不就是应该返回值吗?

From googling this issue online, I found the only time when return should print a value is when an interactive console is being used (I am using pycharm). 通过在网上搜索这个问题,我发现只有在使用交互式控制台时(我正在使用pycharm),return才应该打印一个值。

prints twice 打印两次

prints once 打印一次

class student():

    def __init__(self, name, gpa):
        self.name = name
        self.gpa = gpa

    def __add__(x, y):
        return ((x.gpa + y.gpa)/2)

s1 = student("john", 9)
s2 = student("wick", 7)

avg = s1 + s2
print(s1 + s2)

It looks like in the first screenshot there is more source code when you scroll down. 看起来,在第一个屏幕快照中 ,向下滚动时有更多源代码。 Check if a print exists there... 检查那里是否有打印件...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么我的函数不返回值? - Why my function doesn't return a value? 在函数中打印返回值 - Printing return value in function 为什么我的退货单没有价值? - Why am I not getting a value to for my return statements? 为什么当我输入 0 时,带有 != '' 的“if”代码返回 true,这应该是一个 falsey 值? - Why does my 'if' code with != '' return true when I input 0, which is supposed to be a falsey value? 为什么我的 function 不返回最后一个值? - why my function don't return the last value? 在函数中打印返回值,Python - Printing return value in function, Python 我不明白为什么我不能让 python 中的 readline function 在这个程序中工作。 我究竟做错了什么? - I don't understand why i can't get readline function in python to work in this program. What am I doing wrong? 为什么我的属性值不能正确打印到 Django 中的 shell? - Why isn't my attribute value printing correctly to the shell in Django? 为什么我的 5 层 RSA 加密不能正常工作? 解密没有返回正确的值 - Why isn't my 5 layer RSA encryption working properly? the decryption doesn't return the right value Django Rest 框架 - 当 function 甚至不应该做任何事情时,为什么我会收到错误消息 - Django Rest Framework - Why am I getting an error when the function isn't even supposed to do anything
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM