Book Image

Python Essentials

By : Steven F. Lott
Book Image

Python Essentials

By: Steven F. Lott

Overview of this book

Table of Contents (22 chapters)
Python Essentials
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

The if-elif-else statement


Our central tool for conditional processing is the if statement. This is a compound statement which is built from a number of clauses. The initial clause starts with the if keyword. Any number of elif (short for "else if") clauses can be used. Each of these clauses has a conditional expression and an indented suite of statements. We can also add a single catch-all else clause at the end; this doesn't have a condition, but does have a suite of statements.

The minimal if statement, with a single clause, might look like this:

if abs(a-b) < ε:
    print("{a} \N{ALMOST EQUAL TO} {b}".format(a=a, b=b))

The if statement contains a single expression. If the expression is True, the suite of statements is executed. In this case, the suite is a single expression statement, using the print() function.

The else clause can be used in simple if statements.

if count == 0:
    print("Insufficient Data")
else:
    print("Mean = {0:.2f}".format(total/count))

In this case, we have two...