Chapter 2. Numbers and Operators

From our first breath of air, we are raised to use numbers. As a baby, we use them for estimating distance as we begin to crawl and, eventually, stand. As time progresses, we branch out and use them on a more conscious level, such as when we purchase a beverage or calculate our monthly budget. Whether you are one year old or 90, to some degree you are familiar with numbers. Indeed, numbers are such a familiar concept that you probably don't notice the many different ways in which you use them depending on their context.

In this chapter, you are re-introduced to numbers and some of the ways in which Python works with them, including basic arithmetic and special string format specifiers for its different types of numbers.

In this chapter you learn:

  • To be familiar with the different basic categories of numbers that Python uses.

  • To be familiar with the methods for using those numbers.

  • The displaying and mixing the various number types.

Different Kinds of Numbers

If you have ever used a spreadsheet, you've noticed that the spreadsheet doesn't just look at numbers as numbers but as different kinds of numbers. Depending on how you've formatted a cell, the spreadsheet will have different ways of displaying the numbers. For instance, when you deal with money, your spreadsheet will show one dollar as 1.00. However, if you're keeping track of the miles you've traveled in your car, you'd probably only record the miles you've traveled in tenths of a mile, such as 10.2. When you name a price you're willing to pay for a new house you probably only think to the nearest thousand dollars. At the large end of numbers, your electricity bills are sent to you with meter readings that come in at kilowatt hours, which are each one thousand watts per hour.

What this means in terms of Python is that, when you want to use numbers, you sometimes need to be aware that not all numbers relate to each other (as you see with imaginary numbers in this chapter), and sometimes you'll have to be careful about what kind of number you have and what you're trying to do with it. However, in general, you will use numbers in two ways: The first way will be to tell Python to repeat a certain action, and the second way will be to represent things that exist in the real world (that is, in your program, which is trying to model something in the real world). You will rarely have to think of numbers as anything besides simple numbers when you are counting things inside of Python. However, when you move on to trying to solve problems that exist in the real world — things that deal with money, science, cars, electricity, or anything else — you'll find yourself more aware about how you use numbers.

Numbers in Python

Python offers three different kinds of numbers with which you can work: integers, floating-point numbers (or floats), and imaginary numbers.

In previous versions of the language, Python had a different way of handling larger numbers. If a number ranged from −2,147,483,648 to +2,147,483,647, it was deemed an integer. Anything larger was promoted to a long. All that has changed, and the two types have now merged. Now, integers are described as a whole number, either positive or negative.

To determine the class of a number, you can use a special function that is built into Python, called type. When you use type, Python will tell you what kind of data you're looking at. Let's try this with a few examples.

The last type of number that Python offers is oriented toward engineers and mathematicians. It's the imaginary number, and you may remember it from school; it's defined as the square root of −1. Despite being named imaginary, it does have a lot of practical uses in modeling real-world engineering situations, as well as in other disciplines like physics and pure math. The imaginary number is built into Python so that it's easily usable by user communities who frequently need to solve their problems with computers. Having this built-in type enables Python to help them do that. If you happen to be one of those people, you will be happy to learn that you're not alone, and Python is there for you.

Program Files

By now you should be fairly comfortable using the Python shell and writing different lines of code within it. You've used it for all of the examples thus far, but now you are going to use it in a different manner. Instead of simply typing in single lines of code that disappear once you close the GUI, you are now going to create and save actual files that you can open and use again.

For the remainder of this chapter, you are encouraged to use the Python shell along with Notepad to create your very own files.

Using the Different Types

Except for the basic integer, the other number types can grow to an unwieldy number of digits to look at and make sense of. Therefore, very often when these numbers are generated, you will see them in a format that is similar to scientific notation. Python will let you input numbers in this format as well, so it's a two-way street. There are many snags to using very large integers and floats. The topic is quite detailed and not necessarily pertinent to learning Python. If you want to know more about floating-point numbers in general, and what they really mean to a computer, the paper at http://docs.sun.com/source/806-3568/ncg_goldberg.html is a very good reference, although the explanation will only make sense to someone with prior experience with computers and numbers. Don't let that stop you from looking, though. It may be something you want to know about at some point in the future.

More commonly, you will be using integers and floats. It wouldn't be unusual to acquire a number from somewhere such as the date, the time, or information about someone's age or the time of day. After that data, in the form of a number, is acquired, you'll have to display it.

The usual method of doing this is to incorporate numbers into strings. You can use the format specifier method that was used in Chapter 1. It may make intuitive sense to you that you should also be able to use the + method for including a number in a string, but in fact this does not work, because deep down they are different types, and the + operator is intended for use only with two things of the same type: two strings, two numbers, or two other objects and types that you will encounter later. The definite exceptions are that floats and integers can be added together. Otherwise, you should expect that different types won't be combined with the + operation.

You are likely wondering why a string format specifier can be used to include a number, when a + can't. The reason is that the + operation relies on information contained in the actual items being added. Almost everything you use in Python can be thought of as an object with properties, and all of the properties combined define the object. One important property of every object is its type, and for now the important thing to understand about a type is that certain naturally understood things like the + operation work only when you perform them with two objects of compatible types. In most cases, besides numbers, compatible types should be thought of as the same type.

