The lectures (more or less) follow the official Python 3.7 tutorial and the w3schools tutorial is also good.
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 there.
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 (if any) is printed on the console.
The interpreter is the python
(.exe
) executable program.
Jupyter is a browser based interface for python (and other languages as well).
You can run jupyter from your own computer (if it is installed), but for the labs we will use jupyter.math.bme.hu. This is the same interface as you would start jupyter notebook
from your own machine.
Jupyter itself is a browser-based interface, it runs a Python (or Sage, R or other) interpreter in the background (so called kernel ).
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 elements 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", "öt hűtőházból kértünk színhúst", "ハンガリーからのご挨拶", "هنغاريا", "Венгрия", "헝가리", "הונגריה", "匈牙利", "ฮังการี",... The type can be acquired with the type
command.
type(5.0)
Operations operate on objects, resulting an expression, the result can have 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
result bool
Boolean operations on boolean objects:
a and b
a or b
not a
a != b
(exclusive or, xor)String operations:
a + b
, concatenationa in b
, inclusion (results bool
)5 / 11
2 ** 251
12 ^ 7 # bitwise exclusive or: 1100 ^ 0111 = 1011
a = 54
b = a - 50
a * b
54 > 12
b <= 0
54 > 12 or b <= 0
s = "puppy"
"up" in s
s = "little " + s
s
[_a-zA-Z]
[_a-zA-Z0-9]
val1
and Val1
are different namesThere are tree ways of constructing a string literal.
s = "puppy"
type(s)
s = 'puppy'
type(s)
s = """사랑 means
love
"""
type(s)
s
You can see the "new line" control character denoted by an escape sequence \n
.
The print
command prints it in a readable format.
print(s)
The first two quotion types 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("A 'quotion' mark, " + 'and an other "quotion" mark.')
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 the \n
escape sequence.
Some other escape sequences: \\\\, \\', \\", \n
(new line), \t
(tab)
print("\home\name")
print(r"\home\name") # raw text, no escape sequences
In Jupyter notebooks, the last result is printed after every cell, but if you run a python program you have to use the print()
function. If you want to see more values in one cell, you have to use print()
.
5 + 8
5 + 7
a = 5
print(a)
a = 15
print(a * 2)
a
string = "hon"
"Pyt" + string
print("Once upon a time there was a %s who liked to bark." % "puppy")
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" |
mixed | "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" |
With the option end=
you can determin how to close the string. The default end is \n
.
If you want to continue a line, use end=' '
or end=''
.
Empty print()
begins a new line.
print(1, 3.14, "cat", end=' ') # a space
print("some", end='') # an empty character
print("thing", end=' ') # a space
print() # a new line (if there is no end='...' argument)
print("EOT")
Since we know how to output things, we learn how to read input.
input()
This is an annoyingly polite piece of code:
name = input("Your name, please! ")
print("Hi %s,\nnice to meet you!" % name)
input() > 10
int(input()) > 10 # converts the input strint to integer
type(input())
x = float(input())
if x < 0:
print("negative")
elif x == 0:
print("zero")
elif x == 1:
print("one")
else:
print("too 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 indentation) is executed. If the first condition is not satisfied, then the first elif
which evaluates to True
is executed. If neither of those is True
, then the else
branch is considered (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, end=' ') # results separated by spaces
a = a + 1
print("end")
The while
block is executed as while as the condition is evaluated to True
. One can embed control flows into each other.
Here is a code for the famous Collatz or $3x+1$-conjecture:
a = int(input())
while a != 1:
print(a, end=' ') # write the numbers in the same line
if a % 2 == 0:
a = a // 2
else:
a = a * 3 + 1
print(a)
We need to go deeper!
a = int(input())
if a > 0:
while a != 1:
print(a, end=' ')
if a % 2 == 0:
a = a // 2
else:
a = a * 3 + 1
print(a)
else:
print("Give a positive integer, please!")
The above code checks for positive integer input. Change the code with repeatedly reading the numbers, and stop running if the input is zero. You can use the break
command within loops, which unconditionally and immediately escapes the given block and continues as if the loop would have ended.
while True:
a = int(input())
if a > 0:
while a != 1:
print(a, end=' ')
if a % 2 == 0:
a = a // 2
else:
a = a * 3 + 1
print(a)
elif a == 0:
break
else:
print("Please, enter a nonnegative integer! 0 stops running.")
In case of nested loops, break escapes the innermost loop.