Prof. Andrea Gallegati
One of the most powerful features of a programming language is the ability to manipulate variables.
A variable is a name that refers to a value.
It creates a new variable and gives it a value, e.g.
message = 'And now for something completely different'
n = 17
pi = 3.141592653589793
... generally choose variables names to document what the variable is used for.
The underscore character (can appear), is often used in names with multiple words, e.g. your_name
It is legal to use uppercase letters, but it is conventional to use only lowercase for variables names (in python).
If you give a variable an illegal name, you get a syntax error:
76trombones = 'big parade' #begins with a number
File "<ipython-input-12-58a707cabf44>", line 1 76trombones = 'big parade' # begins with a number ^ SyntaxError: invalid syntax
counter@ = 1000000 #contains an illegal char
File "<ipython-input-11-812170a98a40>", line 1 counter@ = 1000000 ^ SyntaxError: invalid syntax
class = 'Advanced Theoretical Zymurgy' #is a python keyword
File "<ipython-input-15-fc6d141676f8>", line 1 class = 'Advanced Theoretical Zymurgy' #is a python keyword ^ SyntaxError: invalid syntax
The interpreter uses keywords to recognize the structure of the program.
They cannot be used as variable names.
False class finally is return
None continue for lambda try
True def from nonlocal while
and del global not with
as elif if or yield
assert else import pass
break except in raise
... usually displayed in a different color!
... are a combination of values, variables, and operators.
Even a value or a variable all by theirself are considered an expression.
The following are all legal expressions:
42
42
Typing an expression at the prompt, the interpreter evaluates it, finding the value of the expression
n
17
n + 25
42
... are units of code with an effect, like creating a variable or displaying a value.
n = 17 #assignment statement - gives a value to n
print(n) #print statement - displays the value of n
17
When you type a statement, the interpreter executes it, which means that it does whatever the statement says.
In general, statements don’t have values.
Running Python in interactive mode, means that you interact directly with the interpreter.
... a good way to get started, but not working with a few lines of code, it soon becomes clumsy!
Thus, save code in a file (aka script), then run the interpreter in script mode to execute the script.
By convention, Python scripts' names end with .py
%run ../scripts/example.py
17
Again, typing the above command from an actual CLI, you don't need to precede it by a %run
This notebook cells aren't CLIs in the strictest sense of the word.
Since Python provides both modes, it turns useful to test bits of code in interactive mode before putting them into a script.
But there are differences between the two!
... using Python (interactively) as a calculator
miles = 26.2
miles * 1.61
42.182
It turns out that a marathon is about 42 kilometers.
But running the same code into a script, you get no output at all.
In script mode an expression, all by itself, has no visible effect.
Python always evaluates the expression, but without displaying the value unless told:
miles = 26.2
print(miles * 1.61)
42.182
A script usually contains a sequence of statements:
;
and the results appear one at a time as the statements execute.
With more than one operator, the order of evaluation depends on the order of operations.
For mathematical operators, Python follows mathematical convention (PEMDAS).
highest precedence and can be used to force an expression to evaluate in the order you want.
You can also use parentheses to make an expression easier to read, even if it doesn’t change the result.
has the next highest precedence.
higher precedence than Addition and Subtraction.
Operators with the same precedence are evaluated from left to right (except exponentiation).
... use parentheses to make it obvious.
Of course, you can’t perform mathematical operations on strings, even if the strings look like numbers, so the following are illegal:
'2'-'1'
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-30-c01bed84b0cf> in <module>() ----> 1 '2'-'1' TypeError: unsupported operand type(s) for -: 'str' and 'str'
'eggs'/'easy'
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-31-0345b55442cd> in <module>() ----> 1 'eggs'/'easy' TypeError: unsupported operand type(s) for /: 'str' and 'str'
'third'*'a charm'
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-32-6e8a84f5298f> in <module>() ----> 1 'third'*'a charm' TypeError: can't multiply sequence by non-int of type 'str'
But there are two exceptions.
The +
operator performs string concatenation: it joins the strings by linking them end-to-end.
first = 'throat'
second = 'warbler'
first + second
'throatwarbler'
The *
operator performs repetition. If one of the values is a string, the other has to be an integer.
'Spam'*3
'SpamSpamSpam'
These two exceptions make sense by analogy.
On the other hand, there is a significant way in which string concatenation and repetition are different from integer addition and multiplication.
Can you think of a property that addition has that string concatenation does not?
As programs get bigger and more complicated, they get more difficult to read.
Formal languages are dense: it is difficult to say what a piece of code is doing, or why.
Add notes to your programs – to explain in natural language – what the program is doing.
These notes are called comments, and they start with the #
symbol:
a comment may appear on a line by itself
# compute the percentage of the hour that has elapsed
minute = 45
... or you can even put comments at the end of a line
percentage = (minute * 100) / 60 # percentage of an hour
print(str(percentage) + " % ")
75.0 %
Everything from the #
to the end of the line (aka EOL) is ignored – without affecting the execution.
Comments are most useful when they document non-obvious features of the code.
This comment is redundant with the code and useless
v = 5 # assign 5 to v
This comment contains useful information that is not in the code:
v = 5 # velocity in meters/second.
Good variable names can reduce the need for comments, but long names make complex expressions hard to read.
...so there is a trade-off.
Three kinds of errors can occur in a program:
refers to the structure of a program and the rules about that structure, e.g. parentheses have to come in matching pairs.
If there is a syntax error anywhere in your program, Python displays an error message and quits.
... the easiest to track down and you will find them everyday faster.
the error does not appear until after the program has started running.
Also called exceptions to indicate that something exceptional (and bad) has happened.
... it might be a while before you encounter one, but for sure will happen!
related to meaning, e.g. your program will run without generating error messages, but it will not do the "right thing", rather something else: specifically, what you told it to do.
tricky, requiring you to work backward (aka reverse engineering) by looking at the output
It could take your entire life, sometimes, to get to the point!