为什么 Python 不打印返回值? [英] Why doesn't Python print return values?

查看:62
本文介绍了为什么 Python 不打印返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习算法和数据结构 (Python) 课程.书中有一个堆栈"示例,其中包含返回特定值的方法.在书中,这些值是在调用方法时打印的.但是,当我运行程序时,没有打印任何内容.我必须自己打印返回值.这是 Python 2 和 3 之间的区别,还是我做错了什么?这是代码.

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()

因此,这应该打印1"、False"和5".但它没有.

So, this should print "1", "False" and "5". But it doesn't.

推荐答案

在交互式解释器中,Python 会将表达式值的 repr(除了 None)打印为方便.在脚本中,您必须手动打印,因为在脚本中自动打印非常麻烦.

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.

这篇关于为什么 Python 不打印返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