Python is a computer programming language. Unlike natural languages we use daily, the biggest difference lies in that natural languages may have different interpretations in varying contexts. However, for computers to execute tasks via programming languages, the programs written in these languages must be completely unambiguous. Thus, every programming language has its own set of syntax. Compilers or interpreters are responsible for converting syntactically valid program code into machine code executable by the CPU before execution. Python is no exception.
Python boasts simple syntax that adopts an indentation-based format, and the code written looks like this:
# print absolute value of an integer:
a = 100
if a >= 0:
print(a)
else:
print(-a)
Lines starting with # are comments. Comments are for human readers, can contain any content, and will be ignored by the interpreter. Every other line is a single statement. When a statement ends with a colon (:), the indented lines below are regarded as a code block.
Indentation has both pros and cons. The advantage is that it forces you to write well-formatted code, but there is no rule specifying whether to use spaces or tabs for indentation. By convention, you should always stick to 4 spaces for indentation.
Another advantage of indentation is that it pushes you to write code with fewer indentation levels. You will tend to split long sections of code into several functions, resulting in code with shallower indentation.
The downside of indentation is that the copy-paste function becomes ineffective, which is quite frustrating. When refactoring code, you have to recheck the indentation of pasted code to ensure correctness. Besides, it’s difficult for IDEs to format Python code as seamlessly as they do for Java code.
Last but not least, please note that Python programs are case-sensitive. Errors in capitalization will cause the program to throw exceptions.
Python uses indentation to organize code blocks. Please strictly follow the conventional practice and always use 4 spaces for indentation.
In your text editor, enable the setting that automatically converts tabs to 4 spaces to avoid mixing tabs and spaces.