Python beginner

Topics

  • overview and comparison to other programming languages
  • installation
  • working with the interactive Python console
  • variables and basic data types
  • composite types: dict, list, tuple
  • help and documentation
  • builtins and the standard library
  • control structures
    • if / else
    • loops (while, for)
  • functions
  • code quality and linting
  • debugging

Python: Overview

Python

  • simple syntax, relatively easy to learn
  • useful in many areas (science, web development, GUI programming)
  • big standard library, many additional packages

Python development and versions

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

Code examples

# this is a comment

a = 3
b = 4
print(a * b)

if a * b > 10:
    print('greater')

Installation on Windows

Installation on Windows

Download from https://python.org

during installation, check the option "Add Python 3.x to PATH"

Installation on Windows

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 on Windows

installation includes:

  • Python runtime for executing Python code
  • interactive Python console
  • IDLE: simple development environment
  • PIP: package manager for installing extensions

Interactive Python console

Interactive Python console

options for running Python code:

  • write a program as a file / collection of files, run that program (e.g. GUI applications, web applications, data processing pipelines)
  • type code into an interactive console or notebook line by line (e.g. for quick calculations, experimenting, data exploration / analysis)

Interactive Python console

options:

  • local installation
  • online notebooks (Jupyter)

Local Python console

launching the Python console / shell:

  • command python in the command prompt
  • from the start menu (e.g. Python 3.9)

quitting:

exit()

Online Python consoles

simple:

https://www.python.org/shell/

Jupyter notebooks:

Variables

Variables

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

Variables

Overwriting (reassigning) variables:

name = "John"
name = "Jane"
a = 3
a = a + 1

Basic (primitive) data types

Basic (primitive) data types

  • int (integer)
  • float (floating point number)
  • str (string): text
  • bool (boolean): yes / no
  • none: missing / unknown value

int and float

example:

(7 - 3) * 0.5 / 3.5

str

A string represents text

Strings can be enclosed in single or double quotes

greeting = "Hello"
name = 'John'

Building strings

name = "John"

Inserting a variable (f-strings):

message1 = f"Hello, {name}!"

Joining strings:

message2 = "Hello, " + name + "!"

Strings - escape sequences

Problem: how do we include characters like " in a string?

this is invalid:

text = "He said: "hi!""

Strings - escape sequences

solution:

text = "He said: \"hi!\""

Python treats the sequence \" like a single "

Strings - escape sequences

Line break: \n

a = 'line 1\nline 2'

single Backslash: \\

b = 'C:\\docs'

bool

boolean value: yes/no

In Python: True or False

note the capitalization

None

None represents a value that is unknown or missing

first_name = "John"
middle_name = None
last_name = "Doe"

Types and type conversions

Types

Determining the type of a variable via type:

a = 4 / 2

type(a)

Type conversions

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)

Functions

Functions

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 object
  • type() can tell us the type of an object
  • print() can write some output into the terminal
  • ...

Functions

A 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

Methods

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", "@")

Composite types: dict, list, tuple

dict

Dicts (dictionaries) are mappings that contain "named" entries with associated values.

person = {
    "first_name": "John",
    "last_name": "Doe",
    "nationality": "Canada",
    "birth_year": 1980
}

dict

Retrieving and setting elements:

person["first_name"]
person["first_name"] = "Jane"

dict

exercise:

create and modify dictionaries that represent various objects, e.g.:

  • a date (e.g. October 23, 1971)
  • a calendar event
  • a person
  • a product in an online shop
  • ...

list

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}
]

list

Retrieving list elements via their index (starting at 0):

users = ["Alice", "Bob", "Charlie"]

users[0]
users[1]
users[-1] # last element

list

Overwriting a list element

users[0] = "Andrew"

list

Appending an element

users.append("Dora")

list

Removing the last element:

users.pop()

Removing by index:

users.pop(0)

list

Determining the length

len(users)

list

exercise:

create and modify data consisting of dicts and lists that represents various objects, e.g.:

  • todos
  • calendar events
  • products in an online shop / shopping basket
  • transactions on a bank account

Tuple

date = (1973, 10, 23)
  • area of application: similar to dicts
  • behavior: similar to lists

Tuples

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

Tuples

Behavior: similar to lists:

