Simple Statements
The statements introduced in this chapter will involve tests or conditions. More syntax for conditions will be introduced later, but for now consider simple arithmetic comparisons that directly translate from math into Python. Try each line separately in the Shell
You see that conditions are either
True or False. These are the only possible Boolean values (named after 19th century mathematician George Boole). In Python the name Boolean is shortened to the type bool. It is the type of the results of true-false conditions or tests.
Note
The Boolean values
True and False have no quotes around them! Just as '123' is a string and 123 without the quotes is not, 'True' is a string, not of type bool.
Simple if Statements
Run this example program, suitcase.py. Try it at least twice, with inputs: 30 and then 55. As you an see, you get an extra result, depending on the input. The main code is:
The middle two line are an
if statement. It reads pretty much like English. If it is true that the weight is greater than 50, then print the statement about an extra charge. If it is not true that the weight is greater than 50, then don’t do the indented part: skip printing the extra luggage charge. In any event, when you have finished with the if statement (whether it actually does anything or not), go on to the next statement that is not indented under the if. In this case that is the statement printing “Thank you”.
The general Python syntax for a simple
if statement isifcondition:indentedStatementBlock
If the condition is true, then do the indented statements. If the condition is not true, then skip the indented statements.
Another fragment as an example:
As with other kinds of statements with a heading and an indented block, the block can have more than one statement. The assumption in the example above is that if an account goes negative, it is brought back to 0 by transferring money from a backup account in several steps.
In the examples above the choice is between doing something (if the condition is
True) or nothing (if the condition is False). Often there is a choice of two possibilities, only one of which will be done, depending on the truth of a condition.
if-else Statements
Run the example program,
clothes.py. Try it at least twice, with inputs 50 and then 80. As you can see, you get different results, depending on the input. The main code of clothes.py is:
The middle four lines are an if-else statement. Again it is close to English, though you might say “otherwise” instead of “else” (but else is shorter!). There are two indented blocks: One, like in the simple
if statement, comes right after the if heading and is executed when the condition in the if heading is true. In the if-else form this is followed by an else: line, followed by another indented block that is only executed when the original condition is false. In an if-else statement exactly one of two possible indented blocks is executed.
No comments:
Post a Comment