Prof. Dario Abbondanza
Python, in a few words ...
print('\n Hi guys! ¯\_(ツ)_/¯ \n') # this is a comment, on the left there is a function
Hi guys! ¯\_(ツ)_/¯
Python's developers aim for it to be fun to use. Its name was a tribute to the British comedy group "Monty Python."
... is a sequence of instructions that specifies how to perform a computation. The computation might be:
import re
with open("doc/document.txt", "r") as file:
text = file.read()
print("\n" + text + "\n")
replacements = {
"President": "Supreme Leader",
"United States": "The Banana Republic",
"Donald Trump": "Barack Obama",
"Congress": "The Honorable Council of Elders",
"Senate": "The High Council of Wise Ones",
"House of Representatives": "The Assembly of the People",
"economy": "banana economy",
"Wall Street": "Banana Street",
"taxes": "banana tariffs",
"stock market": "banana market"
}
The President of the United States, Donald Trump, has been meeting with Congress and Senate to discuss plans for the economy. Wall Street and taxes are among the main topics of discussion.
for old, new in replacements.items():
text = re.sub(old, new, text)
with open("doc/funny_document.txt", "w") as file:
file.write(text)
print("\n ... and the replacement is complete! \n")
print("\n" + text + "\n")
... and the replacement is complete! The Supreme Leader of the The Banana Republic, Barack Obama, has been meeting with The Honorable Council of Elders and The High Council of Wise Ones to discuss plans for the banana economy. Banana Street and banana tariffs are among the main topics of discussion.
... is a sequence of instructions that specifies how to perform a computation. The computation might be:
from PIL import Image
from IPython.display import display
with Image.open("img/lgbt-logo.jpg") as im:
display(im.convert("L")) # opts: L, 1, RGB, "P", palette=Image.ADAPTIVE, colors=256
... is a sequence of instructions that specifies how to perform a computation. The computation might be:
from PIL import Image, ImageSequence
from IPython.display import display
im = Image.open("img/monty-python.gif")
frames = [frame.copy() for frame in ImageSequence.Iterator(im)]
frames.reverse()
frames[0].save('img/reverse-monty-python.gif', save_all=True,
append_images=frames[1:], loop=0)
Get data from the keyboard, a file, the network, or some other device.
Display data on the screen, save it in a file, send it over the network, etc.
Perform basic mathematical operations like addition and multiplication.
Check for certain conditions and run the appropriate code.
Perform some action repeatedly, usually with some variation.
Every program you’ve ever used, no matter how complicated, is made up of instructions that look pretty much like these.
So you can think of programming as the process of breaking a large, complex task into smaller and smaller subtasks until the subtasks are simple enough to be performed with one of these basic instructions.
Why this book?
According to the Preface, the Author decided to:
This is the goal of this class.
This way of thinking combines some of the best features of mathematics, engineering, and natural science.
The single most important skill for a computer scientist is problem solving.
The ability to formulate problems, think creatively about solutions, and express a solution clearly and accurately.
We will use programming as a means to that end!
One of the challenges of getting started with Python is that you might have to install Python and related software on your computer.
If you are familiar with your operating system
and especially
If you are comfortable with the command-line interface (CLI)
You will have no trouble installing Python.
Otherwise, it can be cumbersome to learn, at the same time, about:
Our recommendation is start out running Python in a **browser**.
... to install it later, *locally*, when comfortable with Python.
There are a number of web pages to run Python (e.g. PythonAnywhere).
During this class, we will rely on these two different solutions:
Detailed instructions will follow, as needed.
editing & running Colab notebooks (like this one!)
One-click-install application to build & share containerized applications and microservices, reducing the time spent on complex setups, just to focus on writing code.
There are two versions of Python. They are very similar.
python2
python3
This class (as well as the book) is designed for python3
, but there might be some
notes about python2
, on a few differences you might encounter as a beginner.
Right now, for you, it is just a matter of different interpreters ...
is a program that reads and executes Python code.
Depending on your environment, you might start the interpreter
python
on a command line (CLI). When it starts, you might see some output like: the information about the interpreter and the operating system it’s running on, so it might be different for you!
Then, there's the prompt, a line usually starting with
>>>
Then, there's the prompt, a line usually starting with
>>>
it indicates that the interpreter is ready for you to enter code.
If you type a line of code and hit Enter, the interpreter displays the result:
>>> 1 + 1
2
1 + 5
6
Now we’re ready to get started.
From here on, let's assume we know at least a way to run and test our code: from within this notebook cells embedded Python interpreter.
Check that the version number is the right one.
To do so, just type at the prompt (just anoher CLI) this command
!python --version
Python 3.4.5 :: Continuum Analytics, Inc.
since it begins with 3 it's the right version.
... typing the above command from an actual CLI, you don't need to precede it by a !
This notebook cells aren't CLIs in the strictest sense of the word.
Traditionally, the first program you write in a new language is called “Hello, World!”
print("Hello, World!")
Hello, World!
All it does is to say hello to the World!
This is an example of a print statement, i.e. it displays a result on the screen.
Quotation marks "text"
mark the beginning and end of
text to be displayed (aka strings).
The parentheses indicate that print is a function.
print('Hello, World!')
Hello, World!
In python2
, the print statement is slightly different; it is not a function, so it
doesn’t use parentheses.
>>> print 'Hello, World!'
Single quotes and double quotes do the same thing.
Most people use single quotes, except in cases like this where a single quote (e.g. an apostrophe) appears in the string.
print("I worked all the night so I'll sleep all day.")
I worked all the night so I'll sleep all day.
... next step is arithmetic. Python provides operators:
special symbols that represent computations like addition and multiplication!
The operators +
, -
, and *
perform addition,
subtraction, and multiplication, as in the following examples:
40 + 2
42
43 - 1
42
6 * 7
42
The operator /
performs division:
84 / 2
42.0
... why the result is 42.0
instead of 42
. It's a matter of
types.
Let's wait for a while!
Finally, the operator **
performs exponentiation, i.e. it raises a
number to a power:
6**2 + 6
42
In some other languages, ^
is used for exponentiation.
In Python this is a bitwise operator called XOR ... the result will surprise you:
6 ^ 2
4
We won’t cover them, but read more about this on: http://wiki.python.org/moin/BitwiseOperators
... bitwise operators have lot of applications in cryptography, as well as XOR in particular!
# Test
key = 5
message = "This is a secret message for you. Don't tell anybody !!!"
def encrypt(message, key):
return ''.join(chr(ord(c) ^ key) for c in message)
def decrypt(ciphertext, key):
return ''.join(chr(ord(c) ^ key) for c in ciphertext)
ciphertext = encrypt(message, key); print("Encrypted message:", ciphertext)
plaintext = decrypt(ciphertext, key); print("Decrypted message:", plaintext)
Encrypted message: Qmlv%lv%d%v`fw`q%h`vvdb`%cjw%|jp+%Ajk"q%q`ii%dk|gja|%$$$ Decrypted message: This is a secret message for you. Don't tell anybody !!!
In this example, the encrypt
function takes a message
and a key
as input, and returns the
XOR of each character in the message with the key.
The decrypt
function takes the ciphertext
and the
key
as input and returns the original message by
doing the same operation again.
The key
could even be a string, with a slightly more articulated
script:
key = "Fidelius"
def encrypt(message, key):
key_len = len(key); key_index = 0
encrypted_message = ""
for c in message:
encrypted_message += chr(ord(c) ^ ord(key[key_index]))
key_index = (key_index + 1) % key_len
return encrypted_message
def decrypt(ciphertext, key):
key_len = len(key); key_index = 0
decrypted_message = ""
for c in ciphertext:
decrypted_message += chr(ord(c) ^ ord(key[key_index]))
key_index = (key_index + 1) % key_len
return decrypted_message
ciphertext = encrypt(message, key); print("Encrypted message:", ciphertext)
plaintext = decrypt(ciphertext, key); print("Decrypted message:", plaintext)
L S'I ffLhI NS2 L $ LHTR Decrypted message: This is a secret message for you. Don't tell anybody !!!
A value is one of the basic things a program works with (like a letter or a number).
Some values we have seen so far are 2
, 42.0
, and
'Hello, World!'
These values belong to different types:
2
is an integer42.0
is a floating-point number'Hello, World!'
is a string, because the letters (i.e.
char in other languages) it contains are strung together.
... the interpreter can tell you:
type(2)
int
type(42.0)
float
type('Hello, World!')
str
What about values like '2'
and '42.0'
?
They look like numbers, but they are in quotation marks like strings
:
type('2')
str
type('42.0')
str
Do not use commas between groups of digits, when typing a large integer (as in
1,000,000
)
1,000,000
(1, 0, 0)
That’s not what we expected at all!
Python interprets 1,000,000
as a comma-separated sequence of
integers we will learn more about.
Again, let's wait for a while!
These are Beautiful definitions taken from your book:
Natural languages are the languages people speak, i.e. English, Spanish, and French. They were not designed by people (although people try to impose some order on them); they evolved naturally.
Formal languages are languages that are designed by people for specific applications, i.e. mathematical notation is particularly good at denoting relationships among numbers and symbols. Chemists use a formal language to represent the chemical structure of molecules. And most importantly:
Programming languages are formal languages that have been designed to express computations.
Formal languages tend to have strict syntax rules that govern the structure of statements, i.e. in mathematics the statement
3 + 3 = 6
has correct syntax, but
3 + = 3 $6
does not!
Syntax rules come in two flavors, pertaining to tokens and structure. Tokens are the basic elements of the language, such as words, numbers, and chemical elements.
In the above example $ is not a legal token, in mathematics.
The second type of syntax rule pertains to the way tokens are combined. The above equation is illegal because although + and = are legal tokens, you can’t have one right after the other!
This is @ well-structured Engli$h sentence with invalid t*kens in it.
This sentence has all valid tokens, but an invalid structure as well.
When you read a sentence in English or a statement in a formal language, you have to figure out the structure (although in a natural language you do this subconsciously).
This process is called parsing.
Formal and natural languages have many features in common – tokens, structure, and syntax – there are some differences ...
Natural languages are full of ambiguity, which people deal with by using contextual clues and other information.
Formal languages are designed to be nearly or completely unambiguous, which means that any statement has exactly one meaning, regardless of context.
As a result, they are often verbose. Formal languages are less redundant and more concise.
In order to make up for ambiguity and reduce misunderstandings, natural languages employ lots of redundancy.
Formal languages, simply mean exactly what they say.
Natural languages are full of idiom and metaphor ...
Because we all grow up speaking natural languages, it is sometimes hard to adjust to formal languages.
The difference between formal and natural language is like the difference between poetry and prose
Words are used for their sounds as well as for their meaning, and the whole poem together creates an effect or emotional response. Ambiguity is not only common but often deliberate.
The literal meaning of words is more important, and the structure contributes more meaning. Prose is more amenable to analysis than poetry but still often ambiguous.
The meaning of a computer program is unambiguous and literal, and can be understood entirely by analysis of the tokens and structure.
Formal languages are more dense than natural languages, so it takes longer to read them.
The structure is important, so it is not always best to read from top to bottom, left to right.
Learn to parse the program in your head identifying the tokens and interpreting the structure.
Details matter: small errors in spelling and punctuation, can make a big difference in a formal language.
Programmers make mistakes.
Programming errors are called bugs and the process of tracking them down is called debugging.
Programming, and especially debugging, sometimes brings out strong emotions.
If you are struggling with a difficult bug, you might feel angry, despondent, or embarrassed.
Think of the computer as an employee with certain strengths, like speed and precision, and particular weaknesses, like lack of empathy and inability to grasp the big picture. Your job is to be a good manager.
Use your emotions to engage with the problem, without letting your reactions interfere with your ability to work effectively.
Learning to debug can be frustrating, but it is a valuable skill that is useful for many activities beyond programming.