Why doesn't Python print return values?

后端 未结 4 1749
一个人的身影
一个人的身影 2021-01-22 00:49

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

相关标签:
4条回答
  • 2021-01-22 01:17

    You can either

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

    or replace your return statements with print.

    0 讨论(0)
  • 2021-01-22 01:21

    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.

    0 讨论(0)
  • 2021-01-22 01:32

    Why should it print if you haven't included a print statement? Try:

    print s.size()
    print s.isEmpty()
    print s.peek()
    
    0 讨论(0)
  • 2021-01-22 01:39

    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 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 Stack definition there. Then use

    python -i a.py
    

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

    0 讨论(0)
提交回复
热议问题