The lectures (more or less) follow the official Python 3.7 or 3.8 tutorial and the w3schools tutorial is also good (you may try several examples, and may check your knowledge with online tests).
python
is a so called interpreted languageThere are several ways to run a python code.
In Linux:
$ python3
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):
$ python3 hello.py
This runs all the commands in the .py
file, the output (if any) is printed on the console.
In Windows:
C:\Users\YourName> py
or maybe instead of py
you may write python(.exe)
.
C:\Users\YourName> py Desktop\hello.py
IDLE is part of the Python distribution. It has two main window types, the Shell window and the Editor window. It is possible to have multiple editor windows simultaneously. Run it by
$ idle
In Windows you may right click on a .py
file, or search IDLE from start menu.
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 ).
It saves the files with .ipynb
ending (interactive python notebook). Never send your homework in this format!
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.3E4, 2.3e4bool
(boolean): True, Falsestr
(string): "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
function.
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
divisiona // 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 = 14
b = a - 10
a * b
54 > 12
b <= 0
54 > 12 or b <= 0
54 > 12 and b <= 0
s = "puppy"
"up" in s
s = "little " + s
s
[_a-zA-Z]
[_a-zA-Z0-9]
val1
, Val1
and VAL1
are different namestime
, number_of_participants
. Use explanatory names! There 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 equivalent and 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:
'quotation marks are \' and "'
print('quotation marks are \' and "')
In the third type you can use line breaks, in the others you have to use the \n
escape sequence. In Python we use \
for escape sequences: \\\\, \\', \\", \n
(new line), \t
(tab)
print("\home\name")
print(r"\home\name") # raw text, no escape sequences
Inline comments with #
, multiline comments with the """
-strings. Any string which is not assigned to a variable is a comment!
1 + 1 # my first Python command
"""The next code
is really
very simple:"""
1 + 2
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))
"Hi %s! You have %d points." % ("Tom", 100)
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() # new line (if there's 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()) # the input gets always a string
x = float(input())
if x < 0:
print("negative")
elif x == 0:
print("zero")
elif x == 1:
print("one")
else:
print("positive, but not one")
if x >= 10:
print("it has at least two digits")
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 $3n+1$-conjecture:
n = int(input())
while n != 1:
print(n, end=' ') # write the numbers in the same line
if n % 2 == 0:
n = n // 2
else:
n = n * 3 + 1
print(n)
We need to go deeper!
n = int(input())
if n > 0:
while n != 1:
print(n, end=' ')
if n % 2 == 0:
n = n // 2
else:
n = n * 3 + 1
print(n)
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.