简体   繁体   English

我不能在Python中使用花括号吗?

[英]Is it true that I can't use curly braces in Python?

I was reading that Python does all it's "code blocks" by indentation, rather than with curly braces. 我读到Python通过缩进而不是花括号来完成它所有的“代码块”。 Is that right? 是对的吗? So functions, if's and stuff like that all appear without surrounding their block with curly braces? 所以函数,如果这样的东西都没有用花括号包围它们的块?

if foo: #{
    print "it's true"
#}
else: #{
    print "it's false!"
#}

(Obviously, this is a joke.) (显然,这是一个笑话。)

You can try to add support for braces using a future import statement, but it's not yet supported, so you'll get a syntax error: 您可以尝试使用将来的import语句添加对大括号的支持,但它尚不支持,因此您将收到语法错误:

>>> from __future__ import braces
  File "<stdin>", line 1
SyntaxError: not a chance

Correct for code blocks. 纠正代码块。 However, you do define dictionaries in Python using curly braces: 但是,您使用花括号在Python中定义词典:

a_dict = {
    'key': 'value',
}

Ahhhhhh. AHHHHHH。

Yes. 是。 Curly braces are not used. 不使用卷曲括号。 Instead, you use the : symbol to introduce new blocks, like so: 相反,您使用:符号来引入新块,如下所示:

if True:
    do_something()
    something_else()
else:
    something()

Yup :) 对 :)

And there's (usually) a difference between 4 spaces and a tab, so make sure you standardize the usage .. 而且(通常)4个空格和一个标签之间存在差异,因此请确保标准化使用情况。

Python with Braces is a variant of python that lets you do exactly that. Python with Braces是python的一个变种,可以让你做到这一点。 It's a project that I've been working on lately together with my friend. 这是我最近和朋友一起工作的一个项目。

Yes. 是。

if True:
    #dosomething
else:
    #dosomething else

#continue on with whatever you were doing

Basically, wherever you would've had an opening curly brace, use a colon instead. 基本上,无论你在哪里都有一个开口花括号,请使用冒号代替。 Unindent to close the region. Unindent关闭该地区。 It doesn't take long for it to feel completely natural. 它感觉完全自然不需要很长时间。

Python does not use curly braces for code blocks: Python不对代码块使用花括号:

