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:
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:
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.
Now what we have done is assign x ...
Get The Python Book 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.