German / English

The Python programming language

introduction

preliminary remark

Why Python?

Python... A major reason for Python's popularity is the large number of freely available materials such as introductory tutorials, free books, sample programs, extensions, etc. Much of it is in English, but some is also in German.
A key resource for Python is the Python Software Foundation page .

Computing speed (performance)

Python first emerged as a teaching language in academia. Therefore, speed (performance) was not the most important goal. Python is significantly slower to run than C and significantly slower than Java. However, this is less a property of the language itself than of the concrete implementation.

remedy

The most important features of Python

Python is case sensitive (in English the language is said to be "case sensitive"). This applies to both the reserved words and variable names. For those who already know another programming language, the following list is of interest:

Python is interpreted

Put simply, there are 2 types of programming languages: compilers and interpreters. Python belongs to the 2nd group. This has the advantage that a program does not have to be translated (=compiled) into machine language after every change. On the other hand, it means that Python must be installed on every computer on which a Python program is to be able to run. However, there are workarounds for most of these limitations (e.g. http://www.py2exe.org/ ).

How is Python installed?

Python is offered in 2 versions (quite confusing for beginners): Version 2 and Version 3
When do you choose which version?
Some improvements were made from version 2 to version 3 that are not backwards compatible with version 2, i.e. Python 3 programs that use these new features will not run under Python 2.
Therefore, the following applies:
If you write a program from scratch without using third-party libraries (=libraries), then you use Python 3. If you are dependent on the use of such libraries and they only exist in the Python 2 version, then you use Python 2. If in doubt, install Python 3 first.
The installation is very easy.

Windows

A Google search with the words "Download Python" or "Download Python" usually returns the correct address as the first search result:
https://www.python.org/downloads/
After downloading, the python-xyzexe file is in the Downloads folder , where x, y, z are digits denoting the version number. The number z changes in each new version, the number y only with major changes and the number x indicates that there are some major changes in the new version, but don't worry, programs written for older versions can usually be used as is will.
Double-click the downloaded file and the following window will open:

Install

Tick the following box:

installpath

This allows Python to be called system-wide from anywhere.
Then click on "Install Now". After a short time, a window with the text "Setup was successful" should appear.
When would you not tick this box?
If you want to run several different Python versions in parallel on one computer. For example if you have an application that requires a specific version of Python.
Standardmässig wird Windows-Benutzern die 32-bit Version angeboten. Diese Version kann man getrost auch auf 64-bit Windows-Versionen installieren. Für Python gibt es auch eine 64-bit Version. Die ist für den Anfang aber nicht notwendig.

Linux

Python is pre-installed on many Linux systems. You may have to help out a bit with the configuration.

Raspberry Pi

Not only is Python already installed here, the "Pi" in Raspberry Pi stands for Python and shows the mini-computer's commitment to this programming language.

macOS

Python should already be installed and running, but may not be the latest version. You can find the latest version at the following link:
https://www.python.org/downloads/mac-osx/

use Python

Finally the time has come. Python is installed on the computer. How can I start it?
Hover your mouse over the Windows Start icon in the lower left corner, click 1 time and start typing "pyth..." on the keyboard. As you type, the menu appears as shown in the image below:

start python

You are offered 2 options to start Python:
For the first option, you don't necessarily need the link shown here, the Python shell works in any Windows command prompt.

The Windows command prompt

Again, hover over the Windows Start icon in the lower left corner, click 1 time and start typing "cmd" on the keyboard. The following menu will then appear:

start command

Click on Command Prompt and the following window will open:

command
It is faster with: Window+r, then type cmd and then Enter.

The Windows command prompt opens. A cursor stands in the first line and waits for your input.

What is Windows Command Prompt?

The Windows command prompt, also sometimes called the command line or shell, is a powerful additional gateway to your computer's operating system. The Windows command prompt is very powerful and is therefore intentionally hidden. Only users who know what they are doing should work here.
In the command prompt you can enter text commands and use them to do something or just get information. For example, enter "dir" (=directory) followed by the Enter key. Then you get the contents of the current directory listed. Feel free to try it out. With "cd" you can switch to one of the listed directories and with "cd .." you can go back one level.

The Python shell

Now enter "python" in the command prompt:

shell

Python responds with ">>>". That means the installation worked and Python was found on the system. The ">>>" is also called the prompt. With that, Python reports and says: "I'm ready for your input".
Führt die Eingabe von "python" hier zur Fehlermeldung:
Der Befehl "python" ist entweder falsch geschrieben oder konnte nicht gefunden werden.
Dann gibt es 2 Möglichkeiten:
  • Python wurde nicht richtig installiert
  • Python ist installiert wurde aber nicht gefunden
Versuch im ersteren Fall die Installation noch einmal und wenn es wieder nicht klappt, bitte jemand um Unterstützung. Im zweiten Fall hat während der Installation das Setzen des Systempfads nicht geklappt. Vielleicht war während der Installation das betreffende Häkchen nicht gesetzt? Entweder versuchst du eine Deinstallation und Neuinstallation diesmal mit dem Häkchen, alternativ kann man diese Konfiguration auch manuell vornehmen:

Gib zuerst in der Windows Eingabeaufforderung "where python" ein und drücke die Eingabetaste:
C:\Users\administrator>where python

Windows meldet dann den Pfad von python.exe der könnte etwas so lauten (xy steht für die Versionsnummer):
C:\Pythonxy\python.exe

oder so:
C:\Users\administrator\AppData\Local\Programs\Python\Pythonxy-z\python.exe


Öffne dann:
Start > System > Erweiterte Systemeinstellungen > Umgebungsvariablen
Selektiere in der Rubrik "Systemvariablen" die Variable "Pfad" und drücke "Bearbeiten".
Füge dann den entsprechenden Python-Pfad ans Ende der Variablen hinzu, der alte und der neue Inhalt werden mit ";" getrennt. Das Ergebnis wäre dann zum Beispiel (xyz sind die Versionsnummern, sie müssen mit deiner Version übereinstimmen):
C:\Windows;C:\Windows\System32;C:\Pythonxy
oder
C:\Windows;C:\Windows\System32;C:\Users\administrator\AppData\Local\Programs\Python\Pythonxy-z\

alternative

As an alternative to local installation, there are also online variants, for example the one shown here:
https://repl.it/languages/python3

A local installation is preferable for our purpose.

If everything went well, we now have a Python shell available - a very good opportunity to gain initial experience with Python. The shell is also called the "interactive mode" because Python reacts immediately to every input with a result. Python "replies" to our inputs, so to speak.
This is where the strength of an interpreter comes into play. In contrast to a compiler, the entered program sections do not have to be translated first.

Hello World (anticipation)

Traditionally the first program you learn in any programming language:
print("hello world!")

Expressions

What is an expression? Expressions are important building blocks of programs. An expression consists of a combination of values ​​and operators. Expressions are evaluated and then return a value.

The following examples are known to us from school:
You can write expressions with or without spaces, depending on your taste.
(3+5)*2 is equivalent to (3 + 5)*2

Well-Formed Expressions

The structure of expressions is subject to certain rules. do you know examples If an expression satisfies these rules, then it is said to be "well-formed". On the other hand, it cannot be evaluated and the attempt returns an error. A violation of the rules in this context is called a "syntactic error". (We'll see later that there are other types of syntactic errors.)

The Python shell is an ideal tool for testing expressions. When developing a program, it's always worth having a shell open where you can quickly test expressions.

operators

The following table shows some important Python operators.
The ranking is in descending "operator order" (priority):
   
** power
*, /, //, % Multiplication, division, integer division, modulo
+, - addition, subtraction
in, not in Element of, not element of
<, <=, >, >=, !=, == comparison
not logical "not"
other logical "and"
or logical "or"

Operators on the same line have the same precedence. If you evaluate an expression using this table, you always start with the operator that is furthest up in the table. If two operators are on the same line, the expression is evaluated from left to right. For example, if there are no parentheses, * is evaluated before + because * comes before + in the list. Likewise, "and" is evaluated before "or" because "and" comes before "or" in the list. Parentheses can cause a different evaluation order, but parentheses can also make an expression more readable.
Now we can expand our list of expressions even further:

remark

Confusing "=" and "==" is one of the most common programming errors and happens even to experienced programmers.
A major advantage in Python is that "a = 1" is not a valid condition, so "if a = 1:" will return an error.

Operator overloading

Warning!: "Overloading" of operators can be very confusing for beginners. In order to evaluate an expression, you must first be sure of the data type you are looking at.
What output does the following statement produce. Explain the result:
print("*"*3)
What output does the following statement produce. Explain the result:
print("a"<"b")

data types

A distinction is made between basic and higher data types. First we will deal with the basic data types.

integer

Holds an integer of any size, positive or negative, such as 1 or 3 or 9999999 or -712 or 0.
Unlike many other languages, integers are "unbounded," meaning they can be of any size. This saves a lot of effort, makes the programs more secure (overflow) and works because Python itself reserves as much memory as necessary for each number.

floating point number (float)

Contains a decimal number like 11.456 or -71.3 or 29.0 (Caution! "." instead of ",")

Gleitkommazahlen sind auf den ersten Blick der umfassendere Datentyp. Haben aber entscheidende Nachteile. Zum Beispiel ist ein Vergleich nicht so einfach wie bei ganzen Zahlen:
2.00000001
2.00000000
Sind die Zahlen gleich oder nicht?

Gleitkommazahlen werden auch verwendet, um sehr große oder sehr kleine Zahlen in wissenschaftlicher Notation darzustellen. So bedeutet zum Beispiel 5.0e30 eine 5 gefolgt von 30 Nullen. 1.7e-6 ist 0.000017, was bedeutet 1,7 dividiert durch 1 gefolgt von 6 Nullen.

character string

A character string contains a text, for example the name of a person, such as John Doe. The input function used here soon returns a character string.

Boolean (logical value)

Contains either True or False. The Boolean data type can only have one of these two states. Boolean values ​​also result from comparisons.
For example, the expression 3 < 4 evaluates to Boolean True.

The type function can be used to query which data type is present.
The conversion functions can be used to convert between the data types: The following example shows how the type function and conversion functions can be used:
>>> type(bool("true")) <class 'bool'> >>> bool(0) False >>> bool(1) True >>> type(3) <class 'int'> >>> type(3.0) <class 'float'> >>> type(1/2) <class 'float'> >>>
What do you notice on the last call?

literals

variable

Variables are like containers for a value. To distinguish variables from each other, they have identifiers. The values ​​are accessed via these identifiers.
x=2 y=x*2 print("x:", x) print("y:", y)

valid variable names

Variable names are subject to certain rules.
This also applies to other identifiers in Python (function names, class names, ...).
Allowed characters are:
Forbidden are: Good variable names express the meaning/use of the value they hold. For example: count, sum, length, first_name, last_name, age, temperature_12_o'clock, ... distance, angle, distance, x, y, z (for coordinates)

Python Convention (PEP 8)

Variable names and function names are lowercase, classes uppercase.
Unfortunately, both can be very difficult to find.

allocation

x=2 firstname="max" pi=3.14 is_greater_than = True is_not_greater_than = not is_greater_than # Code is like text

Attention!: an assignment is not an equation.
x=x+1 is a valid assignment but as an equation it would make no sense.

instructions

Sometimes instructions correspond to lines in the program, but an instruction can also span multiple lines.
name = input("Please enter your name: ") print("Hello", name)

instruction sequences

Simple programs sometimes only consist of sequences of instructions.
x=2 x=x*2 print("x:",x)
Instruction sequences are processed strictly in order.

Comments

A distinction is made between single-line "#" and multiple-line comments: """
Purpose: Intended for those who read the code, i.e. possibly also for the author himself.

Such comments are not necessary. Self-explanatory.
x=3 # The variable x is assigned the value 3

""" You can simply comment out several lines with the triple inverted comma """
The above method can also be used to comment out entire program parts and thus switch them to inactive.

It might be a bit confusing at first:
Even multi-line text in the program is written with triple inverted commas.
>>> str = """hello ... you!""" >>> str 'hello\nyou!' >>> print(str) hello you! >>>

IDLE

Python is a text-oriented language. Python programs can be written with any text editor.
An integrated development environment or IDE supports programming. A simple but good IDE called "IDLE" is already pre-installed in the standard Python installation.

Key features of IDLE.
If you open and start a Python program, there are 3 windows
  1. the source code
  2. the application window: this is where the program runs
  3. a Python shell where all print() output and any error messages are displayed
Use Alt+tab to switch between windows. You can close it under Windows with Alt+F4 or with the "x" at the top right .
(For other operating systems there are equivalent shortcuts)

Attention! Python programs must not be given the same names as Python modules used.
For example, a self-created program file "turtle.py" leads to an error.
Unfortunately, you will not get an error message in this case.

The if statement

Simple programs sometimes only consist of sequences of instructions, but these can neither react to external conditions nor to internal states. The program flow has no variants and is strictly linear.
if <condition>: <statement block>
The following example uses the input function, which has not yet been explained.
The input function expects user input terminated by Enter. You can pass a text to the input function that will be output. User input is returned as text (even if the user enters a number).
>>> str = input("Type something: ") Type something: Test >>> str 'Test' >>>

temp = int(input("How cold is it today?: ")) if temp < 0: print("Beware of ice!")
Note here that the program will fail if the user does not enter an integer.

Indentation in Python

Using indentation to form blocks is a specialty of Python.
This feature takes some getting used to when switching from other languages, but it is very practical.

else

Decisions of the following form are often required:
temp = int(input("How cold is it today?: ")) if temp < 0: print("Careful on ice!") else: print("Probably no ice today.")

elif (else if)

With the elif branch, the if construct is complete:
temp = int(input("How cold is it today?: ")) if temp < 0: print("Beware of ice!") elif temp > 0: print("Certainly no ice today.") else: # temp = = 0 (everything to the right of "#" is just a comment) print("It's exactly zero degrees.")
The elif branch is the only one that can appear more than once.

Task:
Write a program that asks the user to enter their age. The program is designed to determine if the user is under 13, a teenager (13-19), or older. The program should then make a corresponding output.
Use the input function for this.

Ribbons

There are 2 types of loops in Python.

for loops

Especially useful if you know in advance how often you want to go through the loop.
Often - but not always - the range function is used here.
Try typing the following in the shell:
print(list(range(10)))
for i in range(10): print(i)

special case:
for char in "abcdef": print(char)

Similarly for lists

while loops

These are especially useful if you don't know the exact number of iterations, but you can easily specify a loop condition.
i = 0 while i < 10: # "i < 10": Loop condition print(i) i=i+1 # This line is very important because of the termination condition!
The programmer is responsible for ensuring that the termination conditions are actually met. An endless loop often occurs unintentionally.

But sometimes you deliberately want an infinite loop (e.g. for the implementation of a service):
while True: print(".", end="") print("Goodbye") # This line is never reached: "dead code"

break

The break statement ends the loop prematurely, but the program continues to run.
Now we see that a "while True:" loop is an infinite loop only if it doesn't contain a reachable "break".
In this context, a "while True:" construction is a very useful option.

Task :
Write a program that prompts the user to enter whole numbers. By entering "q" the program should be terminated. Before that, however, the sum of the entered numbers should be output.

lists

Lists belong to the higher data types. Higher data types, unlike elementary data types, are not atomic. They can be used to display series of values ​​(e.g. a series of measured values) or compositions (e.g. a personal data record consisting of first name, last name, date of birth, ...).

A list can be created in Python in the following way:
pets = ["cat","dog","hamster","goldfish","bunny"]

The names of the pets are the elements here. Elements can then be accessed by their so-called index, by first giving the name of the list or tuple and then the position of the element in square brackets.

Danger! :
Not only in Python, but also in almost all other programming languages, you don't start counting with 1 but with 0!

Entering pets[3] does not return 'hamster', as you might expect, but 'goldfish'!
This is a fundamental difference, a potential source of error, and it takes any novice programmer more or less time to get used to it.
So pets[0] returns 'cat' and entering pets alone returns the whole list.
Here's another little trick: pets[-1] returns the last element of the list "bunny".

Example:
>>> pets = ["cat","dog","hamster","goldfish","bunny"] >>> pets[3] 'goldfish' >>> pets[0] 'cat' >>> pets ['cat', 'dog', 'hamster', 'goldfish', 'bunny'] >>>

The following command sorts the list named pets :
pets.sort()

Example:
names = ["David", "Anna", "Peter", "Paul", "Luise"] print("The names are:", names) names.sort() print("The names in sorted order are:" ) print(names)

When executed, this gives:
>>> The names are: ['David', 'Anna', 'Peter', 'Paul', 'Luise'] The names in sorted order are: ['Anna', 'David', 'Luise', 'Paul ', 'Peter'] >>>

Slice operator for lists

This returns parts of lists:

list[n:m] returns a list with elements of the list starting with the element with the index n inclusive up to the element with the index m excluding .

However, the lower (n) and upper index (m) can also be omitted, so the following variants are also permitted:
Here are a few examples to clarify:
>>> names = ["Sarah", "David", "Ann", "Peter", "Mary", "Paul"] >>> names[0:1] ['Sarah'] >>> names[1 :4] ['David', 'Ann', 'Peter'] >>> names[3:] ['Peter', 'Mary', 'Paul'] >>> names[:4] ['Sarah', 'David', 'Ann', 'Peter']

Iterate through lists

To iterate through lists, the for loop is used as follows:
pets = ["cat","dog","hamster","goldfish","bunny"] for element in pets: print(element)

Mixed lists

Mixed lists are allowed in Python, which means that the elements do not all have to have the same data type.
(This is not so self-evident)
So the following is allowed:
Mix_List = ["abc", 1, 3.5, False]

lists of lists

will be dealt with later

Built-in methods for lists

With the dir command (works with any object) these are displayed. Methods with "__" can be ignored for now (e.g. __add__ corresponds to the "+" operator):
>>> dir(list) ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] >>>
Here you can find all the basic useful functions for lists, such as adding, removing, ...
Attention!: what does list.count() return?

Also try:
help(list)

or:
help(list.insert)

With this in mind, we can find out that list.count doesn't return the number of elements in a list, because the method doesn't need an additional parameter for that.
The count method returns the number of elements of a given (passed) value. For the total number of elements "len()" (built-in functions) is sufficient.
Note: when do you use object-oriented notation "object.method()" when do you use classic notation "function(parameter)"?

Let's use this information to demonstrate one way of working with lists:
list_1 = [] list_1.append("a") list_1.append("b") list_1.append("c") print(list_1) list_1.insert(1,"d") print(list_1) list_1.remove( "d") print(list_1)

dir()/help()

dir() and help() also work with built-in objects:
int (integer), float, bool, str (strings), dict (dictionaries), list, tuple, set, ...
And also with imported objects:
>>> import math >>> dir(math) ['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc'] >>> help(math.sin) Help on built-in function sin in module math: sin(...) sin(x) Return the sine of x (measured in radians). >>>

tuple

Everything that has been said for lists applies to them, with the exception that once created, tuples cannot be modified.
pets = ("Cat","Dog","Hamster","Goldfish","Bunny") for element in pets: print(element) print(pets[3]) pets.insert(2, "Goldfish")

Delivers:
>>> Cat Dog Hamster Goldfish Rabbit Traceback (most recent call last): File "C:/Python34/haustiere.py", line 4, in <module> haustiere.insert(2, "Goldfisch") AttributeError: 'tuple' object has no attribute 'insert' >>>

functions

A function is a piece of program code that can be called from different places in the program. You already know functions, because Python has many useful built-in functions that almost no program can do without. input() and print() are examples of such functions:

Built-in functions list

In any case, an occasional review of this list is recommended, because you will find useful building blocks here on which your own works can be built. Some built-in functions are used frequently, some only very rarely:

https://docs.python.org/3/library/functions.html

In addition to the possibility of using built-in functions, the possibility of being able to create your own functions is one the most important basic methods of a programming language.
In Python, the keyword def (short for "define") is used to define a function. A function can be called from anywhere in the program by specifying its name. The program code in the function is then processed and after completion the calling program continues to be executed from the point of the call. The program flow jumps back to the point of the call, so to speak.
There are functions that do something ("do_...") and functions that return something ("get_...") and combinations of these.

without parameters

Nevertheless, the "()" is used in order to be able to distinguish from a variable.

Let's consider the following function:
def Stars(): print("*****") print("Before calling the Stars() function") Stars() print("After calling the Stars() function")

>>> ============= RESTART: C:/.../stars.py ============= Before calling the function Stars() * **** After calling the Stars() >>> function

This is the simplest type of function, but it's not very flexible. 5 stars are always given.

with one/several parameter(s)

The following function is an improved variant of the function above. A parameter is passed that controls how many stars are given.
def stars_according_number(number_stars): print("*" * number_stars) stars_according_number(5)

Calling it with parameter 5, the result is the same as the function above.
>>> ==== RESTART: .../stars_according_number.py ==== ***** >>>

Such a function can of course be used in many different ways:
def stars_by_number(number_of_stars): print("*" * number_of_stars) stars_by_number(1) stars_by_number(2) stars_by_number(3)

The above program returns:
>>> ==== RESTART: .../stars_according_number.py ==== * ** *** >>>

with or without a return value

The functions created so far did not return a value: Function without a return value. The well-known print() function is an example of this group.
Functions without a return value are also called procedures in other programming languages.

A function can also perform a calculation and return a value to the calling program: function with return value. The input() function, which we are already familiar with, is an example of this group.
#T(°C) = (T(°F) - 32) / 1.8 def Fahrenheit_to_Celsius(Temperature_in_Fahrenheit): return int((Temperature_in_Fahrenheit - 32) / 1.8) print("-100 Fahrenheit is in Celsius: ", Fahrenheit_to_Celsius(- 100)) print("0 Fahrenheit is in Celsius: ", Fahrenheit_to_Celsius(0)) print("100 Fahrenheit is in Celsius: ", Fahrenheit_to_Celsius(100))

The central point here is the return statement, which is new for us and is formed from the "return" keyword and followed by the return value. The return statement ends the execution of the function and returns the return value. Any program code after a return statement is no longer executed ("dead" code). About a call:
if <condition>: return
but that cannot be said in general terms. So the return command does not have to be the last statement in the function.

In the calling program, the function call is then replaced by the return value. Out of:
print("-100 Fahrenheit is in Celsius: ", Fahrenheit_to_Celsius(-100))

becomes after executing the function and substituting the return value:
print("-100 Fahrenheit is in Celsius: ", -73)

Executing the program gives:
>>> RESTART: .../Fahrenheit_nach_Celsius.py -100 Fahrenheit are in Celsius: -73 0 Fahrenheit are in Celsius: -17 100 Fahrenheit are in Celsius: 37 >>>

In the small program above, we converted the return value to an int because the division would result in long decimal numbers. Instead, we could have done a rounding in order to be able to output the values ​​more precisely. Python provides the built-in function "round()" for this, with which you can round to 2 decimal places, for example. Change the line:
return int((Temperature_in_Fahrenheit - 32) / 1.8)

in
return round((Temperature_in_Fahrenheit - 32) / 1.8,2)

The built-in function "round()" is also a function with a return value. It is given 2 transfer parameters: the number to be rounded and the number of digits to which it is to be rounded. Do the same for the following 2 lines and start the program. Danger! A common and very understandable beginner's mistake regarding functions with return values ​​can be shown with the following example program:
def double(number): return number * 2 double(10)

Look at the program and try to predict what will happen when it is called. Is the program error-free? Will it work as desired? Try the program. Suggest solutions.

Resolution:
The program is syntactically correct (it contains no syntactic errors). However, the program contains a semantic error, which is more difficult to find than a syntactic error. The function is correctly defined and meaningfully named. The call is fine, but the problem is that nothing is done with the return value returned by the function. The value is neither output nor used in any other way. After the start, the program terminates after a short computing time, but nothing happens. A possible fix would be the line:
double(10)

to change to:
print("The result is:", double(10))

boolean functions

These are functions that can only return True or False as a result.
These can be used as a condition (e.g. in if, while).
It doesn't have to
if f()==True: ...

to be written.
if f(): ...

suffices perfectly.
The same also applies to boolean variables .

Functions are also an important way of structuring a program.

Dictionaries    +!  advanced content

Another important data type in Python. Similar to a list, but the elements are not addressed via an index but via a "key". Dictionaries are also said to be lists of key/value pairs.
>>> dict = {"one":"one", "two":"two", "three":"three", "four":"four"} >>> dict["one"] 'one' >>> print(dict) {'four': 'four', 'two': 'two', 'three': 'three', 'one': 'one'} >>>

The order in the dictionary is not guaranteed.
dict = {"one":"one","two":"two","three":"three","four":"four"} for key in dict: print ("key:", key, " dict[key]:", dict[key])

The above program returns:
>>> key: one dict[key]: one key: three dict[key]: three key: four dict[key]: four key: two dict[key]: two >>>

Nested dictionaries

...

Import modules

The functionality of Python can be extended by importing modules.
There are several ways to do this import.
import random Obst = ["Apfel", "Birne", "Banane", "Orange"] print(random.choice(Obst)) for i in range(10): print(random.randint(1,6)) for i in range(10): print(random.randrange(1,7))

from time import strftime, gmtime, localtime # http://strftime.org/, https://docs.python.org/2/library/datetime.html print("aktuelle Zeit:", strftime("%d.%m.%Y %H:%M", gmtime())) print("aktuelle Zeit:", strftime("%d.%m.%Y %H:%M", localtime())) print("aktuelle Zeit:", strftime("%d.%m.%Y %I:%M", localtime())) print("aktuelle Zeit:", strftime("%d.%m.%Y %I:%M %p", localtime())) """ Example output: aktuelle Zeit: 03.05.2018 12:35 aktuelle Zeit: 03.05.2018 14:35 aktuelle Zeit: 03.05.2018 02:35 aktuelle Zeit: 22.11.2018 02:35 PM """

"strftime" probably stands for "string from time". For more information on date and time formatting see:
http://strftime.org/
https://docs.python.org/2/library/datetime.html

from math import * print(sqrt(9)) print(pi)

The following are imported: objects, functions, constants

Turtle graphic

There's a great way to get started with graphics programming in Python in an easy way. Traditionally, this module is called turtle graphics because it is about an imaginary turtle that, while you control it with commands, draws a colored line wherever you send it. You can also control the color and thickness of the pen with commands and you can raise and lower the pen.
After importing the turtle library with "from turtle import *", you can access all turtle commands. Some of these commands are listed here, many commands have a long and a short form (e.g. forward and fd) - it doesn't matter which of the two you use.

Turtle Commands:
fd(distance) (forward) Die Schildkröte bewegt sich um "Strecke" nach vorne.
bk(Strecke) (back) Die Schildkröte bewegt sich um "Strecke" rückwärts.
lt(Winkel) (left) Die Schildkröte dreht sich um "Winkel" nach links.
rt(Winkel) (right) Die Schildkröte dreht sich um "Winkel" nach rechts.
pu() (pen up) Die Schildkröte hebt den Zeichenstift an (und schreibt nicht mehr).
pd() (pen down) Die Schildkröte senkt den Zeichenstift (und schreibt wieder).
pensize(Breite) setzt die Stiftdicke auf "Breite".
pencolor(Farbe) setzt die Stiftfarbe auf "Farbe".
shape(Form) setzt die Form der Schildkröte (‘arrow’,‘classic’,‘turtle’,‘circle’).
home() Schildkröte kehrt nach (0,0) zurück (Mitte des Zeichenblatts).
clear() Löschen der Zeichnung, Schildkröte ändert Zustand nicht.
reset() Löschen der Zeichnung, Schildkröte geht in Ausgangszustand.
setup(Breite, Hoehe) Fenster mit "Breite", "Hoehe" erzeugen.
heading() In welche Richtung schaut die Schildkröte? (3-Uhr-Position = 0)
setheading(Winkel) Drehe die Schildkröte in Richtung "Winkel" (3-Uhr-Position=0).
goto(x, y) Bewege die Turtle zur Position x, y.
(Falls pen=down wird auch gezeichnet. Ändert die Orientierung nicht.)
dot(size, color) Zeichnet einen Kreis der Größe "size" und der Farbe "color" an der aktuellen Position.
towards(x, y) Liefert den Winkel, den sich die Schildkröte drehen müsste um auf x, y zu zeigen.

With Turtle Graphics you can easily create great graphics and learn a lot about programming in a descriptive way because you can, so to speak, watch the programs at work.
And here is a sample program to demonstrate:
from turtle import * setup(400,400) # create a window of this size shape('turtle') # show the turtle fd(50) # forward 50 units lt(90) # rotate left 90 degrees pencolor('red' ) # pen color is now "red" fd(70) lt(90) fd(110) pencolor('blue') # pen color is now "blue" rt(90) # rotates 90 degrees to the right bk(100) # Go back 100 units pu() # pen up: raise the pen lt(45) bk(50) pd() # pen down: lower the pen pensize(5) # change the pen size to 5 bk(70) pensize( 1) home() # Go to the origin

Here is the result when the program is called:

turtle

And here is an advanced example:
import turtle, colorsys turtle.setup(350,350) turtle.pensize(10) turtle.color("#ff0000") turtle.fd(10) turtle.color("#00ff00") turtle.fd(10) turtle.color( "#0000ff") turtle.fd(10) hue=0.0 i = 0 while True: turtle.fd(1) turtle.lt(1) turtle.color(colorsys.hsv_to_rgb(hue, 1, 1)) hue+=0.01 i = i + 1 if i > 315: break

Output of the program:

circle

Event Oriented Programming

There are several fundamental approaches to programming. You already know several of them because they are an integral part of traditional programming: Another approach is presented in this chapter. This is also part of traditional programming, but it is not quite as universal as the three approaches mentioned above. In the context of programming graphical user interfaces (GUIs), this approach is increasingly used.
In event-oriented programming, events play a central role in the program logic. Every action of the user, for example mouse movements, clicks, key presses, triggers events. However, mechanisms within the program can also trigger events, such as the elapse of a specified period of time, the arrival of data or the completion of a previously started task. Events can also be triggered by the computer itself, for example a notebook whose battery level falls below a certain threshold could trigger an event specifically designed for this purpose.

Event handlers

Keypress Events

Events are associated with special event handlers (functions) that are called when the events occur. For example, such event handlers can be assigned to the arrow keys on the keyboard (up, down, left, right). Depending on which event occurs (up, down, left, right), the program executes the appropriate event handler, which then performs the correct movement of the turtle.
The turtle library presented above is ideal for presenting this event-oriented programming in a practical way.
import turtle turtle.setup(400,500) # Fenstergröße wn = turtle.Screen() # wn repräsentiert das Fenster wn.title("Tastendruck-Ereignisse") # Fenster Titel wn.bgcolor("lightgray") # Hintergrundfarbe schildkroete = turtle.Turtle() # Schildkröte anlegen # Event-Handler: def h1(): schildkroete.forward(30) def h2(): schildkroete.left(15) def h3(): schildkroete.right(15) def h4(): wn.bye() # Fenster schließen # Verknüpfung herstellen zwischen Tastenereignissen und Handlern wn.onkey(h1, "Up") wn.onkey(h2, "Left") wn.onkey(h3, "Right") wn.onkey(h4, "q") # Mit "listen" fängt die Anwendung an nach Ereignissen zu "horchen". # Ein richtiger Tastendruck löst den zugehörigen Eventhandler aus. wn.listen() wn.mainloop()

keypress

Mausklick-Ereignisse

But I can also react to mouse click events. I now add the following handler to the above program:
... def h5(x, y): turtle.penup() turtle.goto(x, y) turtle.pendown() ...

and with the following line I associate the handler with the event:
... wn.onclick(h5) # "onclick" reacts to mouse click ...

So together:
import turtle turtle.setup(400,500) # Fenstergröße wn = turtle.Screen() # wn repräsentiert das Fenster wn.title("Tastendruck-Ereignisse") # Fenster Titel wn.bgcolor("lightgray") # Hintergrundfarbe schildkroete = turtle.Turtle() # Schildkröte anlegen # Event-Handler: def h1(): schildkroete.forward(30) def h2(): schildkroete.left(15) def h3(): schildkroete.right(15) def h4(): wn.bye() # Fenster schließen #------------------- neu ------------------------ def h5(x, y): schildkroete.penup() schildkroete.goto(x, y) schildkroete.pendown() #------------------------------------------------ # Verknüpfung herstellen zwischen Tastenereignissen und Handlern wn.onkey(h1, "Up") wn.onkey(h2, "Left") wn.onkey(h3, "Right") wn.onkey(h4, "q") #------------------- neu ------------------------ wn.onclick(h5) # "onclick" reagiert auf Mausklick #------------------------------------------------ # Mit "listen" fängt die Anwendung an nach Ereignissen zu "horchen". # Ein richtiger Tastendruck löst den zugehörigen Eventhandler aus. wn.listen() wn.mainloop()

The following figure then shows a possible execution if I click on different points of the window during execution:
mouse click

Rest of the chapter +!  advanced content

timer

Let's look at the following example:
import turtle turtle.setup(400,500) wn = turtle.Screen() wn.title("Using a timer") wn.bgcolor("lightgray") schildkroete = turtle.Turtle() schildkroete.color("purple") schildkroete. pensize(3) def h1(): schildkroete.forward(100) schildkroete.left(56) wn.ontimer(h1, 2000) wn.mainloop()

The ontimer function is used to specify that function h1 is called after 2 seconds.
Result:
timer
This is sufficient for some applications, but if a timer function is to be called regularly then you have to proceed as shown below:
import turtle turtle.setup(400,500) wn = turtle.Screen() wn.title("Using a timer") wn.bgcolor("lightgray") schildkroete = turtle.Turtle() schildkroete.color("purple") schildkroete. pensize(3) def h1(): schildkroete.forward(100) schildkroete.left(56) wn.ontimer(h1, 2000) h1() wn.mainloop()
Result:
timer 2

Let's now build this timer functionality into our example:
import turtle turtle.setup(400,500) # Fenstergröße wn = turtle.Screen() # wn repräsentiert das Fenster wn.title("Tastendruck-Ereignisse") # Fenster Titel wn.bgcolor("lightgray") # Hintergrundfarbe schildkroete = turtle.Turtle() # Schildkröte anlegen # Event-Handler: def h1(): schildkroete.forward(30) def h2(): schildkroete.left(15) def h3(): schildkroete.right(15) def h4(): wn.bye() # Fenster schließen def h5(x, y): schildkroete.penup() schildkroete.goto(x, y) schildkroete.pendown() #------------------- neu ------------------------ def h6(): if schildkroete.pensize() == 1: schildkroete.pensize(10) else: schildkroete.pensize(1) wn.ontimer(h6, 700) #------------------------------------------------ # Verknüpfung herstellen zwischen Tastenereignissen und Handlern wn.onkey(h1, "Up") wn.onkey(h2, "Left") wn.onkey(h3, "Right") wn.onkey(h4, "q") wn.onclick(h5) # "onclick" reagiert auf Mausklick # Mit "listen" fängt die Anwendung an nach Ereignissen zu "horchen". # Ein richtiger Tastendruck löst den zugehörigen Eventhandler aus. wn.listen() #------------------- neu ------------------------ h6() #------------------------------------------------ wn.mainloop()

And here is another example of an implementation:
timer

recursion

From school we remember the definition of factorials:

n! = n * (n-1)! (for all n > 1))
n! = 1 (for n:0,1)

Consider the following function.
from turtle import * setup(800, 800) def draw_recursive(like_often_yet): if like_often_yet < 1: # abort the recursion return fd(how_oft_yet_yet) lt(15) # recursion call with reduced size: draw_recursive(how_oftly_yet - 1) draw_recursive(50)

The program creates the following picture:
recursion

Recursion can be quite confusing at first, because a definition that contains itself is reminiscent of a faulty circular reference at first glance. For example as in the following dialog:

"Do you know Max?"
"Yes, that's Tom's neighbor"
"Who is Tom?"
"This is Max's neighbor"

In fact, our function is not a circular reference, because the transfer parameter always plays a role when a function is called.
Let's expand the function a bit:
from turtle import * setup(800, 800) def dreieck(groesse): # Zeichnet ein Dreieck in der angegebenen Größe # Nach dem Zeichnen ist die Schildkröte wieder # in der ursprünglichen Position und hat den # ursprünglichen Winkel fd(groesse) lt(120) fd(groesse) lt(120) fd(groesse) lt(120) # Ergänzt auf 360 Grad def zeichne_rekursiv(wie_oft_noch): if wie_oft_noch < 1: # Abbruch der Rekursion return fd(wie_oft_noch) lt(15) dreieck(wie_oft_noch) # Rekursionsaufruf mit verringerter Größe: zeichne_rekursiv(wie_oft_noch - 1) zeichne_rekursiv(50)

The program produces the following picture:
recursion 2

Recursive functions are powerful tools and are often used in computer science. Recursive functions are also ideal for processing recursive data structures.
Recursive functions are not limited to graphical applications, there are, for example, recursive search methods.




Content from here goes beyond the Computing module

Word processing (string processing)

Let's recall and the example of iterating through a character string:
for char in "abcdef": print(char)

But also in other cases character strings can be treated like lists:
>>> str_list = "abcdef" >>> str_list[3] 'd'

Otherwise, searching one string within another is one of the most basic operations.
"in" can be used for this. this operator always works "case-sensitive".
To avoid this, one must use the lower method.
If you need the position of the found string, use the find method.
str = "one two three" print("two" in str) # True print("two" in str) # False print("two".lower() in str) # True print(str.find("two" )) # 5 print(str.find("twoEgg")) # -1 print(str.lower().find("twoEgg".lower())) # 5 print(str.lower()) # "one two three" print("twoEgg".lower()) # "two"

File operations    +!  advanced content

Read

line by line:
with open("filename") as fileobj: for line in fileobj: print(line)

Individual characters:
with open("filename") as fileobj: for line in fileobj: for ch in line: print(ch)

What if there are no rows?:
with open(filename) as fileobj: while True: c = fileobj.read(1) if not c: print("End of file") break print("Read a character:", c)

pi_digits.txt

romeo_und_juliet.txt Now

let's apply this:
""" with open("romeo_and_juliet.txt") as fileobj: for line in fileobj: #print(line) print(line, end="") """ fileobj = open("romeo_and_juliet.txt") for line in fileobj: print(line.rstrip()) #print(line, end="") # alternatively fileobj.close()

This leads to a very long output:
... For lovers never perished like this: Juliet and her Romeo. (All exit.) End of this project Gutenberg Etextes Romeo and Juliet, by William Shakespeare (Translated by August Wilhelm von Schlegel)

But now we only want to display the found lines:
search = "gift" fileobj = open("romeo_und_juliet.txt") for line in fileobj: if (search in line.lower()): print(line.rstrip()) fileobj.close()

That works better. This runs much faster. Why actually?:
Full of poisonous plants and conducive to recovery. The little flower here harbors poisonous juices And if you say "Yes", this sound poisons...
The screen outputs often take considerably more time than all other calculations and tasks: bottlenecks.

But now we also want the line numbers:
search = "gift" # gift, death, love, verona, nightingale line_num = 1 num = 0 fileobj = open("romeo_und_juliet.txt") for line in fileobj: if (search in line.lower()): print(line_num , line.rstrip()) num += 1 line_num += 1 print() print(num) # print("\n" + str(num)) # alternatively fileobj.close()

This is much more meaningful:
1730 Full of poisonous plants and conducive to recovery. 1745 The little flower here harbors poisonous juices 2905 And if you say "Yes", this sound poisons 3116 So you had mixed no poison, no knife 3483 Oh, did you only find someone who had a poison 3825 How? Were it poison that sly art 3836 The poisonous mouth never breathed pure air into me, 4239 Would someone need poison here, to sell it 4481 In my loved one's hand? 4708 sold him poison with which he would go 11

Write

We now want to record all calls in a log file:
search = "love" # gift, death, love, verona, nightingale line_num = 1 num = 0 fileobj = open("romeo_und_julia.txt") fileobj_append = open("log.txt", "a") # "a" for append. If the file is missing, it will be created. for line in fileobj: if (search in line.lower()): print(line_num, line.rstrip()) num += 1 line_num += 1 print() print(num) # print("\n" + str (num)) # alternative fileobj_append.write(search + " " + str(num) + "\n") fileobj.close() fileobj_append.close()

The log.txt then says:
poison 11 death 61 love 95 verona 11 nightingale 2

Finally, I would like to highlight the sources:
search = "gift" # gift, death, love, verona, nightingale line_num = 1 num = 0 fileobj = open("romeo_und_julia.txt") for line in fileobj: pos = line.lower().find(search) if ( pos > -1): print(line_num, line.rstrip()) print(" "*len(str(line_num)) + " " + " "*pos + "="*len(search)) num += 1 line_num += 1 print() print(num) # print("\n" + str(num)) # alternatively fileobj.close() """ only one occurrence per line is marked. marking all occurrences would be a bit more complicated. " ""

This then creates:
1730 Full of poisonous plants and conducive to recovery. ==== 1745 The little flower here harbors poisonous juices ==== 2905 And if you say "Yes", this sound poisons ==== ...

Writing a list as a csv file    +!  advanced content

The following program writes the content of the list to a file:
fileobj = open("export_list.csv", "w") # "w" for write i.e. writing. # Any existing file will be overwritten list_1 = [ [3,1,True,5.7,"Demo"], [9,1,False,15.27,"Test"], [1,1,True,2.2,"Xyz" ], [4,1,True,4.8,"Pattern"], [8,1,False,9.7,"Abc"] ] for record in list_1: separator = "" for element in record: fileobj.write(separator + str(item)) separator = ";" fileobj.write("\n") fileobj.close() print("The file has been exported.")

The above program writes the following file:
3;1;True;5.7;Demo 9;1;False;15.27;Test 1;1;True;2.2;Xyz 4;1;True;4.8;Pattern 8;1;False;9.7;Abc

Try except    +!  advanced content

The "catching" of exceptions (Exceptions) using try-except.

Let's remember the previous example.
Let's reduce this to the pure reading process.
from datetime import * fileobj_read = open("demo.txt") for line in fileobj_read: print(line.rstrip()) fileobj_read.close()

File operations (read, write, append) may fail.
examples?
You can catch these exceptions like this:
try: fileobj_read = open("demo.txt") for line in fileobj_read: print(line.rstrip()) fileobj_read.close() except: print("The file was not found.") # Alternatively: continue possible?

Result:
The file was not found. >>>

The following also works:
try: fileobj_read = open("demo.txt") for line in fileobj_read: print(line.rstrip()) fileobj_read.close() except Exception as e: print(e)

Result:
[Errno 2] No such file or directory: 'demo.txt' >>>

Saving a list as JSON    +!  advanced content

Saving the list:
import json friends = ["Tina",["Peter",3],"Paul"] friends_json = json.dumps(friends) with open('data.txt', 'w') as outfile: json.dump(friends_json , outfile)

Loading the list:
import json with open('data.txt') as json_file: data_str = json.load(json_file) print(type(data_str)) data = json.loads(data_str) print(type(data)) print(data)

Generated output:
<class 'str'> <class 'list'> ['Tina', ['Peter', 3], 'Paul']

Databases    +!  advanced content

Databases are an important tool for storing data in a structured way over the long term, for processing it and for accessing it efficiently.
In the following example, an SQLite database is used.

"SQLite is a library that implements a self-contained, serverless, zero-configuration, transactional SQL database engine. The code for SQLite is in the public domain and as such can be used for any commercial or personal purpose. SQLite is the most widely deployed database in the world, including several high-profile projects."

With any small adjustments, these programs also work with other databases.

The data of a SQLite database is stored in a ".db" file.

The following program creates a table and removes any previously existing versions. If the employee.db file does not exist, it will be created automatically.
import sqlite3 connection = sqlite3.connect("employee.db") cursor = connection.cursor() # Delete table: cursor.execute("DROP TABLE IF EXISTS tbl_employee;") sql_command = """ CREATE TABLE tbl_employee ( staff_number INTEGER PRIMARY KEY, firstname VARCHAR(20), lastname VARCHAR(30), gender CHAR(1), joining DATE, birth_date DATE);""" cursor.execute(sql_command) print("The table was newly created.")

The following program shows how records are entered into the table.
import sqlite3 connection = sqlite3.connect("employee.db") cursor = connection.cursor() people = [ #firstname, lastname, gender, joining, birth_date ["Max","Muster","m","2016-04-07","2000-01-12"], ["Maria","Muster","f","2016-04-07","2001-11-02"], ["Tom","Taler","m","2017-03-23","1990-05-09"], ["Peter","Maier","m","2011-01-08","2001-01-05"], ["Karin","Müller","w","2017-02-17","2002-06-01"] ] for element in people: cursor.execute("""INSERT INTO tbl_employee (firstname, lastname, gender, joining, birth_date) VALUES ('""" + element[0] + "','" + element[1] + "','" + element[2] + "','" + element[3] + "','" + element[4] + "');") print("Die Sätze wurde eingefügt.") connection.commit() connection.close()

Alternatively, here is a program for manually entering data records.
But that would be cumbersome if more than individual sentences are involved.
import sqlite3 connection = sqlite3.connect("employee.db") # Felder: firstname lastname gender joining birth_date cursor = connection.cursor() while True: firstname = input("Bitte den Vornamen und 'Return' drücken (q=ende): ") if firstname == "q": break lastname = input("Bitte den Nachnamen und 'Return' drücken: ") gender = input("Bitte das Geschlecht (m oder f) und 'Return' drücken: ") joining = input("Bitte das Eintrittsdatum und 'Return' drücken (JJJJ-MM-TT): ") birth_date = input("Bitte das Geburtsdatum und 'Return' drücken (JJJJ-MM-TT): ") sql_command = "INSERT INTO tbl_employee (firstname, lastname, gender, joining, birth_date) VALUES ('"+firstname+"','"+lastname+"','"+gender+"','"+joining+"','"+birth_date+"');" cursor.execute(sql_command) print("Auf Wiedersehen") connection.commit() connection.close()

The output of all data records can be obtained with the following program:
import sqlite3 connection = sqlite3.connect("employee.db") cursor = connection.cursor() print("----------------") cursor.execute("SELECT * FROM tbl_employee") result = cursor.fetchall() for record in result: print(record) print("----------------") connection.close()

The following program deletes all records from the table:
import sqlite3 # Delete all records connection = sqlite3.connect("employee.db") cursor = connection.cursor() cursor.execute("delete FROM tbl_employee") connection.close() print("All records have been deleted.")

The following program imports data records from the csv file import.csv and writes them to the table:
import csv import sqlite3 with open("import.csv", "r") as file: import_list = csv.reader(file, delimiter = ";") # Read data from file connection = sqlite3.connect("employee.db ") cursor = connection.cursor() for element in import_list: print(element) sql = """INSERT INTO tbl_employee (firstname, lastname, gender, joining, birth_date) VALUES ('""" + element[0] + " ','" + element[1] + "','" + element[2] + "','" + element[3] + "','" + element[4] + "');" print(sql) cursor.execute(sql) # Insert record into database print("Records have been inserted.") connection.commit() connection.close()

Example of a csv file used.
Peter;Berger;m;2017-04-01;2002-03-02 Lisa;Müller;w;2020-02-01;2001-09-17 Thomas;Bauer;m;2020-04-07;2005-04- 11 Paula;Adler;f;2019-08-04;2001-02-19 Karl;Kummer;m;2018-10-30;1990-11-10 Berta;Auer;f;2017-12-31;2000-01 -27 Horst;Maier;m;2019-06-17;2003-02-15

Example of a csv export from the database:
import sqlite3 fileobj = open("export.csv", "w") connection = sqlite3.connect("employee.db") cursor = connection.cursor() cursor.execute("SELECT * FROM tbl_employee") result = cursor. fetchall() for record in result: fileobj.write(str(record[0])+";"+record[1]+";"+record[2]+";\ "+record[3]+"; "+record[4]+";"+record[5]+"\n") fileobj.close() connection.close() print("The file was exported.")
Note that the "\" character was used to break the line.
Python then automatically reads on to the next line and the break has no meaning for the logical structure of the program.

This is an example of the export.csv file created in this way:
1;Max;Sample;m;2016-04-07;2000-01-12 2;Maria;Sample;f;2016-04-07;2001-11-02 3;Tom;Taler;m;2017-03- 23;1990-05-09 4;Peter;Maier;m;2011-01-08;2001-01-05 5;Karin;Müller;w;2017-02-17;2002-06-01 6;Peter;Berger ;m;2017-04-01;2002-03-02 7;Lisa;Müller;w;2020-02-01;2001-09-17

Of course you can also merge all program parts into one file and then you already have the basic framework for a complete application.

SQLite can also be managed using a graphical interface:
You would have to add:
The sqlite database shown above is a great option for small projects or to get started quickly, but when sqlite reaches its limits, you should switch to a real server database. Below is shown how to connect to a mySQL or MariaDB database.
Adjust the connection data accordingly: user, password, host, database).
In the case below, the connection is made to the so-called localhost (127.0.0.1). That means the database runs on the same computer as Python. Of course that doesn't have to be the case.
In order for this to work, the user used (in our case connnect_user) must have permission to connect. If you do not want to connect from the same computer (localhost) but from a remote computer (remote), you must have your own additional authorization for this user.
Danger! To import the mysql module as shown below, you need to install the module beforehand.

To do this, open a Windows command line but in administrator mode:
Command line admin

Then enter the following in the window:
C:\Users\python_fan>pip install mysql

Window key > cmd > right click on the command line icon
              > Run as administrator
              > pip install mysql

Installation may fail if you are not in administrator mode.

import mysql.connector connection = mysql.connector.connect(user='connnect_user', password='!dE3rZ?%', host='127.0.0.1', database='mydb') cursor = connection.cursor() # table delete: cursor.execute("DROP TABLE IF EXISTS tbl_employee;") sql_command = """ CREATE TABLE tbl_employee ( staff_number INTEGER PRIMARY KEY, firstname VARCHAR(20), lastname VARCHAR(30), gender CHAR(1), joining DATE, birth_date DATE);""" cursor.execute(sql_command) print("The table was newly created.") connection.close()

The following example shows the connection to a Microsoft Access database. The mydb.accdb file must exist at the specified path.
import pyodbc conn = pyodbc.connect(r'Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\python\db\mydb.accdb;') cursor = conn.cursor() cursor .execute('select * from tbl_employee') for row in cursor.fetchall(): print (row) conn.close()
Before running, install the pyodbc module using "pip install pyodbc" as shown above.
Use a Windows command line in administrator mode again.

You can create the table in the Access database beforehand using the following SQL script and then fill it:
CREATE TABLE tbl_employee ( staff_number INTEGER PRIMARY KEY, firstname VARCHAR(20), lastname VARCHAR(30), gender CHAR(1), joining DATE, birth_date DATE);

In the above case, the connection was established via an ODBC (Open Database Connectivity) interface. In addition to installing and importing the pyodcb module, 2 requirements must be met for this:

Web services with Python    +!  advanced content

...

classes    +!  advanced content

In contrast to Java, you don't always have to program object-oriented in Python. But of course, as a modern language, Python also supports the object-oriented paradigm.

disambiguation

Classes are blueprints for objects. With the help of a "constructor" (a special function that can also have parameters) a so-called object instance is created at runtime. The constructor function has the same name as the class (see for example the Person() function in the example below). There can be many instances of a class at a time. Classes are relevant at design time, objects at runtime.
What is an object?
An object consists of attributes and methods. The attributes contain the data of the object. The methods can read or write this data and return it directly or results derived from it.
An important property of objects is that an object can hide part of its internal structure and state from the outside. There can be so-called private attributes or methods which are not or not directly accessible from the outside (outside the object).
The practical thing about classes is that you usually don't need to know the exact implementation of a method. It is sufficient if one understands what the method does.

motivation

In Python, all data types have classes behind them. This is why you can also use the "pets.sort()" call on the object instance to call the associated method for the "pets" list. We are already familiar with this spelling from the way it is used. So a simple explanation for objectorized programming is to say that you can use classes to create your own data types.

For example, let's look at the following program:
import datetime class Person: def __init__(self, name, birth_year, birth_month, birth_day): self.name = name self.birth_year = birth_year self.birth_month = birth_month self.birth_day = birth_day def get_age(self): today = datetime.date.today() birthday = datetime.date(self.birth_year,self.birth_month,self.birth_day) current_birthday = datetime.date(today.year, birthday.month, birthday.day) if today < current_birthday: return today.year - birthday.year - 1 else: return today.year - birthday.year p1 = Person("John", 2000, 1, 1) print(p1.get_age())

Explanation:
The definition of a class starts with the "class" keyword. The "__init__" method is used for initialization.
name, birth_year, birth_month, birth_day are the attributes in this class. They contain the data of the object. get_age is a method of the object.

Attention!:
The parameter "self" has a special meaning. It can be used to access the current object instance. Every class method (including init) must have this parameter and by convention the name "self" is usually used, but this is not mandatory.
So in the init method, "self" refers to the newly created object. In other class methods, it refers to the instance whose method was called.

In our case, however, init has other parameters, namely names and dates of birth. The passed values ​​are assigned to the object using the "self" variable.
The get_age method uses these values ​​to get the person's age.
Finally, in the main program, an object instance (or object for short) of the class is created using the "Person()" constructor. When the object is created, the init method is automatically called and the constructor's parameters are passed to it. Then the get_age method is called to determine and output the person's age.

Abstract data types    +!  advanced content

An abstract data type is a composite of data along with the definition of all legal operations that access it. It is striking that the definition of an abstract data type is closely related to object-oriented programming. In fact, abstract data types are a strong motivation for using classes and can be implemented very well with them. However, this is not necessarily the case and abstract data types also exist in classic (non-object-oriented) programming.
Stack and queue are presented here as examples.

Stack / stack memory

A stack is also known as a LIFO (Last-In-First-Out) data structure. The last item entered is the first item output.

The following program uses a stack to parse a bracketed expression. If an opening parenthesis is detected, then it is saved on the stack. If a closing bracket is recognized, a corresponding opening bracket must be at the top of the stack.
If the expression contains only one kind of parenthesis, you wouldn't necessarily need the stack approach; a counter would suffice, recording how many parentheses are open. The way chosen here has the advantage that the method can be extended to more complicated expressions and different types of brackets ("()","[]","{}").
import sys class Stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return self.items[len(self.items)-1] def size(self): return len(self.items) stack = Stack() expression = input("Bitte gib einen Klammernausdruck ein (zb '(((())))()(())'): ") for ch in expression: if ch == "(": stack.push(ch) elif ch == ")": if stack.isEmpty(): print("Kein gültiger Klammernausdruck.") sys.exit() elif stack.pop() != "(": print("Kein gültiger Klammernausdruck.") sys.exit() if stack.size() == 0: print("Gültiger Klammernausdruck.") else: print("Kein gültiger Klammernausdruck.")

Queue / Warteschlange

A queue or queue is also referred to as a FIFO (First-In-First-Out) data structure. The first item entered is the first item output.

The following small program simulates a typical application of a queue: the waiting room of a doctor's office. Each new arriving patient is entered in the queue. Patients are treated in the order of their arrival.
class Queue: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def enqueue(self, item): self.items.insert(0,item) def dequeue(self): return self.items.pop() def size(self): return len(self.items) def show(self): print(self.items) def neuer_patient_trifft_ein(name): wartezimmer.enqueue(name) anzahl = wartezimmer.size() if anzahl > 10: nachricht = "Tut mir leid " nachricht += name nachricht += " die Wartezeit beträgt mindestens " nachricht += str(anzahl * 10) + " min." print(nachricht) def naechster_patient_ist_dran(): if wartezimmer.size() == 0: print("Das Wartezimmer ist leer.") else: print(wartezimmer.dequeue() + " bitte ins Behandlungszimmer eintreten.") waiting room = Queue() while True: print("1: new patient arrived 2: next patient's turn") print("3: show waiting room q: end") command = input("Please choose an option: ") if command == "1": name = input("Name of the arriving patient?: ") new_patient_arrives_in(name) elif command == "2": next_patient_is_turn() elif command == "3": waiting room.show() elif command = = "q": print("Thank you for using MediSoft waiting room software.") break else: print("Please enter only 1, 2, 3 or 'q'.")

error types

lexical errors

Examples: Program code with a lexical error is not executable.

syntactic errors

Such an error occurs when all the words have been spelled correctly, but there is an error in the program structure. Examples:

language comparison

Syntactic errors are similar to grammatical errors. All words are spelled correctly but the sentence structure is not correct.
"Close your book."
This case cannot be found by a word-related spell check, but by a grammatical check of the sentence. A syntax check can also be carried out for programs.

Program code with a syntactical error is not executable.

semantic errors

All words are spelled correctly and the program structure is correct. However, a program construct was used incorrectly and not in accordance with its actual meaning. In the program code, for example, wrong variables are accessed, wrong operations are used, transfer parameters are passed in the wrong order. Other possible reasons are:

language comparison

Words are spelled correctly. Sentences are structured correctly but are not used with their real meaning. The sentence doesn't make any sense.
"The time is green."
"The hammer eats grass."
Semantic errors are harder to find than syntactic errors. However, a compiler or interpreter may very well contain a semantic check. Program code with a semantic error is executable. However, the program does not behave as desired. Errors occur. The program may terminate unintentionally with an error message or the program may crash. The program may deliver incorrect, meaningless results.

logical errors

A program that contains such an error is structurally correct. The program run is also undisturbed and no errors occur. The only problem with logical errors is that they don't deliver the correct results or that the program flow is different than desired. However, the deviating results are not meaningless values, as in the case of semantic errors; they deliver meaningful results but not the desired ones because the programmer used the wrong formula or filled it in incorrectly, for example because he was wrong in the order of the operators.

Logical errors are errors of the programmer.
def mean(a, b): return a + b / 2 # correct would be (a + b) / 2 print(mean(2.0,4.0)) # desired would be: 3.0 output: 4.0 print(mean(1.0,4.0) ) # would be desired: 2.5 output: 3.0

In the example above, the mean value of two transfer parameters should be calculated, which also indicates the meaningful naming. However, due to a programmer error, the wrong result is delivered.

language comparison

Words are spelled correctly. Sentences are structured correctly and all terms are used in a meaningful context but not in the desired one. In the following case, an English tourist says:
"On the way here I saw an ambulance"
, meaning an ambulance, but the listener thinks of a clinic for medical emergencies. Logical errors can be very subtle and then even harder to find than semantic errors.

Programs with logical errors are executable and they do not generate any error messages, they provide meaningful results but not the desired ones.
All types of errors are shown again in the graphic below.

error types

Effects of Errors

Above we classified the bugs strictly from a programming point of view. Now let's categorize them by their impact:

syntax error

These prevent code execution.
Whether in the Python shell or in IDLE, when trying to start a Python program with a syntax error, a window opens with a corresponding message and the offending point in the program is highlighted.

Runtime error

These are also called "bugs" like the insect. They occur during a program run. Runtime errors are often but not exclusively caused by semantic errors. Runtime errors can have the following undesirable effects:

Exceptions

An exception is reported by the system at runtime and it can be caused by a runtime error (=bug). Division by 0 throws the following exception:
>>> Traceback (most recent call last): File "C:\Python34\error.py", line 10, in x = 1/0 ZeroDivisionError: division by zero >>>

But beware!
An exception can also be caused by a so-called expected exceptional situation. What is that? Let's take the following exception as an example. It was caused because a file named "workfile" could not be opened for some reason:
>>> Traceback (most recent call last): File "C:/Python34/file_open.py", line 1, in f = open('workfile', 'r') FileNotFoundError: [Errno 2] No such file or directory: 'workfile' >>>

But this can have various causes. An incorrect path specification by the programmer would be a bug. But if, for example, someone has accidentally removed this file or perhaps the storage medium cannot be read, then this is not a bug, but the expected exceptional situation mentioned above.

You can also "catch" expected exceptions. You can carry out exception handling, for example you can inform the user about what didn't work and then terminate in a controlled manner, or you ask the user to provide a remedy and then try to execute the problematic part again.

Incorrect results

The program seems to work, it also delivers results, but these do not correspond to the values ​​in the specification. This could be due to a logical error in the program.

The program does not run as desired

The program does not generate any errors and does not provide incorrect results, but the observable program behavior deviates from the specifications. For example, the program generates output where it shouldn't and where it shouldn't.

debugging

Eliza in Python Demo

All programs as a zip file zip icon
Other programszip icon

resources

examples and solutions

ecdl_computing_solutions.zip

Free Books

Think Python
Byte of Python

"cheat sheets":

Beginner's Python Cheat Sheet
http://learnpython.org/

Left

CheckiO is expanding the world's code literacy through game play:
https://checkio.org/

Beginner Python exercises:
http://www.practicepython.org/

thenewboston

CodingBat is a free site of live coding problems to build coding skill in Java and Python:
http://codingbat.com/python

BUILD AND DEPLOY IN SECONDS, Instant Serverless Computing Platform:
https://repl.it/

Codester's Python Coding Platform:
https://www.codesters.com/coding-platform/

Solo Learn, Everyone Can Code:
https://www.sololearn.com/Codes?ordering=Trending&language=py

Google's Python Class:
https://developers.google.com/edu/python/

Think Python:
http://greenteapress.com/wp/think-python/

Python-programming-exercises

Python Fiddle:
http://pythonfiddle.com/

PyFiddle is a free lightweight Python IDE to run and share Python scripts:
https://pyfiddle. io/

We host a growing number of Open Source, interactive textbooks you can use in a course.
Written by award winning authors. Used by some of the best schools:
http://interactivepython.org/

Put Interactive Python Anywhere on the Web:
https://trinket.io/python

fiddle
x^^