The lectures (more or less) the official Python tutorials.
python
is a so called interpreted languageThere are several ways to run a python code.
For example, interactively:
$ python
This opens a prompt, you can type commands here.
One can run a given set of python commands from a file (a python script, .py
extension):
$ python hello.py
This runs all the commands in the .py
file, the output (is any) is printed on the console.
The interpreted is the python
(.exe
) executable here.
Jupyter is a browser based interface, which is in close resemblance to the Sage notebooks from last semester.
You can start your own web server, on leibniz
:
$ ipython notebook --port=##### --no-browser --ip=127.0.0.1
Where ##### is a port number ranging from 9000 to 20000.
Then you can look your notebooks on the address localhost:##### in your web-browser.
This starts a program which handles the interface in yout browser and this program starts other interpreters (kernels), depending on your usage.
But ipython
is an interpreter itself.
In newer versions ipython notebook
is replaces with jupyter notebook
(it's easier from your own computer).
Jupyter can run multiple kernels, not even with the same programming language, for example Python, Sage and there are several others.
Spyder is an graphical development environment for python, it is installed on leibniz
, but you can install it on your own machine, for any operating system.
This is not an interpreter, rather a graphical insterface to comfortably write and run your code, it has to use and interpreter though.
I advise to use Anaconda. It is available on all of the major desktop OSs (Linux, Mac, Windows)
Anaconda contains command line (python
, ipython
), notebook (jupyter
) and graphical (Spyder
) environments, not to mention a lots of useful libraries, tools and packages.
The objects are the building blocks of the language. Every object has a type. Let's start with the following types:
int
(integer): 2354, -12float
(floating point): 1.0, -23.567, 2.3E4bool
(boolean): True, Falsestr
(string): "puppy", "once upon a time there was a puppy"The type can be acquired with the type
command.
type(5.0)
Operations operate on object, resulting an expression, the result can ha ve a different (but well specified) type.
Integer and float operations:
a + b
additiona - b
subtractiona * b
multiplicationa / b
division (in Python2.7 int/int = int, but from Python3 int/int = float)a // b
integer divisiona % b
remainder, moduloa ** b
power (unlike Sage a ^ b
!)a == b, a < b, a > b, a <= b, a >= b, a != b, a <> b
result bool
Boolean operations on boolean objects:
a and b
a or b
not a
String operations:
a + b
, concatenationa in b
, inclusion (results bool
)5 + 11
2 ** 251
a = 54
b = a - 50
a * b
54 > 12
b < 0
54 > 12 or b < 0
s = "puppy"
"pup" in s
s = "little " + s
s
[_a-zA-Z]
[_a-zA-Z0-9]
val1
and Val1
differThere are tree ways of constructing a string literal.
s = "puppy"
type(s)
s = 'puppy'
type(s)
s = """Once upon a time
there was a puppy.
Elment a vásárba fél pénzzel!
"""
type(s)
s
You can see the control characters (\n
is new line) and UTF-8 byte codes (á=c3a1
, \x
is followed by a hexa code).
The print
command prints it in a readable format.
print s
The first two quotions are for using quotion marks in a string. You can use a quotion mark if it is not the one used to mark string literal. Example:
print "One 'quotion' mark, " + 'two "quotion" marks'
If you want to use the same quotion mark as the string mark, then use escape characters:
'there is this: \' and this: "'
print 'there is this: \' and this: "'
In the third type you can use line breaks, in the others you have to use escape character for newlines (\n
).
Other special (escape) characters: \\\\ (\\), \' ('), \" ("), \n
(new line), \t
(tab)
In Jupyter notebooks, the last result is printed after every cell, but if you run a python program you have to use the print
command. If you want to see more values in one cell, you have to use print
, too.
5 + 8
5 + 7
a = 5
print a
a = 15
print a * 2
a
string = "puppy"
"I had a " + string
print "Once upon a time there was a %s who liked to bark." % string
If a string contains %s
and %
after it, then the latter is substitued in the place of %s
. You can do more substitutions:
print "%s upon a time there was a %s who liked to %s." % ("Once", "puppy", "bark")
You can substitute other types not just strings:
print """The %d is a decimal integer,
the %f is a float number.""" % (23, 1.0/3)
% |
type | example | result |
---|---|---|---|
%s |
string | "Once upon a time there was a %s" % "puppy" |
"Once upon a time there was a puppy" |
%d |
integer | "%d upon a time there was a puppy" % 1 |
"1 upon a time there was a puppy" |
%f |
float | "Once upon a time there were %f puppies" % math.pi |
"Once upon a time there were 3.141593 puppies" |
"There were %d %s and they had to share %f fl.oz. milk" % (3, 'puppies', math.pi) |
"There were 3 puppies and they had to share 3.141593 fl.oz. milk" |
You can print more thing in one line, just use a comma separated list, print
will use a space separator.
If you want to continue a line, end the print
command with a comma.
Empty print
begins a new line.
print 1, 3.14, "puppy"
print "cat",
print "camel",
print
print "EOT"
Since we know how to output things, we learn how to read input.
raw_input()
This is an annoyingly polite piece of code:
a = 5
nev = raw_input("Your name, please! ")
print "Hi %s\nnice to meet you!" % nev
input() > 10
input() ** 10
The difference between raw_input
and input
:
a = raw_input()
a + " cats"
b = input()
b + " cats"
raw_input
always returns a string, input
interprets the input:
type(input())
It is worth mentioning that input
itself is a security risk:
python
>>> intput()
exit()
x = input()
if x < 0:
print "this is negative"
elif x == 0:
print "this is zero"
elif x == 1:
print "this is one"
else:
print "this is many"
You can have more than one elif
branches but neither elif
nor else
is mandatory.
If the first condition is met (expression evaluates to True
) then the first block (marked with an ident) is executed. If not then the first elif
which evaluates to True
. If neither of those, then the else
branch (if there is such a branch).
The ident is mandatory, that marks the block, one ident is usually 4 spaces deep.
n = 1000
a = 1
while a ** 3 <= n:
print a ** 3, # comma continues the line
a = a + 1
print "end"
The while
block is executed as while as the condition is evaluated to True
.
The former example increases the variable a
as long as its cube is not greater than 1000.
One can embed control flows into each other.
The famous Collatz- or $3x+1$-conjecture:
a = input()
while a != 1:
print a, # comma continues the line
if a % 2 == 0:
a = a / 2
else:
a = a * 3 + 1
We need to go deeper!
a = input()
if type(a) == int:
while a != 1:
print a, # comma continues the line
if a % 2 == 0:
a = a / 2
else:
a = a * 3 + 1
else:
print "Integer, please"
The above code checks for integer input. Better to prepare for the worst. What if somebody gives a negative input?
a = input()
if type(a) == int:
if a < 0:
a = -1 * a
while a != 1:
print a, # comma continues the line
if a % 2 == 0:
a = a / 2
else:
a = a * 3 + 1
else:
print "Integer, please"
Finaly, we have to exclude 0, because the conjecture doesn't work for that:
a = input()
if type(a) == int and a != 0:
if a < 0:
a = -1 * a
while a != 1:
print a, # comma continues the line
if a % 2 == 0:
a = a / 2
else:
a = a * 3 + 1
else:
print "Non zero integer, please"
You can use break
within loops, this command unconditionally and immediately escapes the given block and continues as if the loop would have ended.
n = input("Give a whole square under 10000! ")
a = 0
while a ** 2 < 10000:
if a ** 2 == n:
break
a = a + 1
if a ** 2 < 10000:
print "its square root is %d" % a
else:
print "You lied! :("
In case of nested loops, break escapes the innermost loop.