Chapter 4. The absolute basics

 

This chapter covers

  • Indenting and block structuring
  • Differentiating comments
  • Assigning variables
  • 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 type a number or a string, 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. Here 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 like this:

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

Here’s the Python equivalent:

4.2. Differentiating comments

4.3. Variables and assignments

4.4. Expressions

4.5. Strings

4.6. Numbers

4.7. The None value

4.8. Getting input from the user

4.9. Built-in operators

4.10. Basic Python style

Summary

sitemap