17/18 Why use print?


#1

https://www.codecademy.com/courses/python-intermediate-en-WL8e4/3/3?curriculum_id=4f89dab3d788890003000096

I have the following code here:


class Triangle(object):
    def __init__(self, angle1, angle2, angle3):
        self.angle1 = angle1
        self.angle2 = angle2
        self.angle3 = angle3
    
    number_of_sides = 3
    
    def check_angles(self):
        if self.angle1 + self.angle2 + self.angle3 == 180:
            return True
        else:
            return False
            

my_triangle = Triangle(30, 60, 90)
print my_triangle.number_of_sides
print my_triangle.check_angles()

I know this code appears as the correct answer, but I was just wondering... Why doesn't the code work if I just call this instead?

print my_triangle.number_of_sides
my_triangle.check_angles()

I saw "return" in the check angles method, so I figured there would be no need to actually use the print function. However, when I tried this it only displayed the first line. Could someone explain why this wouldn't work and when to use "print" and when to use "return"?
Sorry if I couldn't extrapolate my question well enough. Thanks!


#2

Hi, @kalaborative,

If you run Python in interactive mode, for example in IDLE, as follows, the values of expressions that you enter are displayed in the console ...

Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 26 2016, 10:47:25) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "copyright", "credits" or "license()" for more information.
>>> x = 4
>>> print(x)
4
>>> x
4
>>> y = 5
>>> y
5
>>> x * y
20
>>> def rect_perimeter(a, b):
	return 2 * a + 2 * b

>>> rect_perimeter(x, y)
18
>>>

However, when you run a Python program as a script, as is the case in Codecademy, you need to explicitly ask for output, such as what is done with a print or a write statement, in order to display or write output. If you use an expression as an entire statement in script mode, rather than explicitly outputting the result, the expression does get evaluated, but its value does not get displayed.

In IDLE, by the way, you can choose between working in interactive or script mode.

Use return when the purpose of the function or method your are composing is to compute a value that is to be used in the program, for example in an assignment statement, or as part of an expression. Use print if a purpose of the function or method is to display output.


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.