date_tuple[0] # 1973
len(date_tuple) # 3

Unlike lists, tuples are immutable (no .append / .pop / ...)

Data types - exercises

create and modify data structures that include dicts, lists and tuples

Object references and mutations

Object references and mutations

What will be the value of a after this code has run?

a = [1, 2, 3]
b = a
b.append(4)

Object references and mutations

An assignment (e.g. b = a) assigns a new (additional) name to an object.

The object in the background is the same.

Object references and mutations

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]

Object references and mutations

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

Help and documentation

Help and documentation

resources:

  • official guides
  • official API reference
  • answers for questions: Stack Overflow

Help and documentation

Interactive help on objects in the Python console:

help(list)

(navigate through long outputs via Space and Enter, exit via Q)

Help and documentation

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

Help and documentation

helpful website with answers for many common questions: StackOverflow

Help and documentation

other free resources:

Error messages and tracebacks

Error messages and tracebacks

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

Error messages and tracebacks

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 messages and tracebacks

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'

VS Code for Python

VS Code for Python

popular development environments for Python:

  • VS Code (open source)
  • PyCharm Community (open source)
  • PyCharm Professional

VS Code

Basic functionality:

  • opening a folder
  • file explorer
  • creating a new (Python) file
  • split editor

Python extension

functionality:

  • show errors / warnings (via pylint, flake8)
  • automatic formatting (via black / autopep8, yapf)
  • debugging
  • Jupyter notebooks

Python extension

installation:

  • open the extensions view in the left sidebar (fifth icon)
  • install the extension named Python by Microsoft

registering your Python installation with VS Code:

  • open the command palette (F1 or Ctrl + Shift + P)
  • search for "Python: select interpreter"
  • Enter
  • wait...
  • choose the desired Python version (probably only 1 choice)

Configuration

via File - Preferences - Settings

possible settings:

  • Auto Save
  • Format on Save
  • Word Wrap
  • Python > Formatting: Provider (recommendation: black)
  • ...

Command palette

command palette: via F1 or Ctrl + Shift + P

  • searchable
  • shows shortcuts

example commands (some are only available for specific file types):

  • View: Toggle Terminal
  • Find
  • Format Document
  • ...

Python extension: running programs

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)

Text output

Text output

in the interactive console / notebook:

if the last command in a cell produces a value, it will be automatically written ("printed") as the output

Text output

general way to create text output from anywhere: print()

print("Hello, world!")

Our first Python program

Our first Python program

We'll create a file called greeting.py

Our program will ask the user their name and greet them.

Input and output of text

Input: via input():

print("What is your name?")
name = input()

input will always return a string

Input and output of text

writing the greeting

print("Nice to meet you, " + name)

Comments

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)

Executing programs

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)

Exercise: age from birth year

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.

Exercise: length of the name

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.

Builtins, standard library

Builtins, standard library

  • Builtins: functions and objects that are used frequently and are available at all times
  • Standard library: collections of additional modules and packages that can be imported

documentation: https://docs.python.org/3/library/index.html

Builtins

amongst others:

  • print()
  • input()
  • len()
  • max()
  • min()
  • open()
  • range()
  • round()
  • sorted()
  • sum()
  • type()

Standard library

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))

Standard library

modules of interest:

  • pprint (pretty printing)
  • random
  • math
  • datetime
  • os (operating system, file system)
  • urllib.request (HTTP queries)
  • webbrowser (simple web-browser controller)

print and pprint

Printing multiple elements:

print(1, 2, 3, sep=", ", end="\n\n")
1, 2, 3


print and pprint

import pprint

pprint.pprint(['Mercuy', 'Venus', 'Earth', 'Mars', 'Jupiter',
               'Saturn', 'Uranus', 'Neptune', 'Pluto'])
['Mercuy',
 'Venus',
 'Earth',
 'Mars',
 'Jupiter',
 'Saturn',
 'Uranus',
 'Neptune',
 'Pluto']

open

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

urllib.request

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()

random

import random

print(random.randint(1, 6))
print(random.choice(["heads", "tails"]))

Control structures

Control structures

By using control structures we can execute some code repeatedly or only under certain circumstances.

Control structures

