Search code examples
pythonprintingreturn

Why doesn't Python print return values?


I'm taking a class in Algorithms and Data Structures (Python). In the book there is an example of a "stack" with methods that return certain values. In the book, these values are printed when the methods are called. However, when I run the program nothing is printed. I have to print the return value myself. Is this a difference between Python 2 and 3, or am I doing something wrong? Here is the code.

class Stack:
    def __init__(self):
        self.items = []

    def isEmpty(self):
        return self.items == []

    def push(self, item):
        self.items.append(item)

    def pop(self):
        return self.items.pop()

    def peek(self):
        return self.items[len(self.items)-1]

    def size(self):
        return len(self.items)

s = Stack()
s.push(5)
s.size()
s.isEmpty()
s.peek()

So, it should print this, but it doesn't:

1
False
5

Solution

  • At the interactive interpreter, Python will print the repr of expression values (except None) as a convenience. In a script, you have to print manually, as automatic printing would be highly awkward to work around in a script.