Text stringlengths 1 9.41k |
|---|
>>> should never appear in your code.[2] Return values and evaluation of expressions are indicated just as they are in the Python shell, without the leading >>>.
```
>>> 1 + 2
3
>>> import math
>>> math.sqrt(36)
6
```
2Except in the case of doctests, which are not presented in this text.
-----
In a few pl... |
For example, when
describing the three-argument syntax for the range() function, we might
write range(<start>, <stop>, <stride>) to indicate that three arguments
must be supplied—the first for the start value, the second for the stop
value, and the last for the stride. |
It’s important to understand that the
angle brackets are not part of the syntax, but are merely a typographic
convention to indicate where an appropriate substitution must be made.
All of these conventions are in accord with the typographical conventions used in the official Python documentation at python.org. |
Hopefully,
this will make it easier for students when they consult the official documentation.
Note that this use of angle brackets is a little different when it comes
to traceback messages printed when exceptions occur. |
There you may
see things like <stdin> and <module>, and in this context, they are not
placeholders requiring substitution by the user.
###### Other conventions
When referring to functions, whether built-in, from some imported module, or otherwise, without any other context or specific problem instance,
we write funct... |
The correct way to specify the entry point of your code in_
Python is with
```
if __name__ == '__main__':
# the rest of your code here
```
This is explained fully in Chapter 9.
In code samples in the book, we do, however, avoid using this if there
_are no function definitions included in the code. |
We do this for space_
and conciseness of the examples. The same could reasonably apply to
your code. |
In most cases, if there are no function definitions in your
module, there’s no need for this if statement (though it’s fine to include
it). |
However, if there are any function definitions in your module, then
```
if __name__ == '__main__': is the correct, Pythonic way to segregate
```
your driver code from your function definitions.
###### Origin of Python
Python has been around a long time, with the first release appearing
in 1991 (four years before Jav... |
It was invented by Guido van Rossum,
who is now officially Python’s benevolent dictator for life (BDFL).
-----
Python gets its name from the British comedy troupe Monty Python’s
_Flying Circus (Guido is a fan)._
Nowadays, Python is one of the most widely used programming languages on the planet and is supported by a... |
See: https://python.org/ for more.](https://python.org/)
###### Python version
As this book is written, the current version of Python is 3.11.4. |
However,
no new language features introduced since version 3.6 are presented in
this book (as most are not appropriate or even useful for beginners).
This book does cover f-strings, which were introduced in version 3.6.
Accordingly, if you have Python version 3.6–3.11, you should be able to
follow along with all code s... |
Accordingly, it’s important that you know how to find and
consult Python’s online documentation.
There are many resources available on the internet and the quality
of these resources varies from truly awful to superb. |
The online Python
documentation falls toward the good end of that spectrum.
**Pros**
- Definitive and up-to-date
- Documentation for different versions clearly specified
- Thorough and accurate
- Includes references for all standard libraries
- Available in multiple languages
- Includes a comprehensiv... |
If you’ve done any programming before, some of this may
seem familiar, but read carefully nonetheless. |
If you haven’t done any
programming before that’s OK.
**Learning objectives**
- You will learn how to interact with the Python interpreter using
the Python shell.
- You will learn the difference between interactive mode (in the shell)
and script mode (writing, saving, and running programs).
- You will learn a... |
Computers can perform all manner of
tasks: communication, computation, managing and manipulating data,
modeling natural phenomena, and creating images, videos, and music,
just to name a few. |
However, computers don’t read minds (yet), and
thus we have to provide instructions to computers so they can perform
these tasks.
Computers don’t speak natural languages (yet)—they only understand binary code. |
Binary code is unreadable by humans.
For example, a portion of an executable program might look like this
(in binary):
```
0110101101101011 1100000000110101 1011110100100100
1010010100100100 0010100100010011 1110100100010101
1110100100010101 0001110110000000 1110000111100000
0000100000000001 0100101101110100 0000001000... |
It’s bad enough to try to read it, and it would be
even worse if we had to write our computer programs in this fashion.
Computers don’t speak human language, and humans don’t speak
computer language. |
That’s a problem. |
The solution is programming lan_guages._
Programming languages allow us, as humans, to write instructions
in a form we can understand and reason about, and then have these
instructions converted into a form that a computer can read and execute.
There is a tremendous variety of programming languages. |
Some languages are low-level, like assembly language, where there’s roughly a
one-to-one correspondence between machine instructions and assembly
language instructions. |
Here’s a “Hello World!” program in assembly language (for ARM64 architecture):[1]
```
.equ STDOUT, 1
.equ SVC_WRITE, 64
.equ SVC_EXIT, 93
.text
.global _start
_start:
stp x29, x30, [sp, -16]!
mov x0, #STDOUT
ldr x1, =msg
mov x2, 13
```
[1Assembly language code sample from Rosetta Code: ... |
Here’s the same program
in C++:
```
#include <iostream>
int main () {
std::cout << "Hello World!" << std::endl;
}
```
Much better, right?
In Python, the same program is even more succinct:
```
print('Hello World!')
```
Notice that as we progress from machine code to Python, we’re increasing abstraction. |
Machine code is the least abstract. These are the actual instructions executed on your computer. |
Assembly code uses humanreadable symbols, but still retains (for the most part) a one-to-one correspondence between assembly instructions and machine instructions. |
In
the case of C++, we’re using a library iostream to provide us with an abstraction of an output stream, std::cout, and we’re just sending strings
to that stream. |
In the case of Python, we simply say “print this string”
(more or less). |
This is the most abstract of these examples—we needn’t
concern ourselves with low-level details.
-----
**Figure 2.1: Increasing abstraction**
Now, you may be wondering: How is it that we can write programs in
such languages when computers only understand zeros and ones? |
There
are programs which convert high-level code into machine code for execution. |
There are two main approaches when dealing with high-level
languages, compilation and interpretation.
###### 2.2 Compilation and interpretation
Generally speaking, compilation is a process whereby source code in some
programming language is converted into binary code for execution on a
particular architecture. |
The program which performs this conversion is
called a compiler. |
The compiler takes source code (in some programming
language) as an input, and yields binary machine code as an output.
**Figure 2.2: Compilation (simplified)**
_Interpreted languages work a little differently. |
Python is an inter-_
preted language. |
In the case of Python, intermediate code is generated,
and then this intermediate code is read and executed by another program.
The intermediate code is called bytecode.
While the difference between compilation and interpretation is not
quite as clear-cut as suggested here, these descriptions will serve for the
present... |
While
you don’t need to understand all the details of this process, it’s helpful
to have a general idea of what’s going on.
Say you have written this program and saved it as hello_world.py.
```
print('Hello World!')
```
You may run this program from the terminal (command prompt), thus:
```
$ python hello_world.py
... |
When
this runs, the following is printed to the console:
```
Hello World!
```
When we run this program, Python first reads the source code, then
produces the intermediate bytecode, then executes each instruction in
the bytecode.
**Figure 2.3: Execution of a Python program**
1. |
By issuing the command python `hello_world.py, we invoke the`
Python interpreter and tell it to read and execute the program
```
hello_world.py (.py is the file extension used for Python files).
```
2. |
The Python interpreter reads the file hello_world.py.
-----
3. The Python interpreter produces an intermediate, bytecode representation of the program in hello_world.py.
4. |
The bytecode is executed by the Python Virtual Machine.
5. |
This results in the words “Hello World!” being printed to the console.
So you see, there’s a lot going on behind the scenes when we run a
Python program.[2] However, this allows us to write programs in a highlevel language that we as humans can understand.
**Supplemental reading**
- Whetting Your Appetite, from Th... |
It’s a great way to get your feet wet._
When working with the Python shell, you can enter expressions and
Python will read them, evaluate them, and print the result. |
(There’s
more you can do, but this is a start.)
There are several ways to run the Python shell: in a terminal (command prompt) by typing python, python3, or py depending on the version(s) of Python installed on your machine. |
You can also run the Python
shell through your chosen IDE (details will vary).
**Figure 2.4: The Python shell in a terminal (above)**
2Actually, there’s quite a bit more going on behind the scenes, but this should
suffice for our purposes. |
If you’re curious and wish to learn more, ask!
[3https://docs.python.org/release/3.10.4/tutorial/appetite.html](https://docs.python.org/release/3.10.4/tutorial/appetite.html)
-----
The first thing you’ll notice is this symbol: >>>. |
This is the Python
prompt (you don’t type this bit, this is Python telling you it’s ready for
new input).
We’ll start with some simple examples (open the shell on your computer and follow along):
```
>>> 1
1
```
Here we’ve entered 1. |
This is interpreted by Python as an integer, and
Python responds by printing the evaluation of what you’ve just typed:
```
1.
```
When we enter numbers like this, we call them “integer literals”—in
the example above, what we entered was literally a 1. |
Literals are special
in that they evaluate to themselves.
Now let’s try a simple expression that’s not a mere literal:
```
>>> 1 + 2
3
```
Python understands arithmetic and when the operands are numbers (integers or floating-point) then + works just like you’d expect. |
So here we
have a simple expression—a syntactically valid sequence of symbols that
evaluates to a value. What does this expression evaluate to? |
3 of course!
We refer to the + operator as a binary infix operator, since it takes
two operands (hence, “binary”) and the operand is placed between the
operands (hence, “infix”).
Here’s another familiar binary infix operator: -. |
You already know
what this does.
```
>>> 17 - 5
12
```
Yup. Just as you’d expect. |
The Python shell evaluates the expression 17
```
- 5 and returns the result: 12.
###### REPL
```
This process—of entering an expression and having Python evaluate it
and display the result—is called REPL which is an acronym for read_evaluate-print loop. |
Many languages have REPLs, and obviously, Python_
does too. REPLs were invented (back in the early 1960s) to provide an
environment for exploratory programming. |
This is facilitated by allowing
the programmer to see the result of each portion of code they enter.
Accordingly, I encourage you to experiment with the Python shell. |
Do
some tinkering and see the results. You can learn a lot by working this
way.
-----
###### Saving your work
Entering expressions into the Python shell does not save anything. |
In
order to save your code, you’ll want to work outside the shell (we’ll see
more on this soon).
###### Exiting the interpreter
If you’re using an IDE there’s no need to exit the shell. |
However, if you’re
using a terminal, and you wish to return to your command prompt, you
may exit the shell with exit().
```
>>> exit()
###### 2.4 Hello, Python!
```
It is customary—a nearly universal ritual, in fact—when learning a new
programming language, to write a program that prints “Hello World!” to
the conso... |
This tradition goes back as at least as far as 1974, when Brian
Kernighan included such a program in his tutorial for the C programming
language at Bell Labs, perhaps earlier.
So, in keeping with this fine tradition, our first program will do the
same—print “Hello World!” to the console.
Python provides us with simple ... |
If we wish to print something to the console, we
write print() and place what we wish to print within the parentheses.
```
print("Hello World!")
```
That’s it!
If we want to run a program in script mode we must write it and save
it. |
Let’s do that.
In your editor or IDE open a new file, and enter this one line of code
(above). Save the file as hello_world.py.
Now you can run your program. |
If you’re using an IDE, you can run
the file within your IDE. |
You can also run the file from the command
line, for example,
```
$ python hello_world.py
```
where $ is the command line prompt (this will vary from system to
system). |
The $ isn’t something you type, it’s just meant to indicate a
command prompt (like >>> in the Python shell). |
When you run this
program it should print:
```
Hello World!
```
-----
###### Next steps
The basic steps above will be similar for each new program you write. |
Of
course, as we progress, programs will become more challenging, and it’s
likely you may need to test a program by running it multiple times as
you make changes before you get it right. |
That’s to be expected. |
But now
you’ve learned the basic steps to create a new file, write some Python
code, and run your program.
###### 2.5 Syntax and semantics
In this text we’ll talk about syntax and semantics, so it’s important that
we understand what these terms mean, particularly in the context of
computer programming.
###### Syntax... |
For example, in English,
My hovercraft is full of eels.
is a syntactically valid sentence.[4] While it may or may not be true, and
may not even make sense, it is certainly a well-formed English sentence.
By contrast, the sequence of words
Is by is is and cheese for
is not a well-formed English sentence. |
These are examples of valid and
invalid syntax. |
The first is syntactically valid (well-formed); the second
is not.
Every programming language has rules of syntax—rules which govern
what is and is not a valid statement or expression in the language. |
For
example, in Python
```
>>> 2 3
```
is not syntactically valid. |
If we were to try this using the Python shell,
the Python interpreter would complain.
4“My hovercraft is full of eels” originates in a famous sketch by Monty Python’s
Flying Circus.
-----
```
>>> 2 3
File "<stdin>", line 1
2 3
^^^
SyntaxError: invalid syntax. |
Perhaps you forgot a comma?
```
That’s a clear-cut example of a syntax error in Python. |
Here’s another:
```
>>> = 5
File "<stdin>", line 1
= 5
^
SyntaxError: invalid syntax
```
Python makes it clear when we have syntax errors in our code. |
Usually
it can point to the exact position within a line where such an error occurs.
Sometimes, it can even provide suggestions, for example, “Perhaps you
forgot a comma?”
###### Semantics
On the other hand, semantics is about meaning. |
In English we may say
The ball is red.
We know there’s some object being referred to—a ball—and that an
assertion is being made about the color of the ball—red. |
This is fairly
straightforward.
Of course, it’s possible to construct ambiguous sentences in English.
For example (with apologies to any vegetarians who may be reading):
The turkey is ready to eat.
Does this mean that someone has cooked a turkey and that it is ready to
be eaten? |
Or does this mean that there’s a hungry turkey who is ready
to be fed? This kind of ambiguity is quite common in natural languages.
Not so with programming languages. |
If we’ve produced a syntactically
valid statement or expression, it has only one “interpretation.” There is
no ambiguity in programming.
Here’s another famous example, devised by the linguist Noam Chomsky:[5]
Colorless green ideas sleep furiously.
This is a perfectly valid English sentence with respect to syntax. |
However, it is meaningless, nonsensical. How can anything be colorless and
green at the same time? How can something abstract like an idea have
color? What does it mean to “sleep furiously”? |
Syntax: A-OK. |
Semantics:
nonsense.
[5https://en.wikipedia.org/wiki/Noam_Chomsky](https://en.wikipedia.org/wiki/Noam_Chomsky)
-----
Again, in programming, every syntactically valid statement or expression has a meaning. |
It is our job as programmers to write code which is
syntactically valid but also semantically correct.
What happens if we write something which is syntactically valid and
also semantically incorrect? |
It means that we’ve written code that does
_not do what we intend for it to do. There’s a word for that: a bug._
Here’s an example. |
Let’s say we know the temperature in degrees
Fahrenheit, but we want to know the equivalent in degrees Celsius. |
You
may know the formula
𝐶= [𝐹−32]
1.8
where F is degrees Fahrenheit and C is degrees Celsius.
Let’s say we wrote this Python code.
```
f = 68.0 # 68 degrees Fahrenheit
c = (f - 32) * 1.8 # attempt conversion to Celsius
print(c) # print the result
```
This prints 64.8 which is incorrect! |
What’s wrong? We’re multiplying by
1.8 when we should be dividing by 1.8! This is a problem of semantics.
Our code is syntactically valid. |
Python interprets it, runs it, and produces
a result—but the result is wrong. Our code does not do what we intend
for it to do. |
Call it what you will—a defect, an error, a bug—but it’s a
semantic error, not a syntactic error.
To fix it, we must change the semantics—the meaning—of our code.
In this case the fix is simple.
```
f = 68.0 # 68 degrees Fahrenheit
c = (f - 32) / 1.8 # correct conversion to Celsius
print(c) # print the result
``... |
Now our program has the
semantics we intend for it.
###### 2.6 Introduction to binary numbers
You may know that computers use binary code to represent, well … ev_erything. |
Everything stored on your computer’s disk or solid-state drive_
is stored in binary form, a sequence of zeros and ones. All the programs
your computer runs are sequences of zeros and ones. |
All the photos you
save, all the music you listen to, even your word processing documents
are all zeros and ones. Colors are represented with binary numbers. |
Audio waveforms are represented with binary numbers. Characters in your
word processing document are represented with binary numbers. |
All the
instructions executed and data processed by your computer are represented in binary form.
-----
**Figure 2.5**
Accordingly, as computer scientists, we need to understand how we represent numbers in binary form and how we can perform arithmetic operations on such numbers.
However, first, let’s review the fam... |
In the decimal system, we represent
6In fact, the first positional numeral system, developed in ancient Babylonia
around 2000 BCE, used 60 as a base. |
Our base 10 system is an extension of the
Hindu-Arabic numeral system. Other cultures have used other bases. |
For example,
-----
numbers as coefficients in a sequence of powers of ten, where each coefficient appears in a position which corresponds to a certain power of ten.
(That’s a mouthful, I know.) This is best explained with an example.
Take the (decimal) number 8,675,309. |
Each digit is a coefficient in the
sequence
8 × 10[6] + 6 × 10[5] + 7 × 10[4] + 5 × 10[3] + 3 × 10[2] + 0 × 10[1] + 9 × 10[0]
Recall that anything to the zero power is one—so, 10[0] = 1. |
If we do the
arithmetic we get the correct result:
8 × 10[6] = 8,000,000
6 × 10[5] = 0,600,000
7 × 10[4] = 0,070,000
5 × 10[3] = 0,005,000
3 × 10[2] = 0,000,300
0 × 10[1] = 0,000,000
9 × 10[0] = 0,000,009
and all that adds up to 8,675,309.
This demonstrates the power and conciseness of a positional numeral
syst... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.