most important control structures in programming languages:

  • if / else
  • loops
    • while loop
    • do while loop
    • for loop (counting loop)
    • foreach loop

Control structures in Python

  • if ... else ...
  • loops:
    • while
    • for ... in ...
    • for ... in range(...)

Comparisons

Comparisons

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)

Comparisons

The result of a comparison is a boolean value (True / False)

We can store the result in a variable:

is_adult = age >= 18

Combining comparisons with and, or, not

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")

If / else

If / else

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 / elif / else

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 blocks

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)

Exercise: coin flip

Simulate a random coin flip via random.choice(["heads", "tails"])

Let the user guess the outcome and tell them if they were right

For loops

For loops

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

For loops

names = ["Alice", "Bob", "Charlie"]

for name in names:
    print("Hello, " + name + "!")

Exercise: for loops and if statements

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

Counting loops

Counting loops

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].

Counting loops

typical variable name in counting loops: i

Counting loops

exercise: create a "multiplication table"

1 x 7 = 7
2 x 7 = 14
3 x 7 = 21
4 x 7 = 28
...

While loops

While loops

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

While loops

exercises:

  • guess the number with multiple attempts
  • a loop that prints the numbers 1 to 10
  • a loop that prints the numbers 7, 14, 21, ..., 70
  • a loop that creates the list [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  • exercise program for simple calculations
  • shopping list

While loops

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"]

Break

Break

keyword break: may be used to end the current loop

Break

example (do-while-loop):

a = 1

while True:
    a = a * 2
    print(a)
    if (a > 1000):
        break

Parts of programs

Parts of programs

  • programs
    • code blocks
      • statements
        • expressions

Empty code blocks

empty code block via the pass statement:

# TODO: warn the user if path doesn't exist

if not os.path.exists(my_path):
    pass

Statements across multiple lines

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

Expressions

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

Control structures - exercises

Control structures - exercises

  • guess the number
  • interest calculator
  • laws by age
  • math trainer (with random tasks)
  • login system
  • leap year

see https://github.com/marko-knoebl/slides/tree/master/exercises/python-beginner

Function parameters

Positional parameters and keyword parameters

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))

Optional parameters and default parameters

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

Defining functions

Defining functions

example:

def average(a, b):
    m = (a + b) / 2
    return m

Optional parameters and default parameters

This is how we define default values for parameters:

def shout(phrase, end="!"):
    print(phrase.upper() + end)

shout("hello") # HELLO!
shout("hi", ".") # HI.

Scope

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"

Scope

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

Functions: Exercises

Functions: Exercises

  • function that checks if a year is a leap year
  • function that checks if a number is a prime number
  • function that returns all prime numbers in an interval
  • function that verifies a bar code check digit (GTIN check digit) (tricky)
  • function that computes the fibonacci numbers
  • function that creates a list of lottery numbers
  • function that can asks the user a yes/no question and returns either True or False

For bar codes / primes: look up the % operator

see https://github.com/marko-knoebl/slides/tree/master/exercises/python-beginner

Modules and packages

Modules and packages

  • Module = collection of Python objects that can be imported
  • Package = collection of modules

(packages are actually a special type of modules)

Example imports

  • urllib = package
  • urllib.request = module
  • urllib.request.urlopen = function
  • sys = module
  • sys.path = object

Example imports

Typical 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

Shorter names for imports

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 *

Automatic import of submodules

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(...)

Conventions for imports

  • all imports in a Python file should be at the start of the file
  • imports should be split into three groups:
    • imports from the standard library
    • imports from other libraries
    • imports within the project

PIP and PyPI

PIP and PyPI

  • PyPI: Python Package Index: official repository for installable Python packages
  • PIP: package manager for Python

PIP

simple use from the terminal:

pip install package_a package_b

PyPI

website of the Python Package Index

https://pypi.org/

PIP and PyPI

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
"""

PIP and PyPI

possible solution:

pip install markdown
import markdown

html_string = markdown.markdown(
    markdown_string
)

Local modules

Local modules

we can import local Python files as modules

example: local file messages.py

import messages

print(messages.message1)

Local modules

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)

Resolving imports

Search order of imports:

  • directory of the Python script that was originally executed
  • standard library
  • external libraries

Avoid name clashes with existing modules / packages!