Home  >  Article  >  Backend Development  >  Why does python need indentation control?

Why does python need indentation control?

(*-*)浩
(*-*)浩Original
2019-07-20 10:06:055335browse

Why does Python have such high requirements for indentation?

Why does python need indentation control?

It’s easy to get an error if the indentation is incorrect! (Recommended learning: Python video tutorial)

Because Python uses indentation to replace begin and and in other programming languages, indentation in Python (Indentation) Determines the scope of the code.

Depending on its designers wanting a more concise programming language!

Many computer programming languages ​​use characters (such as curly braces { and }) or keywords (such as begin and end) to divide code segments.

In these languages, using consistent code indentation can increase the readability of the code, and there are many convenient tools to organize the indented code.

When Guido van Rossum began to think about designing the Python language, he decided to use code indentation to distinguish the code block structure and avoid typing too many curly braces and keywords.

Pyhon uses whitespace to distinguish code structure. This is the first unusual thing that beginners need to pay attention to. The amount of whitespace for indentation is variable, but all code block statements must contain the same indentation. The number of blanks must be strictly enforced. And people with experience in other language development will find it strange.

But using Python - after a while it will feel natural and you will get used to writing concise code for a lot of programming work.

Example

if True:
    print "True"
else:
  print "False"

The following code will execute an error:

Example

#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 文件名:test.py

if True:
    print "Answer"
    print "True"
else:
    print "Answer"
    # 没有严格缩进,在执行时会报错
  print "False"

Execute the above code , the following error reminder will appear:

$ python test.py  
  File "test.py", line 10
    print "False"
                ^
IndentationError: unindent does not match any outer indentation level

IndentationError: unindent does not match any outer indentation level error indicates that the indentation methods you use are inconsistent, some are tab key indentation, and some are space indentation, change it to consistent Can.

For more Python related technical articles, please visit the Python Tutorial column to learn!

The above is the detailed content of Why does python need indentation control?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn