Skip to main content

Numbers and Expressions | Core Python 3.8

Algo . . . What? 

    Before we start programming in earnest, I’ll try to give you an idea of what computer programming is. Simply put, it’s telling a computer what to do. Computers can do a lot of things, but they aren’t very good at thinking for themselves. They really need to be spoon-fed the details. You need to feed the computer an algorithm in some language it understands. Algorithm is just a fancy word for a procedure or recipe—a detailed description of how to do something. Consider the following:

SPAM with SPAM, SPAM, Eggs, and SPAM:  First, take some SPAM. 

Then add some SPAM, SPAM, and eggs. 

If a particularly spicy SPAM is desired, add some SPAM. 

Cook until done -- Check every 10 minutes.


Not the fanciest of recipes, but its structure can be quite illuminating. It consists of a series of instructions to be followed in order. Some of the instructions may be done directly (“take some SPAM”), while some require some deliberation (“If a particularly spicy SPAM is desired”), and others must be repeated several times (“Check every 10 minutes.”)
    Recipes and algorithms consist of ingredients (objects, things) and instructions (statements). In this example, SPAM and eggs are the ingredients, while the instructions consist of adding SPAM, cooking for a given length of time, and so on. Let’s start with some reasonably simple Python ingredients and see what you can do with them.

Numbers and Expressions 

The interactive Python interpreter can be used as a powerful calculator. Try the following:

>>> 2 + 2

This should give you the answer 4. That wasn’t too hard. Well, what about this:

>>> 53672 + 235253 

288925

Still not impressed? Admittedly, this is pretty standard stuff. (I’ll assume that you’ve used a calculator enough to know the difference between 1 + 2 * 3 and (1 + 2) * 3.) All the usual arithmetic operators work as expected. Division produces decimal numbers, called floats (or floating-point numbers).

>>> 1 / 2 

0.5

 >>> 1 / 1 

1.0

If you’d rather discard the fractional part and do integer division, you can use a double slash.

>>> 1 // 2 

>>> 1 // 1 

>>> 5.0 // 2.4 

2.0

In older versions of Python, ordinary division on integers used to work like this double slash. If you’re using Python 2.x, you can get proper division by adding the following statement to the beginning of your program (writing full programs is described later) or simply executing it in the interactive interpreter:

>>> from __future__ import division

 ■ Note  In case it’s not entirely clear, the future in the instruction is surrounded by two underscores on both sides: _ _future_ _.

Another alternative, if you’re running an old Python from the command line, is to supply the commandline switch -Qnew. There is a more thorough explanation of the __future__ stuff in the section “Back to the __future__” later in this chapter. Now you’ve seen the basic arithmetic operators (addition, subtraction, multiplication, and division), but I’ve left out a close relative of integer division.

>>> 1 % 2 

1

