在python中打印周围的括号

编程入门 行业动态 更新时间:2024-10-26 08:32:55
本文介绍了在python中打印周围的括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在python中有这行代码

I have this line of code in python

print 'hello world'

反对

print ('hello world')

谁能告诉我两者的区别?

can someone tell me the difference between the two?

我在一个简单的代码中使用了它

I used it in a a simple code

var = 3 if var > 2: print 'hello'

它无法严格检查 var 的所有值.但是如果我将代码定义为

it fails for checking strictly for all values for var. But if I define the code as

var = 3 if var > 2: print ('hello')

它有效!

推荐答案

对于 Python 2,它没有区别.在那里,print 是一个语句,'hello' 和 ('hello') 是它的参数.后者被简化为 'hello',因此它是相同的.

For Python 2, it makes no difference. There, print is a statement and 'hello' and ('hello') are its argument. The latter gets simplified to just 'hello' and as such it’s identical.

在 Python 3 中,删除了打印语句以支持打印功能.使用大括号调用函数,因此实际上需要它们.在这种情况下, print 'hello' 是一个语法错误,而 print('hello') 使用 'hello' 作为调用函数它的第一个参数.

In Python 3, the print statement was removed in favor of a print function. Functions are invoked using braces, so they are actually needed. In that case, the print 'hello' is a syntax error, while print('hello') invokes the function with 'hello' as its first argument.

您可以通过显式导入将打印函数向后移植到 Python 2.为此,将以下内容添加为模块的第一次导入:

You can backport the print function to Python 2, by importing it explicitly. To do that add the following as the first import of your module:

from __future__ import print_function

然后您将在 Python 2 中获得与 Python 3 相同的行为,同样需要括号.

Then you will get the same behaviour from Python 3 in Python 2, and again the parentheses are required.

更多推荐

在python中打印周围的括号

本文发布于:2023-07-31 15:45:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1260054.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:括号   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!