Hour 3. Logic in Programming


What You’ll Learn in This Hour:

Image How to use if to run code if something is true

Image How to create blocks

Image How to use else to run code if something is not true

Image How to use elif to test more than one condition

Image How Python considers something true or false

Image How to use try/except to avoid errors

Image When to apply logic to real-world problems


Programming is about more than storing information. It’s also filled with logic. In Hour 2, “Putting Numbers to Work in Python,” you learned about how to compare two items to see if they’re the same, different, or if one is bigger than the other. In this hour, we will combine variables and discover how to compare their contents to change how a program runs.

Using a Basic if Statement

The if statement is used when you only want to execute code if something is true. In the following example, we set num to 5. With the if statement, if num is greater than 1, we want to print whatever is stored in num. Because num is greater than 1, the value stored in num is printed:

>>> num = 5
>>> if num > 1:
...    print num
...
5

What happens if we change the operator to the less-than symbol? In that case, num will only be printed if it happens to contain a value less than 1.

>>> a = 5
>>> if a < 1:
...    print a
...
>>>

Because num contains 5, the statement num < 1 is false, so nothing is printed.

Creating Blocks

Why is some of the code indented? Python uses whitespace (tabs and spaces) to mark out blocks of code. As long as everything is indented to the same level, it’s considered to be part of the same block of code. Combined with an if statement, that lets Python know exactly how much code it should run if something is true, and where Python should start running code again if the statement isn’t true.

For example, let’s look at a small script. In it, if the person’s name is Doug, he’ll get a special greeting:

name = "Doug"
if name == 'Doug':
  print "Hello, D-man!"
print "How are you today?"

When we run it, we get the following output:

$ python if1.py
Hello, D-man!
How are you today?

But what if we change the script so that the user’s name isn’t Doug? Here is our altered script:

name = "Jesse"
if name == 'Doug':
  print "Hello, D-man!"
print "How are you today?"

Because the name is now Jesse, the special greeting won’t appear. The script will still print out the line after “Hello, D-man!” because it isn’t part of the block of code under the if statement. Here is what will be printed when we run our changed script:

$ python if1.py
How are you today?


Note: Blocks in the Shell

The Python shell lets you know the code is in a block by using three periods rather than three greater-than signs at the beginning of a line. To end the block, press Return without entering anything on that line.

Note that some shells, rather than printing out the periods, will print out nothing at all, or will insert some whitespace. No matter what, you should not see three angled brackets.


Say we run the following, saved in a file:

num = 5
if num < 5:
    print num
print "Goodbye"

Here is what would be displayed:

Goodbye

Because num, set to 5, is not less than five, the block of code under the if statement is skipped. The program starts running again where it prints Goodbye because that code has the same indention as the if block.

Although you can use either spaces or tabs, it’s considered better to use spaces. Some systems interpret tabs differently. At best, using tabs makes your code look ugly. At worst, it will make your code stop working. The standard for Python code is four spaces for each new block.


Note: Tabs or Spaces?

Technically, you can use tabs or spaces to create whitespace. As long as every line in a block is indented with the same number of spaces or tabs, you’re fine. However, tabs can wreak havoc with your code as you move between text editors. Therefore, it’s safer to just go with spaces.


Adding an else to an if

What if you want to do something if your expression ends up not being true? You can add an else to an if statement. Code in that block will be run only if the expression in the if statement is false, as shown in the following example:

>>> a = 5
>>> if a > 5:
...    print "Greater than five"
... else:
...     print "Five or less"
...
Five or less

If the expression in the if statement is true, however, the code in the else block won’t run.

>>> a = 7
>>> if a > 5:
...    print "Greater than five"
... else:
...     print "Five or less"
Greater than five

The else statement is completely optional, but if you include the else, you have to put a block of code under it. Otherwise, you’ll get an error.

In this example, we don’t have a block of code under the else statement. Python gives us an error rather than running through the if statement:

>>> a = 5
>>> if a > 5:
...    print "Greater than five"
... else:
...
File "<stdin>", line 4
^ IndentationError: expected an indented block


Note: Differences in Versions

