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

Python

Python Problem Overview


I was reading that Python does all it's "code blocks" by indentation, rather than with curly braces. Is that right? So functions, if's and stuff like that all appear without surrounding their block with curly braces?

Python Solutions


Solution 1 - Python

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:

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

Solution 2 - Python

Correct for code blocks. However, you do define dictionaries in Python using curly braces:

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

Ahhhhhh.

Solution 3 - Python

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

Solution 4 - Python

Python with Braces is a variant of python that lets you do exactly that. It's a project that I've been working on lately together with my friend.

Solution 5 - Python

Solution 6 - Python

Yup :)

And there's (usually) a difference between 4 spaces and a tab, so make sure you standardize the usage ..

Solution 7 - Python

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. It doesn't take long for it to feel completely natural.

Solution 8 - Python

>>> 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! Take a look at below:

if x: #{
    x += 1
#}

For Ada or Pascal programmers, I take delight in revealing to you:

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. This allows the following to be recognized as legal Python:

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

And this, for Bash users:

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:

if x:
    do_stuff()

Beautiful. As mentioned before, Python can also automatically correct code with incorrect delimiters, so this code is also legal:

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. > 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. 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.

Solution 9 - Python

Python does not use curly braces for code blocks:

>>> 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. 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. 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.

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:

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

Solution 10 - Python

Yes you can use this library/package { Py } Use curly braces instead of indenting, plus much more sugar added to Python's syntax.

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

Solution 11 - Python

As others have mentioned, you are correct, no curly braces in Python. Also, you do not have no end or endif or endfor or anything like that (as in pascal or ruby). All code blocks are indentation based.

Solution 12 - Python

Yes, code blocks in Python are defined by their indentation. The creators of Python were very interested in self-documenting code. 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. 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. When I left that job and had to start using PHP, I really missed the Python syntax.

Solution 13 - Python

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.

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? 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. But will you use Python in a situation that even the size of source code is sensitive? 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.

Solution 14 - Python

In Python, four spaces( ) are used for indentation in place of curly braces ({). Though, curly braces are used at few places in Python which serve different purpose:

  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

Solution 15 - Python

In relation to format string, curly braces take on a different meaning. See 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 }}.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionopenfrogView Question on Stackoverflow
Solution 1 - PythonAdam RosenfieldView Answer on Stackoverflow
Solution 2 - PythonPaul D. WaiteView Answer on Stackoverflow
Solution 3 - PythonLucas JonesView Answer on Stackoverflow
Solution 4 - PythoneshiraziView Answer on Stackoverflow
Solution 5 - PythonmaldunView Answer on Stackoverflow
Solution 6 - PythoncwapView Answer on Stackoverflow
Solution 7 - PythonSkilldrickView Answer on Stackoverflow
Solution 8 - PythonBenjView Answer on Stackoverflow
Solution 9 - PythonbwDracoView Answer on Stackoverflow
Solution 10 - PythonFernando CesarView Answer on Stackoverflow
Solution 11 - PythonmiyaView Answer on Stackoverflow
Solution 12 - PythonCode CavalierView Answer on Stackoverflow
Solution 13 - PythonSrawView Answer on Stackoverflow
Solution 14 - PythonRBTView Answer on Stackoverflow
Solution 15 - Pythonxxkeith20xxView Answer on Stackoverflow