Skip to Content
The Python Book
book

The Python Book

by Rob Mastrodomenico
January 2022
Beginner to intermediate
272 pages
6h 51m
English
Wiley
Content preview from The Python Book

11Loops, if, Else, and While

This chapter is now going to cover the following important aspects of programming namely loops, if, else, and while statements. These statements are the key components of programming and allow us to operate on our objects. We have covered aspects of logic earlier when we considered comparison and equality and that is key when we look at if statements which is the first aspect we will consider here. The key to an if statement is that we need a statement that returns a true or false value. So let's consider the following statement:

image

Now, the first line is an assignment and the second is comparison and its with the second line that we can introduce an if statement:

image

What we have done here is test the return value of the statement and if its true then we increment the variable x by 1. That is the essence of an if statement, we test to see if the return of a logic statement is true and if it is we do something within that statement. We can extend the example by introducing the concept of an else statement. Essentially given the if statement tests if a statement is true the else deals with if the statement is false.

image

Now what we have done is assign x ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

The Quick Python Book, Third Edition

The Quick Python Book, Third Edition

Naomi Ceder, David Fugate
Serious Python

Serious Python

Julien Danjou

Publisher Resources

ISBN: 9781119573319Purchase Link