Text
stringlengths
1
9.41k
For example, in our familiar decimal system: [8https://docs.python.org/3/tutorial/introduction.html#strings](https://docs.python.org/3/tutorial/introduction.html#strings) [9https://docs.python.org/3/reference/lexical_analysis.html#literals](https://docs.python.org/3/reference/lexical_analysis.html#literals) ----- n...
For example, in Python, we have distinct types, ``` int and float, for holding integer and floating-point numbers, respec ``` tively. I won’t get into too much detail about how these are represented in binary, but here’s a little bit of information. ###### Integers Representation of integers is relatively straightfor...
Integers are represented as binary numbers with a position set aside for the sign. So, 12345 would be represented as 00110000 00111001.
That’s 0 × 2[15] + 0 × 2[14] + 1 × 2[13] + 1 × 2[12] + 0 × 10[11] + 0 × 10[10] + 0 × 10[9] + 0 × 10[8] + 0 × 10[6] + 1 × 2[5] + 1 × 2[4] + 1 × 2[3] + 0 × 2[2] + 0 × 2[1] + 1 × 2[0] This works out to 8192 + 4096 + 32 + 16 + 8 + 1 = 12345. Negative integers are a little different.
If you’re curious about this, see the Wikipedia article on Two’s Complement. ----- ###### Floating-point numbers and IEEE 754 Floating-point numbers are a little tricky.
Stop and think for a minute: How would you represent floating-point numbers?
(It’s not as straightforward as you might think.) Floating-point numbers are represented using the IEEE 754 standard (IEEE stands for “Institute of Electrical and Electronics Engineers”).[10] There are three parts to this representation: the sign, the exponent, and the fraction (also called the mantissa or significand...
IEEE 754 uses either 32 or 64 bits for representing floating point numbers.
The issue with representation lies in the fact that there’s a fixed number of bits available: one bit for the sign of a number, eight bits for the exponent, and the rest for the fractional portion.
With a finite number of bits, there’s a finite number of values that can be represented without error. ###### Examples of representation error Now we have some idea of how integers and floating-point numbers are represented in a computer.
Consider this: We have some fixed number of bits set aside for these representations.[11] So we have a limited number of bits we can use to represent numbers on a computer.
Do you see the problem? The set of all integers, ℤ, is infinite. The set of all real numbers, ℝ, is infinite. Any computer we can manufacture is finite.
Now do you see the problem? There exist infinitely more integers, and infinitely more real numbers, than we can represent in any system with a fixed number of bits.
Let that soak in. For any given machine or finite representation scheme, there are in_finitely many numbers that cannot be represented in that system!
This_ means that many numbers are represented by an approximation only. Let’s return to the example of 1/3 in our decimal system.
We can never write down enough digits to the right of the decimal point so that we have the exact value of 1/3. 0.333333333333333333333 … No matter how far we extend this expansion, the value will only be an _approximation of 1/3.
However, the fact that its decimal expansion is_ non-terminating is determined by the choice of base (10). What if we were to represent this in base 3? In base 3, decimal 1/3 is 0.1.
In base 3, it’s easy to represent! Of course our computers use binary, and so in that system (base 2) there are some numbers that can be represented accurately, and an infinite number that can only be approximated. Here’s the canonical example, in Python: [10For more, see: https://en.wikipedia.org/wiki/IEEE_754](https...
What? Yup. Something strange is going on. Python rounds values when displaying in the shell.
Here’s proof: ``` >>> print(f'{0.1:.56f}') 0.10000000000000000555111512312578270211815834045410156250 >>> print(f'{0.2:.56f}') 0.20000000000000001110223024625156540423631668090820312500 >>> print(f'{0.1 + 0.2:.56f}') 0.30000000000000004440892098500626161694526672363281250000 ``` The last, 0.1 `+` `0.2, is ...
So there’s no way to accurately represent these numbers in binary with a fixed number of decimal places. ###### What’s the point? 1.
The subset of real numbers that can be accurately represented within a given positional system depends on the base chosen (1/3 cannot be represented without error in the decimal system, but it can be in base 3). 2.
It’s important that we understand that no finite machine can rep_resent all real numbers without error._ 3.
Most numbers that we provide to the computer and which the computer provides to us in the form of answers are only approxi_mations._ 4.
Perhaps most important from a practical standpoint, representa_tion error can accumulate with repeated calculations._ 5.
Understanding representation error can prevent you from chasing bugs when none exist. For more, see: [• Floating Point Arithmetic: Issues and Limitations: https://docs.p](https://docs.python.org/3.10/tutorial/floatingpoint.html) [ython.org/3.10/tutorial/floatingpoint.html.](https://docs.python.org/3.10/tutorial/float...
42 b. True c. "Burlington" d. -17.45 e. "100" f. "3.141592" g. "False" You may check your work in the Python shell, using the built-in function ``` type().
For example, >>> type(777) <class 'int'> ``` This tells us that the type of 777 is int. **Exercise 02** What happens when you enter the following in the Python shell? a. 123.456.789 b.
123_456_789 c. hello d. "hello' e. "Hello" "World!" (this one may surprise you!) f. 1,000 (this one, too, may surprise you!) g. 1,000.234 h. 1,000,000,000 i.
'1,000,000,000' **Exercise 03** The following all result in SyntaxError. Fix them! a. 'Still the question sings like Saturn's rings' b.
"When I asked him what he was doing, he said "That isn't any ``` business of yours."" ``` c. 'I can't hide from you like I hide from myself.' d.
What's up, doc? **Exercise 04 (challenge!)** We’ve seen that representation error occurs for most floating-point decimal values.
Can you find values in the interval [0.0, 1.0) that do not have representation error? Give three or four examples.
What do all these examples have in common? ----- ----- #### Chapter 4 ### Variables, statements, and expressions This chapter will expand our understanding of programming by introducing types and literals.
We’ll also learn about two additional arithmetic operators: floor division using the // operator (also called Euclidean division or integer division), and the modulo operator % (also called the remainder operator).
Please note that the modulo operator has nothing to do with calculating percentages—this is a common confusion for beginners. **Learning objectives** - You will learn how to use the assignment operator and how to create and name variables. - You will learn how to use the addition, subtraction, multiplication, div...
As you can see, this isn’t very flexible—you provided the exact text you wanted to print. However, more often than not, we don’t know the values we want to use in our programs when we write them.
Values may depend on user input, database records, results of calculations, and other sources that we cannot know in advance when we write our programs. Imagine writing a program to calculate the sum of two numbers and print the result.
We could write, ``` print(1 + 1) print(2 + 2) ... ``` but that’s really awkward.
For every sum we want to calculate, we’d have to write another statement. So when we write computer programs we use variables.
In Python, a **variable is the combination of a name and an associated value which** has a specific type.[1] It’s important to note that variables in a computer program are not like variables you’ve learned about in mathematics.
For example, in mathematics we might write 𝑎+𝑏= 5 and, of course, there’s an infinite number of possible pairs of values which sum to five. When writing computer programs, variables are rather different. While the same name can refer to different values at different times, a name can refer to only one value at a time...
The variable name is on the left-hand side of the_ assignment operator, and the expression (which yields a value) is on the right-hand side of the assignment operator. ``` a = 3 # the variable named `a` has the value 3 print(a) # prints 3 to the console a = 17 # now the variable named `a` has the value 17 print...
In many other programming languages, variables refer to memory locations which hold values. (Yes, deep down, this is what goes on “under the hood” but the paradigm from the perspective of those writing programs in Python is that variables are names attached to values.) Feel free to check the entry in the glossary for m...
Assignment statements associate a name with a value (or, in certain cases, can modify a value). Beginners often get confused about the assignment operator.
You may find it helpful to think of it as a left-pointing arrow.[2] When reading your code, for example ``` a = 42 ``` it may help to say, “Let a equal 42”, or “a gets 42”, rather than “a equals 42” (which sounds more like a claim or assertion about the value of a). This can reinforce the concept of assignment.[3] ...
However, Python is a dynamically typed language. This means that any given name can refer to values of different types at different points in a program.
So this is valid Python: ``` a = 42 # now `a` is of type int print(a) # prints 42 to the console a = 'abc' # now `a` is of type str print(a) # prints 'abc' to the console ###### Evaluation and assignment ``` Sometimes we can use a variable in some calculation and reassign the result.
For example: ``` x = 0 print(x) # prints 0 to the console x = x + 1 print(x) # prints 1 to the console x = x + 1 print(x) # prints 2 to the console ``` What’s going on here?
Remember, = is the assignment operator. So in the code snippet above, we’re not making assertions about equivalence; instead, we’re assigning values to x.
With: ``` x = 0 ``` 2In fact, the left-facing arrow is commonly used to indicate assignment in pseu_docode—descriptions of algorithms outside the context of any particular program-_ ming language. 3Later on, we’ll see the comparison operator ==.
This is used to compare two values to see if they are identical. For example, a == b would be true if the values of ``` a and b were the same.
So it’s important to keep the assignment (=) and comparison ``` (==) operators straight in your mind. ----- we’re assigning the literal value 0 to x.
At this point we can say the value of x is 0. Consider what happens here: ``` x = x + 1 ``` So first, Python will evaluate the expression on the right, and then it will assign the result to x.
At the start, the value of x is still zero, so we can think of Python substituting the value of x for the object x on the right hand side. ``` x = 0 + 1 ``` and then evaluating the right-hand side: ``` x = 1 ``` and assigning the result to x.
Now the value of x is 1.
If we do it again, ``` x = x + 1 ``` now the x on the right has the value 1, and 1 + 1 is 2, so the variable x has the value 2. ###### Variables are names associated with values What are variables in Python?
Variables work differently in Python than they do in many other languages.
Again, in Python, a variable is a name associated with a value. Consider this code: ``` >>> x = 1001 >>> y = x ``` What we’ve done here is give two different names to the same value.
This is A-OK in Python. What does x refer to? The value 1001. What does `y refer to?
The exact same 1001.[4]` It is not the case that there are two different locations in memory both holding the value 1001 (as might be the case in a different programming language). Now what happens if we assign a new value to x?
Does y “change”? What do you think? ``` >>> x = 2001 >>> x 2001 >>> y 1001 ``` 4We can verify this by inspecting the identity number of the object(s) in question using Python’s built-in id() function. ----- No.
Even though x now has the new value of 2001, y is unchanged and still has the value of 1001. When we assign a value to a variable, ``` >>> x = 1001 ``` what’s really going on is that we’re associating a name with a value.
In the above example, 1001 is the value, and x is a name we’ve given to it. Values can have more than one name associated with them.
In fact, we can give any number of names to the same value. ``` >>> x = 1001 >>> y = x >>> z = y ``` Now what happens if we assign a new value to x? ``` >>> x = 500 >>> x 500 >>> y 1001 >>> z 1001 y and z are still names for 1001, but now the name x is associated with ``` a new value, 500. While i...
x can’t have two different values at the same time. ``` >>> x = 3 >>> x 3 >>> x = 42 # What happened to 3?
Gone forever. >>> x 42 ``` ----- ###### Comprehension check Given the following snippets of Python code, determine the resulting value x: 1. ``` x = 1 ``` 2. ``` x = 1 x = x + 1 ``` 3. ``` y = 200 x = y ``` 4. ``` x = 0 x = x * 200 ``` 5. ``` x = 1 x = 'hello' ``` 6. ``` x = 5 y = 3 ...
Instead of repeating that same value or calculation over and over again, we can just assign the value to a variable and reuse it throughout a program. We call this constant.
A constant is a variable that has a value that will be left unchanged throughout a program.
Using constants improves the readability of programs because they provide meaningful and recognizable names for fixed values.
Let’s look at an example: ``` HOURS_IN_A_DAY = 24 ``` ----- Here we have assigned the variable HOURS_IN_A_DAY to 24.
This variable is a constant because the number of hours in a day will always be 24 (at least for the foreseeable future).
Now if we need to do some calculation using the number of hours in a day, we can just use this variable. Note that constants are uppercase.
This isn’t enforced by Python, but it’s good common practice. ###### 4.2 Expressions In programming—and computer science in general—an expression is something which can be evaluated—that is, a syntactically valid combination of constants, variables, functions, and operators which yields a _value._ Let’s try out a few...
We typed a simple expression—a single literal— and Python replied with its value.
Literals are special in that they evaluate to themselves! Here’s another: ``` >>> 'Hello, Python!' 'Hello, Python!' ``` Once again, we’ve provided a single literal, and again, Python has replied with its value. You may notice that 'Hello, Python!' is rather different from 1.
You might say these are literals of different types—and you’d be correct! Literals come in different types.
Here are four different literals of four different types. `'Hello, Python'` string (str) `1` integer (int) `3.141592` floating-point (float) `True` Boolean (bool) ``` 'Hello, Python!' is a string literal.
The quotation marks delimit the ``` string. They let Python know that what’s between them is to be interpreted as a string, but they are not part of the string itself.
Python allows single-quoted or double-quoted strings, so "Hello, Python!" and 'Hello, ``` Python!' are both syntactically correct.
Note that if you start with a ``` single quote (’), you must end with a single quote. Likewise, if you start with a double quote (“), you must end with a double quote. ----- ``` 1 is different.
It is an integer literal.
Notice that there are no quotation ``` marks around it. Given all this, the latter two examples work as you’d expect. ``` >>> 3.141592 3.141592 >>> True True ``` What types are these?
3.141592 is a floating point literal (that’s a number that has something to the right of the decimal point). True is what’s called a Boolean literal.
Notice there are no quotation marks around it and the first letter is capitalized.
True and False are the only two Boolean literals. ###### Expressions with arithmetic operators Let’s try some more complex expressions.
In order to construct more complex expressions we’ll use some simple arithmetic operators, specifically some binary infix operators. These should be very familiar.
A binary _operator is one which operates on two operands. The term infix means_ that we put the operator between the operands. ``` >>> 1 + 2 3 ``` Surprised? Probably not.
But let’s consider what just happened anyway. At the prompt, we typed 1 + 2 and Python responded with 3. 1 and ``` 2 are integer literals, and + is the operator for addition.
1 and 2 are the ``` operands, and + is the operator.
This combination 1 + 2 is a syntactically valid Python expression which evaluates to… you guessed it, 3. Some infix arithmetic operators in Python are: `+` addition `-` subtraction `*` multiplication (notice we use * and not x) `/` division `//` integer or “floor” division `%` remainder or “modulo” `**` exponentiation...
Here we’ll present examples of the first four, and we’ll present the others later— floor division, modulo, and exponentiation.
Let’s try a few (I encourage you follow along and try these out in the Python shell as we go). ``` >>> 40 + 2 42 >>> 3 * 5 15 ``` ----- ``` >>> 5 - 1 4 >>> 30 / 3 10.0 ``` Notice that in the last case, when performing division, Python returns a floating-point number and not an integer (Python does s...
So even if we have two integer operands, division yields a floating-point number. What do you think would be the result if we were to add the following? ``` >>> 1 + 1.0 ``` In a case like this, Python performs implicit type conversion, essentially promoting 1 to 1.0 so it can add like types.
Accordingly, the result is: ``` >>> 1 + 1.0 2.0 ``` Python will perform similar type conversions in similar contexts: ``` >>> 2 - 1.0 1.0 >>> 3 * 5.0 15.0 ###### Precedence of operators ``` No doubt you’ve learned about precedence of operations, and Python respects these rules. ``` >>> 40 + 2 * 3 46 ...
We also say multiplication and division bind more strongly than addition and subtraction—this is just a different way of saying the same thing. As you might expect, we can use parentheses to group expressions. We do this to group operations of lower precedence—either in order to perform the desired calculation, or to d...
The portions within the parentheses are evaluated first, and then Python performs the remaining operation. We can construct expressions of arbitrary complexity using these arithmetic operators and parentheses. ``` >>> (1 + 1) * (1 + 1 + 1) - 1 5 ``` Python also has unary operators.
These are operators with a single operand.
For example, we negate a number by prefixing -. ``` >>> -1 -1 >>> -1 + 3 2 >>> 1 + -3 -2 ``` We can also negate expressions within parentheses. ``` >>> -(3 * 5) -15 ``` **Summary of operator precedence** `**` exponentiation `+, -` unary positive or negative (+x, -x) `*, /, //, %` multiplication, and ...
When evaluating expressions, do you think Python proceeds left-toright or right-to-left? Can you think of an experiment you might perform to test your hypothesis?