Text
stringlengths
1
9.41k
For base 10, we use the numerals 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9. However, apart from the fact that most of us conveniently have ten fingers to count on, the choice of 10 as a base is arbitrary. ###### Computers and the binary system As noted, computers use the binary system.
This choice was originally motivated by the fact that electronic components which can be in one of two states are generally easier to design and implement than components that can be in one of more than two states. So how does the binary system work?
It, too, is a positional numeral _system, but instead of using 10 as a base we use 2._ When using base 2, we need only two numerals: 0 and 1. In the binary system, we represent numbers as coefficients in a sequence of powers of two.
As with the decimal system, this is best explained with an example. Take the decimal number 975. In binary this is 1111001111.
That’s 1 × 2[9] + 1 × 2[8] + 1 × 2[7] + 1 × 2[6] + 0 × 2[5] + 0 × 2[4] + 1 × 2[3] + 1 × 2[2] + 1 × 2[1] + 1 × 2[0] Again, doing the arithmetic the Kewa counting system in Papua New Guinea is base 37—counting on fingers and other parts of the body: heel of thumb, palm, wrist, forearm, etc, up to the top of the head,...
See: Wolfers, E. P. (1971).
“The Original Counting Systems of Papua and New Guinea”, The Arithmetic Teacher, [18(2), 77-83, https://www.jstor.org/stable/41187615.](https://www.jstor.org/stable/41187615) ----- 1 × 2[9] = 1000000000 1 × 2[8] = 0100000000 1 × 2[7] = 0010000000 1 × 2[6] = 0001000000 0 × 2[5] = 0000000000 0 × 2[4] = 0000000000...
To verify, let’s represent these values in decimal format and check our arithmetic. 1 × 2[9] = 512 1 × 2[8] = 256 1 × 2[7] = 128 1 × 2[6] = 064 0 × 2[5] = 000 0 × 2[4] = 000 1 × 2[3] = 008 1 × 2[2] = 004 1 × 2[1] = 002 1 × 2[0] = 001 Indeed, this adds to 975. Where in the decimal system we have the ones plac...
11. That’s one two, and one one. How about the decimal number 10? 1010. That’s one eight, zero fours, one two, and zero ones. How about the decimal number 13? 1101.
That’s one eight, one four, zero twos, and one one. ###### Binary arithmetic Once you get the hang of it, binary arithmetic is straightforward.
Here’s the most basic example: adding 1 and 1. 1 + 1 1 0 ----- In the ones column we add one plus one, that’s two—binary 10—so we write 0, carry 1 into the twos column, and then write 1 in the twos column, and we’re done. Now let’s add 1011 (decimal 11) and 11 (decimal 3). 1 0 1 1 + 1 1 1 1 1 0 In the ones colu...
Then in the twos column we add one (carried) plus one, plus one, that’s three—binary 11—so we write 1 and carry 1 into the fours column.
In the fours column we add one (carried) plus zero, so we write 1, and we have nothing to carry. In the eights column we have only the single eight, so we write that, and we’re done.
To verify (in decimal): 1 × 2[3] + 1 × 2[2] + 1 × 2[1] + 0 × 2[0] = 1 × 8 + 1 × 4 + 1 × 2 + 0 × 1 = 14 That checks out. ###### 2.7 Exercises **Exercise 01** Write a line of Python code that prints your name to the console. **Exercise 02** Multiple choice: Python is a(n) ________ programming language. a.
compiled b. assembly c. interpreted d. binary **Exercise 03** True or false?
Code that you write in the Python shell is saved. **Exercise 04** How do you exit the Python shell? **Exercise 05** Python can operate in two different modes.
What are these modes and how do they differ? ----- **Exercise 06** The following is an example of what kind of code? ``` 1001011011011011 1110010110110001 1010101010101111 1111000011110010 0000101101101011 0110111000110110 ``` **Exercise 07** Calculate the following sums in binary: a.
10 + 1 b. 100 + 11 c. 11 + 11 d. 1011 + 10 After you’ve worked these out in binary, convert to decimal form and check your arithmetic. **Exercise 08 (challenge!)** Try binary subtraction.
What is 11011 - 1110?
After calculating in binary, convert to decimal and check your answer. ----- #### Chapter 3 ### Types and literals This chapter will expand our understanding of programming by introducing types and literals.
All objects in Python have a type, and literals are fixed values of a given type. For example, the literal 1 is an integer and is of type int (short for “integer”).
Python has many different types. **Learning objectives** - You will learn about many commonly used types in Python. - You will understand why we have different types. - You will be able to write literals of various types. - You will learn different ways to write string literals which include various quotat...
There are many types: motorcycles, mopeds, automobiles, sport utility vehicles, busses, vans, tractor-trailers, pickup trucks, all-terrain vehicles, etc., and agricultural vehicles such as tractors, harvesters, etc.
Each type has characteristics which distinguish it from other types.
Each type is suited for a particular purpose (you wouldn’t use a moped to do the work of a tractor, would you?). Similarly, everything in Python has a type, and every type is suited for a particular purpose.
Python’s types include numeric types such as integers and floating-point numbers; sequences such as strings, lists, and tuples; Booleans (true and false); and other types such as sets, dictionaries, ranges, and functions. Why do we have different types in a programming language?
Primarily for three reasons. First, different types have different requirements regarding how they are stored in the computer’s memory (we’ll take a peek into this when we discuss representation). Second, certain operations may or may not be appropriate for different types.
For example, we can’t raise 5 to the 'pumpkin' power, or divide ``` 'illuminate' by 2. ``` Third, some operators behave differently depending on the types of their operands.
For example, we’ll see in the next chapter how + is used to add numeric types, but when the operands are strings + performs concatenation.
How does Python know what operations to perform and what operations are permitted? It checks the type of the operands. ###### What’s a literal? A literal is simply fixed values of a given type.
For example, 1 is a literal. It means, literally, the integer 1. Other examples of literals follow. ###### Some commonly used types in Python Here are examples of some types we’ll see.
Don’t worry if you don’t know what they all are now—all will become clear in time. Type Description Example(s) of literals `int` integer `42, 0, -1` `float` floating-point `3.14159, 2.7182, 0.0` number `str` string `'Python', 'badger', 'hovercraft'` `bool` Boolean `True, False` `NoneType` none, no value `None` `...
Examples of int literals: 1, 42, -99, 0, 10000000, etc. For readability, we can write integer literals with underscores in place of thousands separators.
For example, 1_000_000 is rather easier to read than 1000000, and both have the same value. ``` float ``` Objects of the float type represent floating-point numbers, that is, numbers with decimal (radix) points.
These approximate real numbers (to varying degrees; see the section on representation error).
Examples of ``` float literals: 1.0, 3.1415, -25.1, etc. str ``` A string is an ordered sequence of characters. Each word on this page is a string.
So are "abc123" and "@&)z)$"—the symbols of a string needn’t be alphabetic. In Python, objects of the str (string) type hold zero or more symbols in an ordered sequence.
Strings must be delimited to distinguish them from variable names and other identifiers which we’ll see later.
Strings may be delimited with single quotation marks, double quotation marks, or “triple quotes.” Examples of str literals: "abc", "123", ``` "vegetable", "My hovercraft is full of eels.", """What nonsense is this?""", etc. ``` Single and double quotation marks are equivalent when delimiting strings, but you must be c...
"foo" and 'foo' are both valid string literals; ``` "foo' and 'foo" are not. >>> "foo' File "<stdin>", line 1 "foo' ^ SyntaxError: unterminated string literal (detected at line 1) ``` ----- It is possible to have a string without any characters at all!
We call this the empty string, and we write it '' or "" (just quotation marks with nothing in between). Triple-quoted strings have special meaning in Python, and we’ll see more about that in Chapter 6, on style.
These can also be used for creating multi-line strings.
Multi-line strings are handy for things like email templates and longer text, but in general it’s best to use the singleor double-quoted versions. ``` bool bool type is used for two special values in Python: True and False.
bool ``` is short for “Boolean”, named after George Boole (1815–1864), a largely self-taught logician and mathematician, who devised Boolean logic—a cornerstone of modern logic and computer science (though computers did not yet exist in Boole’s day). There are only two literals of type bool: True and False.
Notice that these are not strings, but instead are special literals of this type (so there aren’t any quotation marks, and capitalization is significant).[1] ``` NoneType NoneType is a special type in Python to represent the absence of a value. ``` This may seem a little odd, but this comes up quite often in programmi...
If an object is immutable, this means it cannot be changed once it’s been created. Tuples are constructed using the comma to separate values.
The empty _tuple, (), is a tuple containing no elements._ The elements of a tuple can be of any type—including another tuple! The elements of a tuple needn’t be the same type.
That is, tuples can be _heterogeneous._ While not strictly required by Python syntax (except in the case of the empty tuple), it is conventional to write tuples with enclosing parentheses.
Examples of tuples: (), (42, `71,` `99), (x,` `y), ('cheese',` `11,` ``` True), etc. ``` A complete introduction to tuples appears in Chapter 10. ``` list ``` A list is a mutable sequence of zero or more values.
If an object is muta**ble, then it can be changed after it is created (we’ll see how to mutate** lists later).
Lists must be created with square brackets and elements 1In some instances, it might be helpful to interpret these as “on” and “off” but this will vary with context. ----- within a list are separated by commas.
The empty list, [], is a list containing no elements. The elements of a list can be of any type—including another list! The elements of a list needn’t be the same type.
That is, like tuples, lists can be heterogeneous. Examples of lists: [], ['hello'], ’['Larry', 'Moe', 'Curly'], [3, 6, ``` 9, 12], [a, b, c], [4, 'alpha', ()], etc. ``` A complete introduction to lists appears in Chapter 10. ``` dict dict is short for dictionary.
Much like a conventional dictionary, Python ``` dictionaries store information as pairs of keys and values. We write dictionaries with curly braces.
Keys and values come in pairs, and are written with a colon separating key from value. There are significant constraints on dictionary keys (which we’ll see later in Chapter 16).
However, dictionary values can be just about anything—including lists, tuples, and other dictionaries! Like lists, dictionaries are mutable.
Example: ``` {'Egbert': 19, 'Edwina': 22, 'Winston': 35} ``` A complete introduction to dictionaries appears in Chapter 16. The first few types we’ll investigate are int (integer), float (floatingpoint number), str (string), and bool (Boolean).
As noted, we’ll learn more about other types later. [For a complete reference of built-in Python types, see: https://docs](https://docs.python.org/3/library/stdtypes.html) [.python.org/3/library/stdtypes.html](https://docs.python.org/3/library/stdtypes.html) ###### 3.2 Dynamic typing You may have heard of “strongly t...
These terms do not have precise definitions, and they are of limited utility. However, it’s not uncommon to hear people referring to Python as a weakly typed language. This is not the case.
If we’re going to use these terms at all, Python exists toward the strong end of the spectrum.
Python prevents most type errors at runtime, and performs very few implicit conversions between types—hence, it’s more accurately characterized as being strongly typed. ###### Static and dynamic typing Much more useful—and precise—are the concepts of static typing and _dynamic typing.
Some languages are statically typed, meaning that types_ are known at compile time—and types of objects (variables) cannot be changed at runtime—the time when the program is run. Python, however, is dynamically typed.
This means that the types of variables can change at runtime. For example, this works just fine in Python: ----- ``` >>> x = 1 >>> print(type(x)) <class 'int'> >>> x = 'Hey!
Now I am a string!' >>> print(type(x)) <class 'str'> ``` This demonstrates dynamic typing. When we first create the variable ``` x, we assign to it the literal value 1.
Python understands that 1 is an ``` integer, and so the result is an object of type 'int' (which is short for “integer”).
On the next line, we print the type of x, and Python prints: ``` <class 'int'> as we’d expect. Then, we assign a new value to x, and ``` Python doesn’t miss a beat.
Since Python is dynamically typed, we can change a variable’s type at runtime.
When we assign to x the value 'Hey! ``` Now I am a string!', the type of x becomes 'str' (which is short for ``` “string”). In statically typed languages (say, C or Java or Rust) if we were to attempt something similar, we’d receive an error at compile time. For example, in Java: ``` int x = 1; x = "Hey!
Now I am a string!"; ``` would result in a compile-time error: “incompatible `types:` ``` java.lang.String cannot be converted to int”. ``` Notice that, unlike Python, when declaring a variable in Java a type annotation must be supplied, and once something is declared as a given type, that type cannot be changed. It’...
For example, other languages have type _inference but are still statically typed (Python has limited type inference)._ _Type inference is when the compiler or interpreter can infer something’s_ type without having to be told explicitly “this is a string” or “this is an integer.” For example, in Rust: ``` let x = 1; ...
Now I am a string!"; ``` would, again, result in a compile-time error: “mismatched `types...` ``` expected integer, found &str”. ``` While dynamic typing is convenient, this does place additional responsibility on you the programmer.
This is particularly true since Python, unlike many other languages, doesn’t care a whit about the types of formal parameters or return values of functions.
Some languages ensure that programmers can’t write code that calls a function with arguments of the wrong type, or return the wrong type of value from a function. ----- Python does not.
Python won’t enforce the correct use of types—that’s up to you! ###### 3.3 Types and memory The details of how Python stores objects in memory is outside the scope of this text.
Nevertheless, a little peek can be instructive. **Figure 3.1: A sneak peek into an int object** Figure 3.1 includes a representation of an integer with value (decimal) 65.
In binary, decimal 65 is represented as 01000001.
That’s 0 × 2[7] + 1 × 2[6] + 0 × 2[5] + 0 × 2[4] + 0 × 2[3] + 0 × 2[2] + 0 × 2[1] + 1 × 2[0] Find 01000001 within the bitstring[2] shown in Figure 3.1.
That’s the integer value.[3] Figure 3.2 shows the representation of the string 'A'.[4] The letter ‘A’ is represented with the value (code point) of 65. 2A bitstring is just a sequence of zeros and ones. 3Actually, the value is stored in two bytes 01000001 00000000 as shown within the box in Figure 3.1.
This layout in memory will vary with the particular implementation on your machine. 4Python uses Unicode encoding for strings.
For reading on character encodings, don’t miss Joel Spolsky’s “The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)”. ----- **Figure 3.2: A sneak peek into a str object** Again, find 01000001 within the bitstring Figure 3.2—that’s the encoding...
The type information is encoded in this representation (that’s a part of what all the other ones and zeros are).
That’s how Python knows. That’s one reason types are crucial! Note: Other languages do this differently, and the representations (above) will vary somewhat depending on your machine’s architecture. Now, you don’t need to know all the details of how Python uses your computer’s memory in order to write effective programs...
What’s important for you as a programmer is to understand that different types have different behaviors.
There are things that you can do with an integer that you can’t do with a string, and vice versa (and that’s a good thing). ----- ###### 3.4 More on string literals Strings as ordered collections of characters As we’ve seen, strings are ordered collections of characters, delimited by quotation marks.
But what kind of characters can be included in a string? Since Python 3.0, strings are composed of Unicode characters.[5] Unicode, formally The Unicode Standard, is an information technology standard for the consistent encoding, representation, and handling of text expressed in most of the world’s writing systems.
The standard, which is maintained by the Unicode Consortium, defines as of the current version (15.0) 149,186 characters covering 161 modern and historic scripts, as well as symbols, thousands of emoji (including in colors), and non-visual control and formatting codes.[6] That’s a lot of characters! We won’t dive deep...
Strings can contain emojis too! ###### Strings containing quotation marks or apostrophes You’ve learned that in Python, we can use either single or double quotation marks to delimit strings. ``` >>> 'Hello World!' 'Hello World!' >>> "Hello World!" 'Hello World!' ``` Both are syntactically valid, and Python d...
This can motivate our choice of delimiters. For example, given the name of a local coffee shop, Speeder and Earl’s, there are two ways we could write this in Python.
One approach would be to escape the apostrophe within a string delimited by single quotes: ``` >>> 'Speeder and Earl\'s' "Speeder and Earl's" ``` Notice what’s going on here.
Since we want an apostrophe within this string, if we use single quotes, we precede the apostrophe with \.
This 5You may have heard of Unicode, or perhaps ASCII (American Standard Code for Information Interchange).
ASCII was an early standard and in Python was superseded in 2008 with the introduction of Python 3. [6https://en.wikipedia.org/wiki/Unicode](https://en.wikipedia.org/wiki/Unicode) ----- is called escaping, and it tells Python that what follows should be interpreted as an apostrophe and not a closing delimiter.
We refer to the string \', as an escape sequence.[7] What would happen if we left that out? ``` >>> 'Speeder and Earl's' Traceback (most recent call last): ... File "<input>", line 1 'Speeder and Earl's' ^ SyntaxError: unterminated string literal (detected at line 1) ``` What’s going o...
Python reads the second single quote as the ending delimiter, so there’s an extra—syntactically invalid—trailing s' at the end. Another approach is to use double quotations as delimiters. ``` >>> "Speeder and Earl's" "Speeder and Earl's" ``` The same applies to double quotes within a string.
Let’s say we wanted to print “Medium coffee, please”, she said. We could escape the double quotes within a string delimited by double quotes: ``` >>> "\"Medium coffee, please\", she said." '"Medium coffee, please", she said.' ``` However, it’s a little tidier in this case to use single quote delimiters. ``` >>...
Now we must use escapes. Either of the following work: 7Escape sequence is a term whose precise origins are unknown.
It’s generally understood to mean that we use these sequences to “escape” from the usual meaning of the symbols used.
In this particular context, it means we don’t treat the apostrophe following the slash as a string delimiter (as it would otherwise be treated), but rather as a literal apostrophe. ----- or ``` >>> '"I\'ll have a Speeder\'s Blend to go", she said.' '"I\'ll have a Speeder\'s Blend to go", she said.' >>> print('"I\'l...
The escape sequences \n and \t are used to insert a newline or tab character into a string, respectively.
The escape sequence \\ is used to insert a single backslash into a string. Escape sequence meaning `\n` newline `\t` tab `\\` backslash `\'` single quote / apostrophe `\"` double quote ###### Python documentation for strings For more, see the Python documentation for strings, including An Infor_mal Introduction to ...