If you do want to use the + operation with numbers and strings (and doing this is usually a matter of style that you can decide for yourself), you can use a built-in function called str that will transform, if possible, numbers into a string. It enables you to do things such as add strings and numbers into a single string. You can use str with most objects because most objects have a way of displaying themselves as strings. However, for the sake of consistency, you'll use string format specifiers for now.

Basic Math

It's more common than not that you'll have to use the numbers in your program in basic arithmetic. Addition, subtraction, division, and multiplication are all built in. Addition and subtraction are performed by the + and − symbols.

Some Surprises

You need to be careful when you are dealing with common floating-point values, such as money. Some things in Python are puzzling. For one thing, if you manipulate certain numbers with seemingly straightforward math, you may still receive answers that have extra values trailing them, such as the following:

>>> 4023 - 22.4
4000.5999999999999

The trailing nines could worry you, but they merely reflect the very high precision that Python offers. However, when you print or perform math, this special feature actually results in precise answers.

Using Numbers

As you can see from the previous example, you can display numbers with the print() function by including the numbers into strings, for instance by using a format specifier. The important point is that you must determine how to display your numbers so that they mean what you intend them to mean, and that depends on knowing your application.

Order of Evaluation

When doing math, you may find yourself looking at an expression like 4*3+1/4–12. The puzzle you're confronted with is determining how you're going to evaluate this sort of expression and whether the way you would evaluate it is the same way that Python would evaluate it. The safest way to do this is to always enclose your mathematical expressions in parentheses, which will make it clear which math operations will be evaluated first.

Python evaluates these basic arithmetic operations as follows: Multiplication and division operations happen before addition and subtraction, but even this can become confusing.

Number Formats

When you prepare strings to contain a number, you have a lot of flexibility. The following Try It Out shows some examples.

For displaying money, use a format specifier indicating that you want to limit the number of decimal places to two.

Mistakes Will Happen

While you are entering these examples, you may make a mistake. Obviously, there is nothing that Python can do to help you if you enter a different number; you will get a different answer than the one in this book. However, for mistakes such as entering a letter as a format specifier that doesn't mean anything to Python or not providing enough numbers in a sequence you're providing to a string's format specifiers, Python tries to give you as much information as possible to indicate what's happened so that you can fix it.

Some Unusual Cases

Python offers one other feature with its numbers that is worth knowing about so that you understand it when you encounter it. The normal counting system that we use is called base 10, or radix 10. It includes numbers from 0 to 9. Numbers above that just involve combining 0 through 9. However, computers commonly represent the binary numbers they actually deal with in base 8, called octal, and base 16, also called hexadecimal. These systems are often used to give programmers an easier way to understand bytes of data, which often come in one and two chunks of 8 bits.

In addition, neither octal nor hexadecimal can be displayed as negative numbers. Numbers described in this way are said to be unsigned, as opposed to being signed. The sign that is different is the + or − sign. Normally, numbers are assumed to be positive, but if a number is a signed type, it can be negative as well. If a number is unsigned, it has to be positive; and if you ask for the display of a negative number but in a signed format string, you'll get unusual answers.

Summary

This chapter introduced you to numbers in Python, although it doesn't cover everything available. You've seen and used three kinds of built-in numbers that Python knows about: integers, floats, and imaginary numbers. You have learned how to use string format specifiers to allow you to include numbers in your strings, and you've formatted those numbers in strings with different styles.

An important thing to remember is that the format, or how the number is displayed in a string, doesn't change the value of the number. Floats remain floats even when they are printed as integers, and vice versa.

You've performed the major built-in arithmetic operations: addition, subtraction, multiplication, division, and modulus. You have learned that if integers are mixed with a float, the result is a float, or if two integers are divided, they may also return a float, where appropriate. If arithmetic is done with an integer or a float combined with an imaginary number, the result will be a complex number that separates the real component and the imaginary component. You've also learned about the type function, which enables you to determine what type of number you actually have.

Lastly, you generally use numbers in base 10, or radix 10. Computers in general, and Python in particular, can easily translate numbers to base 8, or octal, and base 16, or hexadecimal.

The key things to take away from this chapter are:

  • There are three types of numbers in Python. Those are: integers, which are whole numbers (both negative and positive; floating-point numbers, which are any number with a decimal value; and imaginary number, which is the square-root of 1, and is used in the world of engineering and physics.

  • The + operator, when used on strings, concatenates two or more strings together. For instance, if you write print ("Hello," + " how are you?"), the result will be one sentence: "Hello, how are you?"

  • To convert a number to a string, you can use the str function.

  • Dividing two integers can sometimes result in a floating-point number (i.e.; 3/2). Dividing an integer by a floating-point decimal will always result in a floating-point number.

  • The modulus operator (%) is used to return the remainder in a division. For instance, 5 % 2 will return 1.

  • Using parentheses in your calculations helps to ensure the proper order of evaluation.

Exercises

Do the following first three exercises in Notepad and save the results in a file called ch2_exercises.py. You can run it from within Python by opening the file and choosing Run Module.

  1. In the Python shell, multiply 5 and 10. Try this with other numbers as well.

  2. Print every number from 6 through 14 in base 8.

  3. Print every number from 9 through 19 in base 16.

  4. Try to elicit other errors from the Python interpreter — for instance, by deliberately misspelling print as pinrt. Notice how as you work on a file in the Python shell, it will display print differently than it does pinrt.

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

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