Hour 2. Putting Numbers to Work in Python


What You’ll Learn in This Hour:

Image How Python stores information

Image How to do basic math in Python

Image How to compare numbers in Python

Image When to use Python to solve a math problem


Learning to store information through a program is one of the first major hurdles in learning to program. It’s a hurdle that is almost immediately useful. A calculator may be able to do math, but it often has limited storage space—and most can’t tell you if one number is larger than another, or if two numbers are equal.

Storing Information with Variables

One of the reasons we use computers is because they’re extremely good at storing information. This information can be stored permanently in many ways, such as writing it to a file or keeping it in a database. In general, when a program is running, it needs to store information on a more temporary basis because the information might have to be manipulated, reformatted, combined with other pieces of information, or forgotten so more memory can be made available. To do this, a program uses variables.

You can think of variables like cups: Sometimes they’re empty, sometimes they contain something. You can do things to the contents of the cups, such as pour them out, add them to another cup, or add ingredients to change what they are completely.

Types of Variables

Variables can hold many different kinds of information. We call these data types. In this hour, we’ll only be going over the ones that hold numbers, such as int, float, and long, but you can see more data types in Table 2.1.

Image

TABLE 2.1 Basic Data Types

How do you tell Python what data type you need a variable to be? For the most part, you don’t (at least, you don’t do this explicitly). It’s done when you actually store something in the variable.

Storing Numbers in Variables

In Python, a variable’s type is set when it’s created and you store something in it. Start up your Python interpreter and then type in the following:

>>> a = 5

In Hour 1, “Installing and Running Python,” when we typed in a number, the interpreter echoed it back. Where did the 5 go in the preceding example? It is now stored in the variable a. To see what’s stored in a, type the following:

>>> a

This time, the interpreter will echo back the value you stored into a. In Python, the equals sign doesn’t mean that two things should be equal. It’s used as one of the ways to assign a value to a variable.

How do we know what data type a variable is if we didn’t set it ourselves? Python has a number of functions built in to it (called “built-ins”), one of which is called type. You can use type to get the data type of any variable, as shown in the following example:

>>> a = 5
>>> type(a)
<type 'int'>

Variables can be used more than once, too. If you type a = 7 into the interpreter, Python will discard the 5 and set a to 7. You can also assign a variable to the value that’s in another variable, as follows:

>>> a = 7
>>> b = a
>>> b
7

In this example, b was set to whatever was in a (in this case, 7). If we change a, b will still contain 7:

>>> a = 7
>>> b = a
>>> a = 5
>>> b
7
>>> a
5

So, changing the value stored in a doesn’t change the value stored in b.

Naming Variables

You don’t have to limit your variable names to just one letter (you’d run out rather quickly!). Python is fairly easy going concerning what you can name your variables. There are only a few rules that absolutely must be followed:

Image Names can’t start with a number.

Image Names can’t be too long (the specific length depends on how much memory the computer has).

Image Names can’t contain special characters (although the underscore [_] is okay).

Just because the rules are rather permissive doesn’t mean you shouldn’t follow some standards. Standards not only make your code easier for others to follow, they make it easier for other people to help you. Even if you never plan to work in a group, at some point, you are going to have to ask someone a question about a bug. Clear code is the difference between getting an answer and being left to figure it out on your own.

Also, easy-to-read code is easy to return to down the line. You don’t want to put lots of hard work into a program only to have to rewrite it a year later when you want to make a small update. We have all made the mistake of thinking that we’ll be able to pick up where we left off without a problem. If you have variables that make no sense, you’ll be making more work for yourself.

Python has its own set of guidelines for naming variables:

Image Variable names should make sense. Don’t give your variables random names such as apple or dskadjsla. They should describe what they contain, like total or username.

Image Often, you have to use more than one word in a variable name. Separate them using an underscore rather than running them all together. numberoftoppings is not as easy to read as number_of_toppings.

Image For the most part, your variables should always be lowercase. You should only use all caps if you don’t want the value to be changed. This is called a constant.

Image If you’re going to use a single letter, avoid using a lowercase L or an uppercase O, which can look like a 1 or 0, respectively, in some fonts.


Tip: Python’s PEP 8 Style Guide

Want to learn more about Python’s styling guidelines? Check out the official style guide, called PEP 8, at http://www.python.org/dev/peps/pep-0008/.


Doing Math in Python

Math in Python is similar to what you see in the real world. It follows the same rules you probably learned in grade school, with a few exceptions. The most important difference is that, in Python, the variable you’re setting must always come before whatever calculations you’re doing, as you’ll see in the following examples:

>>> x = 5 + 1
>>> x
6
>>> 5 + 1 = x

File "<stdin>", line 1 SyntaxError: can't assign to operator

Although a teacher might not have taken any points off for writing 5 + 1 = x, Python will simply refuse to run.

Operators

Python supports all the basic operations out of the box: adding, subtracting, multiplying, dividing, negation, absolute values, and exponents. Python, however, uses a few different symbols than you might be used to using. Table 2.2 shows the most commonly used operators in Python.

Image

TABLE 2.2 Operators in Python

Order of Operations

Python follows the order of operations, which means equations are always done in this order:

1. Items in parentheses

2. Exponents and roots

3. Multiplication and division

4. Addition and subtraction

Often, textbooks and teachers will use different kinds of parentheses to make an equation easier for people to read. This will only confuse Python, however, because it uses brackets and curly braces for specific things. Therefore, just use parentheses.

