Python 3: new minor version (e.g. 3.9) released every October
Python 2: support ended in 2019, 10% of developers were still using it by then
# this is a comment
a = 3
b = 4
print(a * b)
if a * b > 10:
print('greater')
Download from https://python.org
during installation, check the option "Add Python 3.x to PATH"
verify the installation:
python --version
should display the version number
pip install requests
should successfully download and install a small Python package named requests
installation includes:
options for running Python code:
options:
launching the Python console / shell:
python
in the command promptquitting:
exit()
simple:
Jupyter notebooks:
birth_year = 1970
current_year = 2020
age = current_year - birth_year
Names of variables are usually written in lower case, separating words by underscores
Variable names may only consist of letters, digits and underscores
Overwriting (reassigning) variables:
name = "John"
name = "Jane"
a = 3
a = a + 1
int
(integer)float
(floating point number)str
(string): textbool
(boolean): yes / noexample:
(7 - 3) * 0.5 / 3.5
A string represents text
Strings can be enclosed in single or double quotes
greeting = "Hello"
name = 'John'
name = "John"
Inserting a variable (f-strings):
message1 = f"Hello, {name}!"
Joining strings:
message2 = "Hello, " + name + "!"
Problem: how do we include characters like "
in a string?
this is invalid:
text = "He said: "hi!""
solution:
text = "He said: \"hi!\""
Python treats the sequence \"
like a single "
Line break: \n
a = 'line 1\nline 2'
single Backslash: \\
b = 'C:\\docs'
boolean value: yes/no
In Python: True
or False
note the capitalization
None represents a value that is unknown or missing
first_name = "John"
middle_name = None
last_name = "Doe"
Determining the type of a variable via type
:
a = 4 / 2
type(a)
Objects may be converted to other types via int()
, float()
, str()
, bool()
, ...
pi = 3.1415
pi_int = int(pi)
message = "Pi is approximately " + str(pi_int)
A function is a "sub-program" that can perform a specific task
examples of predefined functions:
len()
can determine the length of a string (or of a list, ...)id()
can determine the internal ID of an objecttype()
can tell us the type of an objectprint()
can write some output into the terminalA function can receive so-called parameters and produce a result (a return value)
example: len()
can take a string as a parameter and produce an int as the return value
example: print()
can take various objects as parameters; it does not have an explicit return value
A method is a function that belongs to a specific object type (e.g. to str)
examples of string methods:
first_name.upper()
first_name.count("a")
first_name.replace("a", "@")
Dicts (dictionaries) are mappings that contain "named" entries with associated values.
person = {
"first_name": "John",
"last_name": "Doe",
"nationality": "Canada",
"birth_year": 1980
}
Retrieving and setting elements:
person["first_name"]
person["first_name"] = "Jane"
exercise:
create and modify dictionaries that represent various objects, e.g.:
A list represents a sequence of objects
primes = [2, 3, 5, 7, 11]
users = ["Alice", "Bob", "Charlie"]
products = [
{"name": "IPhone 12", "price": 949},
{"name": "Fairphone", "price": 419},
{"name": "Pixel 5", "price": 799}
]
Retrieving list elements via their index (starting at 0):
users = ["Alice", "Bob", "Charlie"]
users[0]
users[1]
users[-1] # last element
Overwriting a list element
users[0] = "Andrew"
Appending an element
users.append("Dora")
Removing the last element:
users.pop()
Removing by index:
users.pop(0)
Determining the length
len(users)
exercise:
create and modify data consisting of dicts and lists that represents various objects, e.g.:
date = (1973, 10, 23)
Area of application: similar to dicts:
point_dict = {"x": 2, "y": 4}
point_tuple = (2, 4)
date_dict = {
"year": 1973,
"month": 10,
"day": 23
}
date_tuple = (1973, 10, 23)
Each entry in a tuple has a specific meaning
Behavior: similar to lists:
date_tuple[0] # 1973
len(date_tuple) # 3
Unlike lists, tuples are immutable (no .append
/ .pop
/ ...)
create and modify data structures that include dicts, lists and tuples
What will be the value of a
after this code has run?
a = [1, 2, 3]
b = a
b.append(4)
An assignment (e.g. b = a
) assigns a new (additional) name to an object.
The object in the background is the same.
If the original should remain intact it may be copied or a derived version can be newly created based on it:
a = [1, 2, 3]
# creating a new copy
b = a.copy()
# modifying b
b.append(4)
a = [1, 2, 3]
# creating a new object b based on a
b = a + [4]
Some objects can be mutated (changed) directly - e.g. via .append()
, .pop()
, ...
Examples: list
, dict
Many simple objects are immutable after they have been created. However, they can be replaced by other objects.
Examples: int
, float
, str
, bool
, tuple
resources:
Interactive help on objects in the Python console:
help(list)
(navigate through long outputs via Space and Enter, exit via Q)
Documentation on built-ins and the standard library:
https://docs.python.org/3/library/index.html (Google: "python library")
Similar to the help
function, but often has slightly more detailed descriptions
helpful website with answers for many common questions: StackOverflow
other free resources:
example code that creates an error message:
open("foo.txt")
error message:
Traceback (most recent call last):
File "xyz.py", line 1, in <module>
open("foo.txt")
FileNotFoundError: [Errno 2] No such file or directory: 'foo.txt'
Last line: description of the error
above: where the error came from
example code with a chain of function calls:
import shutil
def demo_remove_dir_error():
shutil.rmtree("./does_not_exist")
demo_remove_dir_error()
error message involving a chain of function calls:
Traceback (most recent call last):
File "...\demo_remove_dir_error.py", line 5, in <module>
demo_remove_dir_error()
File "...\demo_remove_dir_error.py", line 3, in demo_remove_dir_error
shutil.rmtree("./does_not_exist")
File "...\lib\shutil.py", line 748, in rmtree
return _rmtree_unsafe(path, onerror)
File "...\lib\shutil.py", line 607, in _rmtree_unsafe
onerror(os.scandir, path, sys.exc_info())
File "...\lib\shutil.py", line 604, in _rmtree_unsafe
with os.scandir(path) as scandir_it:
FileNotFoundError: [WinError 3] The system cannot find the
path specified: './does_not_exist'
popular development environments for Python:
Basic functionality:
functionality:
installation:
registering your Python installation with VS Code:
via File - Preferences - Settings
possible settings:
command palette: via F1 or Ctrl + Shift + P
example commands (some are only available for specific file types):
Debug - Start Without Debugging (Ctrl + F5) (will run program in the project directory)
or
green "Play" button in the editor view (will run program in the current working directory)
in the interactive console / notebook:
if the last command in a cell produces a value, it will be automatically written ("printed") as the output
general way to create text output from anywhere: print()
print("Hello, world!")
We'll create a file called greeting.py
Our program will ask the user their name and greet them.
Input: via input()
:
print("What is your name?")
name = input()
input
will always return a string
writing the greeting
print("Nice to meet you, " + name)
Comments are a useful tool for developers to describe what the code is doing. They don't influence the program itself.
A comment starts with a #
and extends to the line end.
Usually comments are placed above the code they describe
# determine the length of the name
name_length = len(name)
on the command line via python greeting.py
in VS Code (Python extension must be installed):
green play button in the editor view
or
Run - Run Without Debugging (Ctrl + F5)
Write a program called age.py
which will ask the user for their birth year and will respond with the user's age in the year 2022.
Write a program which asks the user for their name. It should respond with the number of letters in the user's name.
For this purpose use the function len(...)
to determine the length of a string.
documentation: https://docs.python.org/3/library/index.html
amongst others:
print()
input()
len()
max()
min()
open()
range()
round()
sorted()
sum()
type()
The standard library contains additional modules that can be imported.
example:
import math
print(math.floor(3.6))
or
from math import floor
print(floor(3.6))
modules of interest:
pprint
(pretty printing)random
math
datetime
os
(operating system, file system)urllib.request
(HTTP queries)webbrowser
(simple web-browser controller)Printing multiple elements:
print(1, 2, 3, sep=", ", end="\n\n")
1, 2, 3
import pprint
pprint.pprint(['Mercuy', 'Venus', 'Earth', 'Mars', 'Jupiter',
'Saturn', 'Uranus', 'Neptune', 'Pluto'])
['Mercuy',
'Venus',
'Earth',
'Mars',
'Jupiter',
'Saturn',
'Uranus',
'Neptune',
'Pluto']
opening a text file for writing:
file = open("message.txt", "w", encoding="utf-8")
file.write("hello\n")
file.write("world\n")
file.close()
file does not have to exist beforehand
Querying web contents (and saving to a file)
import urllib.request
# make a HTTP request
req = urllib.request.urlopen("https://en.wikipedia.org")
# read content as utf-8 string
content = req.read().decode("utf-8")
# save to file
file = open("wikipedia.html", mode="w", encoding="utf-8")
file.write(content)
file.close()
import random
print(random.randint(1, 6))
print(random.choice(["heads", "tails"]))
By using control structures we can execute some code repeatedly or only under certain circumstances.
most important control structures in programming languages:
if ... else ...
while
for ... in ...
for ... in range(...)
In order to use if
and while
we have to compare values:
a = 2
b = 5
print(a == b) # a is equal to b
print(a != b) # a not equal to b
print(a < b) # a is smaller than b
print(a > b)
print(a <= b) # a is smaller than or equal to b
print(a >= b)
The result of a comparison is a boolean value (True
/ False
)
We can store the result in a variable:
is_adult = age >= 18
Examples:
if age >= 18 and country == "de":
print("may drink alcohol")
if temperature < -10 or temperature > 30:
print("extreme weather")
if not value > 10:
print("value not greater than 10")
example:
age = 30
age_seconds = age * 365 * 24 * 60 * 60
if age_seconds < 1000000000:
print("You are less than 1 billion seconds old")
else:
print("You are older than 1 billion seconds")
if age_seconds < 100000000:
print("You are less than 100 million seconds old")
elif age_seconds < 1000000000:
print("You are less than 1 billion seconds old")
elif age_seconds < 2000000000:
print("You are less than 2 billion seconds old")
else:
print("You are older than 2 billion seconds")
code block = a group of lines that belong together - for example the code that gets executed when an if condition is true
In Python the line before the code block ends with a :
and the code block is indented (usually by 4 spaces)
Simulate a random coin flip via random.choice(["heads", "tails"])
Let the user guess the outcome and tell them if they were right
With for loops we can iterate over the contents of lists (and similar objects).
In some other programming languages this construct would be called for-each
names = ["Alice", "Bob", "Charlie"]
for name in names:
print("Hello, " + name + "!")
start with a list of numbers, e.g. [2, 5, -3, 8, 1, -5]
print all positive entries, e.g. 2, 5, 8, 1
print the biggest element, e.g. 8
This is how we can count from 0 to 9 in Python:
for i in range(10):
print(i)
The function call range(10)
creates an object that behaves like the list [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
.
typical variable name in counting loops: i
exercise: create a "multiplication table"
1 x 7 = 7
2 x 7 = 14
3 x 7 = 21
4 x 7 = 28
...
An if clause will execute a code block once if a criterion holds
A while clause will execute a code blok as long as a criterion holds
example:
a = 1
while a < 2000:
print(a)
a = a * 2
exercises:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Exercise: shopping list
Example interaction:
enter an item or "x" to quit:
milk
enter an item or "x" to quit:
bread
enter an item or "x" to quit:
apples
enter an item or "x" to quit:
x
your shopping list is:
["milk", "bread", "apples"]
keyword break
: may be used to end the current loop
example (do-while-loop):
a = 1
while True:
a = a * 2
print(a)
if (a > 1000):
break
empty code block via the pass
statement:
# TODO: warn the user if path doesn't exist
if not os.path.exists(my_path):
pass
a statement can span across multiple lines if we use parantheses:
a = (2 + 3 + 4 + 5 + 6 +
7 + 8 + 9 + 10)
Alternative: escaping newlines with \
a = 2 + 3 + 4 + 5 + 6 + \
7 + 8 + 9 + 10
expression = something that produces a value (the value might be None
)
expression = anything that can be on the right-hand side of an assignment (=
)
examples of expressions:
(7 - 3) * 0.5
(7 - 3)
7
round(3.5)
x == 1
see https://github.com/marko-knoebl/slides/tree/master/exercises/python-beginner
Calling open
:
with positional parameters:
f = open("myfile.txt", "w", -1, "utf-8")
with keyword parameters:
f = open("myfile.txt", encoding="utf-8", mode="w")
We can look up names of keyword parameters in the documentation (e.g. via help(open)
)
Some parameters of functions can be optional (they have a default value)
Example: For open
only the first parameter is required, the others are optional
The values of default parameters can be looked up in the documentation
example:
def average(a, b):
m = (a + b) / 2
return m
This is how we define default values for parameters:
def shout(phrase, end="!"):
print(phrase.upper() + end)
shout("hello") # HELLO!
shout("hi", ".") # HI.
A function definition creates a new scope, an area where variables are valid
In the following example there are two distinct variables named m
:
m = "Hello, world"
def average(a, b):
m = (a + b) / 2
return m
x = average(1, 2)
print(m) # prints "Hello, world"
Inside a function, outer variables may be read but not overwritten
In other programming languages constructs like if
or for
usually also open a new scope - this is not the case in Python
True
or False
For bar codes / primes: look up the % operator
see https://github.com/marko-knoebl/slides/tree/master/exercises/python-beginner
(packages are actually a special type of modules)
urllib
= packageurllib.request
= moduleurllib.request.urlopen
= functionsys
= modulesys.path
= objectTypical imports:
import module1
from package2 import module2a, module2b
from module3 import object3a, object3b
from package4.module4 import object4a, object4b
Specific examples:
import os
from urllib import request, response
from math import sqrt, pi
from http.client import HTTPConnection, HTTPSConnection
Typically used in an interactive console to save keystrokes:
Short names:
import numpy as np
import matplotlib.pyplot as plt
import tkinter as tk
Importing everything from a module (usually not recommended):
from math import *
When importing some packages, submodules will be imported automatically.
Examples:
import os
import numpy as np
os.path.join(...)
np.random.randint(10)
Counterexample - this will fail:
import urllib
urllib.request.urlopen(...)
simple use from the terminal:
pip install package_a package_b
website of the Python Package Index
exercise:
convert the following markdown string to HTML - look for a package on PyPI to help you with the task
markdown_string = """
# Important packages
- requests
- numpy
- sqlalchemy
"""
possible solution:
pip install markdown
import markdown
html_string = markdown.markdown(
markdown_string
)
we can import local Python files as modules
example: local file messages.py
import messages
print(messages.message1)
we can create so-called packages as folders
example: folder phrases/, files phrases/messages.py and phrases/greetings.py
from phrases import greetings
print(greetings.greeting1)
Search order of imports:
Avoid name clashes with existing modules / packages!