DevNet Associate DEVASC 200-901 Official Certification Guide by Adrian Iliesiu (z-lib.org)

(andrew) #1

whitespace indenting matters very much in Python. The
clause of an if statement must be indented (four spaces
is the standard) from the beginning of the if statement.
The following example looks for a condition where the
variable n is equal to 5 and prints a message to the
console indicating that the number is indeed a 5:


Click here to view code image


>>> n = 20
>>> if n == 20:
... print('The number is 20')
...
The number is 20

The Python interpreter uses three dots to let you
continue the clause for the if statement. Notice that there
is space between the start of the dots and the print()
statement. Without these four spaces, Python would spit
back a syntax error like this:


Click here to view code image


>>> if n == 20:
... print('oops')
File "<stdin>", line 2
print('oops')
^
IndentationError: expected an indented block

The goal of an if statement is to determine the “truth” of
the elements under evaluation. This is Boolean logic,
meaning that the operators evaluate True or False (refer
to Table 3-4). The previous example is determining
whether a variable is equal to a specific integer. What if
the number is different? You might want to apply other
logic by asking more questions. This is where else if (elif
in Python) comes into play.

Free download pdf