In the following code snippet, note how the order of operations and the nested parentheses affect the output:

>>> 5 + 6 * 2
17
>>> 5 + 6 ** 4
1301
>>> (5 + 6) * (2 + 5 * 2)
132
>>> 5 + (4 * (4 + 2))
29

Combining Types When Doing Math

As we went over before, numbers can have more than one type. What happens when you try to use them in the same equation? In general, if all the numbers are of the same type, Python will return a number of the same type. If there’s even one float, however, it will return a float, as shown in the following examples:

>>> type(1+1)
<type 'int'>
>>> type(100000000000000000000000+1)
<type 'long'>
>>> type(1.0+1)
<type 'float'>

Note that if only integers are in the equation, an integer will be returned. For example, if you divided 1 by 2 in a calculator, you would get 0.5. What happens if you do this in the Python interpreter?

>>> 1/2
0

Zero is most certainly not what we were expecting.

The solution is to make sure one of the integers is a float, either by adding a decimal to one of the numbers or using a built-in method called float to temporarily convert a number to a float. If we make our 2 a float (by converting it, temporarily, to 2.0), what do we get back?

>>> 1/2.0

0.5

>>> 1/float(2)

0.5

If this trips you up, don’t worry. Even the most seasoned Python developers have problems with this from time to time.

Dividing by Zero

One thing you cannot do in Python: divide any number by zero.

>>> 1/0

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

This isn’t a quirk in Python. This is a mathematical fact. Technically, any number divided by zero (including zero) is undefined. Why? Because if it returned a number, the logic behind mathematics would break down.

Comparing Numbers

Often in programming you find yourself needing to compare two things to see if one is larger or if they’re equal. Python has special operators reserved just for comparing items. Table 2.3 lists all of the comparison operators in Python.

Image

TABLE 2.3 Comparison Operators


Warning: Double Equals and Single Equals

Note that the double equals (==) and the single equals (=) do very different things!

It’s common for new developers to confuse the two, which can lead to some very strange behavior when the code is running.


What do the “True” and “False” results mean in Table 2.3? In Python, True and False have special meaning. They mean that an expression was either true or it wasn’t. This will be of huge importance in Hour 3, “Logic in Programming.”

Applying Python Math in the Real World

At this point, you may not think you have enough knowledge to do anything especially practical in Python. After all, it’s not like you can write an invoicing system or a dynamic website yet. Even a little bit of Python can help make your life easier, though!

Let’s say you work at a restaurant where the most advanced piece of technology is an ancient cash register that’s little more than a box full of money with a calculator on top. Recently, though, they acquired a very basic laptop. This blew their budget for IT, though, so all it has on it at the moment is what comes with the operating system and Python.

If a large party comes in, it’s up to a waiter to keep track of each seat and add up the bill total. What if, at the last minute, the customers decide they want separate checks, or that an appetizer should be split between only three of them?

Let’s say the waiter enters in each seat’s meal total and each of the appetizers into its own variable:

>>> seat1 = 13.50
>>> seat2 = 12.00
>>> seat3 = 14.64
>>> seat4 = 22.70
>>> seat5 = 16.73
>>> app1 = 9.99

At first, the waiter sums up the total bill because the table hasn’t told him that they want separate checks yet:

>>> total = (seat1 + seat2 + seat3 + seat4 + seat5 + app1)
>>> total + total * .05
94.038

He rounds up to $94.04 and hands the bill over. Now is when they say they want to have separate checks, and the appetizer should be split between seats 1, 2, and 3. Normally, the waiter would have to type everything in again. This time, though, he simply enters the following lines:

>>> seat1 + app1 / 3
16.83
>>> seat2 + app1 / 3
15.33
>>> seat3 + app1 / 3
17.97
>>> seat4
22.7
>>> seat5
16.73

Now, rather than having to enter in all the totals again, he can easily print out new receipts for each seat without having to reenter their meals!

Summary

During this hour, you learned that Python stores information in items called variables. You also learned about common conventions for naming variables. Finally, you learned how to perform math operations with Python.

Q&A

Q. How long can a long number be?

A. That’s a tricky question. In Python, the longest number that long can be is determined by how much memory your machine has. The more numbers it can keep in memory at one time, the longer a long number can be. This shouldn’t be an issue on most computers, though. You would need to have a number that’s big enough to fill up your available memory and your hard drive, and this would be an enormous number even on the most underpowered machines.

Q. What’s a PEP?

A. A PEP is a Python Enhancement Proposal. A PEP is a document that describes a way in which Python can be made better. Some don’t affect the language at all (such as the style guide), whereas others may add or remove a feature from Python. Others describe processes, such as how to submit a PEP or hand an existing PEP to another developer.

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. What is the difference between = and ==?

2. What happens if you add an integer and a float?

3. What’s the result of this statement: 1 + 2 * 3

Answers

1. A single equals sign (=) is used to set variables to a new value. The double equals (==) is used to compare one variable to another to see if they’re equal.

2. Python returns a float if you add an integer and a float together.

3. The answer is 7. Remember that multiplication comes before addition.

Exercise

Write a single line of Python code that would satisfy this situation: You’re ordering some supplies from a store, and you need to figure out what the total price is. The supplies cost $10. You have a 30% discount at this store, state tax is 5%, and shipping will be $7.50.

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

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