2

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
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Myone
  • 1,103
  • 2
  • 11
  • 24

3 Answers3

8

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.

user2357112
  • 260,549
  • 28
  • 431
  • 505
3

Why should it print if you haven't told it to print? Try:

print(s.size())
print(s.isEmpty())
print(s.peek())
wjandrea
  • 28,235
  • 9
  • 60
  • 81
elParaguayo
  • 1,288
  • 1
  • 13
  • 24
  • 1
    I thought it would print it since that's what happened in my book. However, I did not understand that in the book they were in "interactive mode". I'm used to Matlab where (as you probably know) everything is printed unless you add ";". Now I understand the difference. Thanks! – Myone Jan 22 '14 at 10:57
2

I assume that you have the code in your input file, say a.py. The values of s.size() etc. are ignored in such a case. On the other hand, if you type in anything like that in an interactive Python session, the values will be printed automatically for you. The best way to try all those calls is: remove all operations on s from your input file, leaving only the Stack definition there. Then use

python -i a.py

This will load your file with the Stack definition, and then interactive mode (so called REPL) will be available, where you can try s = Stack(); s.push(5) etc.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Wojtek Surowka
  • 20,535
  • 4
  • 44
  • 51