>>> while True {
  File "<stdin>", line 1
    while True {
               ^
SyntaxError: invalid syntax

>>> from __future__ import braces
  File "<stdin>", line 1
SyntaxError: not a chance

(Notice the "not a chance" message – this is an Easter egg reflecting this design decision.) (请注意“非机会”消息 - 这是反映此设计决定的复活节彩蛋。)

As a language designed to be easy to use and read, Python uses colons and indentation to designate code blocks. 作为一种易于使用和阅读的语言,Python使用冒号和缩进来指定代码块。 Defining code blocks by indentation is unusual and can come as a surprise to programmers who are used to languages like C++ and C# because these (and many other languages) don't care about extra whitespace or indentation. 通过缩进定义代码块是不寻常的,对于习惯于C ++和C#等语言的程序员来说,这可能会让他们感到惊讶,因为这些(和许多其他语言)不关心额外的空格或缩进。 This rule is intended to increase readability of Python code, at the cost of some of the programmer's freedom to use varying amounts of whitespace. 此规则旨在提高Python代码的可读性,代价是程序员可以自由使用不同数量的空白。

An increase in the indentation level indicates the start of a code block, while a decrease indicates the end of the code block. 缩进级别的增加表示代码块的开始,而减少表示代码块的结束。 By convention, each indentation is four spaces wide. 按照惯例,每个压痕宽度为四个空间。

Here's a simple example which sums all the integers from 0 to 9. Note that ranges in Python include the first value, up to but not including the last value: 这是一个简单的例子,它将0到9之间的所有整数相加。请注意,Python中的范围包括第一个值,最多但不包括最后一个值:

j = 0
for i in range(0, 10):
    j += i
print(j)

As others have mentioned, you are correct, no curly braces in Python. 正如其他人所提到的,你是正确的,在Python中没有花括号。 Also, you do not have no end or endif or endfor or anything like that (as in pascal or ruby). 此外,你没有没有结尾endifendfor或类似的东西(如pascal或ruby)。 All code blocks are indentation based. 所有代码块都是基于缩进的。

>>> from __future__ import braces
  File "<stdin>", line 1
SyntaxError: not a chance

Well that explains a lot. 那很好地解释了。
Note however, that Python does natively support curly brace-d code blocks! 但请注意,Python本身支持大括号代码块! Take a look at below: 看看下面:

if x: #{
    x += 1
#}

For Ada or Pascal programmers, I take delight in revealing to you: 对于Ada或Pascal程序员,我很高兴向您透露:

if x: #BEGIN
    ...
#END

Taken from the docs : 取自文档

Python's parser is also sophisticated enough to recognize mixed notations, and it will even catch missing beginning or end delimiters and correct the program for the user. Python的解析器也非常复杂,可以识别混合符号,甚至可以捕获缺少的开始或结束分隔符并为用户更正程序。 This allows the following to be recognized as legal Python: 这允许以下内容被识别为合法的Python:

if x: #BEGIN
     x = x + 1
#}

And this, for Bash users: 对于Bash用户来说:

if x:
    x=99
#fi

Even better, for programmers familiar with C, C++, etc. you can omit the curly braces completely for only one statement: 更好的是,对于熟悉C,C ++等的程序员来说,只需要一个语句就可以完全省略花括号:

if x:
    do_stuff()

Beautiful. 美丽。 As mentioned before, Python can also automatically correct code with incorrect delimiters, so this code is also legal: 如前所述,Python还可以使用不正确的分隔符自动更正代码,因此此代码也是合法的:

if x:
    do_a_hundred_or_more_statements()
    x = x + 1
    print(x)



As this must make you love Python even more , I send you off with one last quote from the docs. 因为这必须让你喜欢Python,我会向你发送文档的最后一句话。

Now as you can see from this series of examples, Python has advanced the state of the art of parser technology and code recognition capabilities well beyond that of the legacy languages. 现在,从这一系列示例中可以看出,Python已经提升了解析器技术和代码识别功能的先进水平,远远超出了传统语言的能力。 It has done this in a manner which carefully balances good coding style with the need for older programmers to feel comfortable with look of the language syntax. 它以一种精心平衡良好编码风格的方式完成了这一点,并且需要老程序员对语言语法的外观感到满意。

The only limitation is that these special delimiters be preceded by a hashtag symbol. 唯一的限制是这些特殊的分隔符前面有一个#标签符号。

Yes, code blocks in Python are defined by their indentation. 是的,Python中的代码块是由它们的缩进定义的。 The creators of Python were very interested in self-documenting code. Python的创建者对自我记录代码非常感兴趣。 They included indentation in the syntax as a way of innately enforcing good formatting practice. 它们在语法中包含缩进,作为一种天生地执行良好格式化实践的方式。

I programmed in Python for a few years and became quite fond of its code structure because it really is easier. 我用Python编程了几年,并且非常喜欢它的代码结构,因为它真的很容易。 Have you ever left out a closing curly brace in a large program and spent hours trying to find it? 你有没有在一个大型程序中遗漏一个结束的大括号,花了几个小时试图找到它? Not a problem in Python. 在Python中不是问题。 When I left that job and had to start using PHP, I really missed the Python syntax. 当我离开那份工作并且不得不开始使用PHP时,我真的很想念Python语法。

In Python, four spaces( 在Python中,有四个空格( ) are used for indentation in place of curly braces ( { ). )用于缩进代替花括号( { )。 Though, curly braces are used at few places in Python which serve different purpose: 虽然,在Python的几个地方使用花括号,它们用于不同的目的:

  1. Initialize a non-empty set (unordered collection of unique elements): 初始化非空集(无序的唯一元素集合):

     fuitBasket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'} 

    Citation 引文

  2. Initialize an empty dictionary (key-value pairs): 初始化一个空字典(键值对):

     telephoneNumbers = {} 
  3. Initialize a non-empty dictionary (key-value pairs): 初始化非空字典(键值对):

     telephoneNumbers = {'jack': 4098, 'sape': 4139} 

    Citation 引文

In relation to format string, curly braces take on a different meaning. 关于格式字符串,花括号具有不同的含义。 See https://docs.python.org/3/library/string.html?highlight=curly : 请参阅https://docs.python.org/3/library/string.html?highlight=curly

Format strings contain “replacement fields” surrounded by curly braces {}. 格式字符串包含由大括号{}包围的“替换字段”。 Anything that is not contained in braces is considered literal text, which is copied unchanged to the output. 大括号中未包含的任何内容都被视为文本文本,它将不加改变地复制到输出中。 If you need to include a brace character in the literal text, it can be escaped by doubling: {{ and }}. 如果您需要在文字文本中包含大括号字符,可以通过加倍{{和}}来对其进行转义。

I will give some thoughts about this question. 我会对这个问题有所了解。

Admittedly at first I also thought it is strange to write code without curly braces. 不可否认,起初我还认为编写没有花括号的代码很奇怪。 But after using Python for many years, I think it is a good design. 但在使用Python多年后,我认为这是一个很好的设计。

First, do we really need curly braces? 首先,我们真的需要花括号吗? I mean, as a human. 我的意思是,作为一个人。 If you are allowed to use curly braces in Python, won't you use indentation anymore? 如果允许你在Python中使用花括号,你不会再使用缩进吗? Of course, you will still use indentation! 当然,你仍然会使用缩进! Because you want to write readable code, and indentation is one of the key points. 因为你想编写可读代码,缩进是关键点之一。

Second, when do we really need curly braces? 第二,什么时候我们真的需要花括号? As far as I think, we only strictly need curly braces when we need to minify our source code files. 据我所知,当我们需要缩小源代码文件时,我们只需要大括号。 Like minified js files. 像缩小的js文件一样。 But will you use Python in a situation that even the size of source code is sensitive? 但是,即使源代码的大小敏感,你会使用Python吗? Also as far as I think, you won't. 据我所知,你也不会。

So finally, I think curly braces are somehow like ; 最后,我认为花括号在某种程度上是这样的; . It is just a historical issue, with or without it, we will always use indentation in Python. 这只是一个历史问题,无论有没有它,我们总是会在Python中使用缩进。

Yes you can use this library/package { Py } Use curly braces instead of indenting, plus much more sugar added to Python's syntax. 是的,你可以使用这个库/包{Py}使用花括号而不是缩进,加上Python的语法添加了更多的糖。

https://pypi.org/project/brackets/ https://pypi.org/project/brackets/

// Use braces in Python!

def fib(n) {
  a, b = 0, 1
  while (a < n) {
    print(a, end=' ')
    a, b = b, a+b
  }
  print()
}

/*
  Powerful anonymous functions
*/

print([def(x) {
  if(x in [0, 1]) {
    return x
  };
  while (x < 100) {
    x = x ** 2
  };
  return x
}(x) for x in range(0, 10)])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM