32
Making Decisions in Python
The familiar if-else
C and Java syntax has its analog in Python. However, it is important to note that any conditional statement ends with a colon and that all the statements that are to be executed must be indented by four spaces. Many Python development environments allow you to use tabs to create this indentation:
if y > 0: z = x / y print("z = ", z)
If you want to carry out either one set of statements or another depending on a single condition, you should use the else
clause along with the if
statement:
if y > 0: z = x / y else: z = 0
If the else
clause contains multiple statements, they must be indented, as in the previous example. Note that the else
clause also requires a colon to set it off.
Python does ...
Get Python Programming with Design Patterns now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.