This is slightly different in the latest version of Python, version 2.7.5. Now, you won’t get an error in the shell. You’ll just get another line, until you force an indentation error by erasing the whitespace and typing something. This only applies to the shell, though.


Testing Many Things with elif

Sometimes, you want to test more than one condition. For example, you might want to print out a different message based on the time of day or how much the total is in a shopping cart. In cases like this, you can use an elif statement.

An elif statement is another optional part of an if statement. You still have to start with an if statement, but after that, you can add on elif statements in very much the same way you created the if statement.

In this example, we code a snippet that tells customers whether they get free shipping or not. If their total is over $50, they get free shipping. If they’re getting close, with a total over $40, we print out a special message to encourage them to spend just a few dollars more:

>>> total = 40.29
>>> if total > 50:
...    print "You get free shipping!"
... elif total > 40:
...    print "Spend a bit more to get free shipping!"
... else:
...    print "Spend $50 to get free shipping"
...
Spend a bit more to get free shipping!

With an if statement that has elif statements, as soon as one of the conditions is satisfied, Python moves on to the code after the if statement. This might be the code right after the else block or the code after the last elif if you don’t have an else statement.

In this snippet, note the order of the statements as well as what is actually printed out:

>>> b = 5
>>> if b == 5:
...    print b
... elif b > 4:
...    print "Hey"
...

5

Because b is set to 5, both b == 5 and b > 4 are true. The only code executed is the block under the first true statement. Everything else is ignored.

True and False Variables

What is true? What is false? This sounds like a philosophical question. To Python, though, something being true or false is a matter of black and white. An expression, such as 5 == 6, can be true or false. Another thing, though, that can be true or false is a variable. If a variable contains something besides “nothing,” it will be evaluated as true. Otherwise, it will be evaluated as false.

This may seem esoteric, but you will see this popping up in code quite a bit. Often, a developer will just want to see if a variable contains something. You may have a message that you only want printed out if someone has any items in his or her shopping cart, or if a string actually contains any text.

In Python, a variable is true if it contains something, anything. You can create an if statement with just if and a variable. If the variable contains a value that’s not “nothing,” the block under the if statement will run.

Each data type has its own way of being false. Table 3.1 shows how some of the data types we’ll be going over can be considered “false” or “empty.”

Image

TABLE 3.1 False Data Type Values

Using try/except to Avoid Errors

In a program, you can never quite be sure what’s going to be in your variables. A user may innocently enter something that ends up crashing the program. A common error is dividing by zero. Try to get Python to divide by zero, and you’ll get an error:

>>> 5 / 0
Traceback (most recent call last):
File "<stdin>", line 1, in <module> ZeroDivisionError:
integer division or modulo by zero

How do you keep a bit of bad data from crashing the program? You use a try/except statement.

A try/except statement is made of two blocks of code. Python attempts to run the try statement first. If it gets any error, it runs the code in the except block. After that, the program keeps running as normal.

In this example, we try to divide by zero. This always causes an error, so the text under our except statement prints out.

>>> try:
...    5 / 0
... except:
...    print "Please don't do that"
...
Please don't do that

If running the code in the try block doesn’t throw any errors, Python skips whatever was in the except block. In this snippet, we divide 5 by 1, which is perfectly fine:

>>> try:
...     a = 5 / 1
...     print "Good to go!"
... except:
...     print "Please don't do that"
...
Good to go!

Because all the code is executed in the try block until there’s an error, any changes that were made by that code still stand after the error. For example, if you changed the value stored in a variable, that change wouldn’t be undone by an exception.

In this example, we increment a by 1, then try to divide by 0. Note the value held in a at the end of the snippet. It holds 6. We started off with 5, so we did manage to increment it by 1 before the error.

>>> a = 5
>>> try:
...    a = a + 1
...    a = a / 0
... except:
...    print "Please don't do that"
...
Please don't do that
>>> print a
6

For now, using a try/except will hide the error and keep running your program. Most of the time, you’ll want to know what exactly went wrong or only catch some types of errors. To see a list of exceptions, check out the Python documentation here: http://docs.python.org/2/library/exceptions.html. If we only wanted to catch a divide by zero error, our code snippet would look like this:

