
4 The absolute basics
This chapter covers
- Indenting and block structuring
- Differentiating comments
- Assigning variables
- Optional type hints
- Evaluating expressions
- Using common data types
- Getting user input
- Using correct Pythonic style
This chapter describes the absolute basics in Python: how to use assignments and expressions, how to use numbers and strings, how to indicate comments in code, and so forth. It starts with a discussion of how Python block structures its code, which differs from every other major language.
4.1 Indentation and block structuring
Python differs from most other programming languages because it uses whitespace and indentation to determine block structure (that is, to determine what constitutes the body of a loop, the else clause of a conditional, and so on). Most languages use braces of some sort to do this. The following is C code that calculates the factorial of 9, leaving the result in the variable r:
/* This is C code */ int n, r; n = 9; r = 1; while (n > 0) { r *= n; n--; }
The braces delimit the body of the while loop, the code that is executed with each repetition of the loop. The code is usually indented more or less as shown, to make clear what’s going on, but it could also be written as follows:
/* And this is C code with arbitrary indentation */ int n, r; n = 9; r = 1; while (n > 0) { r *= n; n--; }
The code still would execute correctly, even though it’s rather difficult to read.
The Python equivalent is