This is the remainder (modulus) operator. x % y gives the remainder of x divided by y. In other words, it’s the part that’s left over when you use integer division. That is, x % y is the same as x - ((x // y) * y).

>>> 10 // 3 

>>> 10 % 3 

1

 >>> 9 // 3 

>>> 9 % 3 

>>> 2.75 % 0.5 

0.25

Here 10 // 3 is 3 because the result is rounded down. But 3 × 3 is 9, so you get a remainder of 1. When you divide 9 by 3, the result is exactly 3, with no rounding. Therefore, the remainder is 0. This may be useful if you want to check something “every 10 minutes” as in the recipe earlier in the chapter. You can simply check whether minute % 10 is 0. (For a description on how to do this, see the sidebar “Sneak Peek: The if Statement” later in this chapter.) As you can see from the final example, the remainder operator works just fine with floats as well. It even works with negative numbers, and this can be a little confusing.

>>> 10 % 3 

>>> 10 % -3

-2

>>> -10 % 3 

>>> -10 % -3 

-1

Looking at these examples, it might not be immediately obvious how it works. It’s probably easier to understand if you look at the companion operation of integer division.

>>> 10 // 3 

3

 >>> 10 // -3 

-4

 >>> -10 // 3 

-4 

>>> -10 // -3 

3

>>> 2 ** 3 

>>> -3 ** 2 

-9 

>>> (-3) ** 2 

9


Given how the division works, it’s not that hard to understand what the remainder must be. The important thing to understand about integer division is that it is rounded down, which for negative numbers is away from zero. That means -10 // 3 is rounded down to -4, not up to -3. The last operator we’ll look at is the exponentiation (or power) operator.
Note that the exponentiation operator binds tighter than the negation (unary minus), so -3**2 is in fact the same as -(3**2). If you want to calculate (-3)**2, you must say so explicitly.

Hexadecimals Octals and Binary 

To conclude this section, I should mention that hexadecimal, octal, and binary numbers are written like this:

>>> 0xAF 

175 

>>> 010 

8

 >>> 0b1011010010 

722

The first digit in both of these is zero. (If you don’t know what this is all about, you probably don’t need this quite yet. Just file it away for later use.)

Comments

Popular posts from this blog

Strings | Core Python 3.8

Strings  Now what was all that "Hello, " + name + "!" stuff about? The first program in this chapter was simply print("Hello, world!") It is customary to begin with a program like this in programming tutorials. The problem is that I haven’t really explained how it works yet. You know the basics of the print statement (I’ll have more to say about that later), but what is "Hello, world!"? It’s called a string (as in “a string of characters”). Strings are found in almost every useful, real-world Python program and have many uses. Their main use is to represent bits of text, such as the exclamation “Hello, world!” Single-Quoted Strings and Escaping Quotes Strings are values, just as numbers are: >>> "Hello, world!"  'Hello, world!' There is one thing that may be a bit surprising about this example, though: when Python printed out our string, it used single quotes, whereas we used double quotes. What’s the differ...

Variables and Statements | Core Python 3.8

Variables  Another concept that might be familiar to you is variables. If algebra is but a distant memory, don’t worry: variables in Python are easy to understand. A variable is a name that represents (or refers to) some value. For example, you might want the name x to represent 3. To make it so, simply execute the following: >>> x = 3 This is called an assignment. We assign the value 3 to the variable x. Another way of putting this is to say that we bind the variable x to the value (or object) 3. After you’ve assigned a value to a variable, you can use the variable in expressions. >>> x * 2  6 Unlike some other languages, you can’t use a variable before you bind it to something. There is no “default value.” ■ Note  the simple story is that names, or identifiers, in python consist of letters, digits, and underscore characters (_). they can’t begin with a digit, so Plan9 is a valid variable name, whereas Plan is not. Statements  Until...

Execution the Program | Core Python 3.8

Saving and Executing Your Programs  The interactive interpreter is one of Python’s great strengths. It makes it possible to test solutions and to experiment with the language in real time. If you want to know how something works, just try it! However, everything you write in the interactive interpreter is lost when you quit. What you really want to do is write programs that both you and other people can run. In this section, you learn how to do just that.     First of all, you need a text editor, preferably one intended for programming. (If you use something like Microsoft Word, which I really don’t really recommend, be sure to save your code as plain text.) If you are already using IDLE, you’re in luck. With IDLE, you can simply create a new editor window with File › New File. Another window appears, without an interactive prompt. Whew! Start by entering the following: print("Hello, world!") Now select File › Save to save your program (which is, in fact, a pl...

Dictionaries: When Indices Won’t Do | Core Python 3.8

You’ve seen that lists are useful when you want to group values into a structure and refer to each value by number. In this chapter, you learn about a data structure in which you can refer to each value by name. This type of structure is called a mapping. The only built-in mapping type in Python is the dictionary. The values in a dictionary don’t have any particular order but are stored under a key, which may be a number, a string, or even a tuple. Dictionary Uses The name dictionary should give you a clue about the purpose of this structure. An ordinary book is made for reading from start to finish. If you like, you can quickly open it to any given page. This is a bit like a Python list. On the other hand, dictionaries—both real ones and their Python equivalent—are constructed so that you can look up a specific word (key) easily to find its definition (value).     A dictionary is more appropriate than a list in many situations. Here are some examples of uses of Pyth...

Lists and Tuples | Core Python 3.8

This chapter introduces a new concept: data structures. A data structure is a collection of data elements (such as numbers or characters, or even other data structures) that is structured in some way, such as by numbering the elements. The most basic data structure in Python is the sequence. Each element of a sequence is assigned a number—its position, or index. The first index is zero, the second index is one, and so forth. Some programming languages number their sequence elements starting with one, but the zeroindexing convention has a natural interpretation of an offset from the beginning of the sequence, with negative indexes wrapping around to the end. If you find the numbering a bit odd, I can assure you that you’ll most likely get used to it pretty fast.     This chapter begins with an overview of sequences and then covers some operations that are common to all sequences, including lists and tuples. These operations will also work with strings, which will be use...