>>> a = 5
>>> try:
...    a = a + 1
...    a = a / 0
... except ZeroDivisionError:
...    print "Please don't do that"
...
Please don't do that
>>> print a
6

Any other errors would not be caught, and Python would throw an error and stop running.

Applying Logic to Real-World Problems

In Hour 2, we showed how a theoretical restaurant might benefit from using Python, even if all the waiter knows how to do is store numbers in variables and perform some basic math to deal with complex bills. How could knowing some of Python’s logic help the same waiter?

Most restaurants have a policy of automatically adding the tip to the bill of large parties. The waiter has had to argue with many a table about this policy, so he has decided that some text should be added to receipts explaining the “extra” charge. In this case, the interpreter won’t help much, so he creates a simple Python script:

total = 19 + 9.99 + 13.97 + 20 + 15.97 + 9.97 + 10 * 2
party = 8
print "Receipt for your meal"
if party >= 8:
     total = total + total * .2
     print "We've added the tip automatically, since your party was eight or
     larger."
print "Total: ", total
print "Thank you for dining with us today!"

When he runs it, this is printed out:

Receipt for your meal
We've added the tip automatically, since your party was eight or larger.
Total: 142.68
Thank you for dining with us today!

Later, another party comes in. This one is much smaller (and, of course, orders different dishes). He changes the first two lines of the file:

total = 13 + 14.02 + 22.35
party = 3
print "Receipt for your meal"
if party >= 8:
     total = total + total * .2
     print "We've added the tip automatically, since your party was eight or
     larger."
print "Total: ", total
print "Thank you for dining with us today!"

This time, running the script prints out the following:

Receipt for your meal
Total: 49.37
Thank you for dining with us today!

Without having to remember that parties of eight have a tip automatically added in, he gets a receipt that automatically adjusts the total and prints a message to explain the extra cost.

Summary

During this hour, you learned that you can control the flow of your program by using if statements. You also learned how to test statements to see if they are true or false. You also learned how to get around potentially problematic code by using try and except.

Q&A

Q. What if I don’t want to do anything in my except block?

A. Unlike else, the except block is required. If you don’t want to do anything in that block, put a pass statement there. Python will move past that block and continue to execute your code, as in the following example:

>>> try:
...     5 / 0
... except:
...     pass

Q. What is the best way to make a block of code?

A. Hands down, spaces are the best way. You can either add the spaces in manually (by pressing the spacebar several times) or set your editor to use spaces when you press the Tab key. Spaces are interpreted the same way across editors, but tabs are often shown to be wider or narrower.

Each editor has a different way of doing this, but it’s generally under preferences. For Notepad++, this is set under the Languages preference tab. Selecting the check box by Replace by Space will set this for all your files. For TextWrangler, the setting is under Editor Defaults. In this case, you’ll want to select Auto-expand Tabs.

If you’re using a different editor, search the Web for the name of your editor plus “spaces for tabs.”

Q. What if I only want to catch certain errors with a try/except?

A. Many times, you only want your code to keep on going when it encounters certain errors, such as dividing by zero. We’ll go into debugging and catching errors more in Hour 23, “Fixing Problem Code.” In general, it’s a good idea to be specific about what kind of errors you want to catch.

Workshop

The Workshop contains quiz questions and exercises to help you solidify your understanding of the material covered. Try to answer all questions before looking at the answers that follow.

Quiz

1. How can you tell if a section of code belongs to one block?

2. What is the difference between a try/except and an if/else?

3. When will an if statement return to the previous block of code?

Answers

1. If a section of code belongs to one block, all of the code will be indented the same amount.

2. With a try/except block, the block of code under the try statement will execute until an error is encountered. If that happens, then and only then will the block of code under the except statement execute. With an if statement, the block of code under the if statement will only execute if the if statement is true. If it is not, the code in the else statement will execute.

3. An if statement will return to the previous block of code once an if or elif statement evaluates as true, the block of code under the else statement has been run, or Python has run out of if/elif statements.

Exercise

Given a number, write a snippet of code that will print “You have money” if the number is positive, “You’re out” if it’s zero, and “You seem to be in debt” if it’s less than zero. Your code should have an if statement, an elif statement, and an else.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.182.62