Add 01_python_allgemein
This commit is contained in:
219
python/01_python_allgemein.md
Normal file
219
python/01_python_allgemein.md
Normal file
@@ -0,0 +1,219 @@
|
||||
Python ist **intepretiert** und **interaktiv**, **dynamisch**, **highlevel**, **Objektorientiert**, **strukturiert**, **Aspektorientiert**, **Funktional (Beweisbarkeit)** -> Reference Counting
|
||||
|
||||
| Interpreter | Compiler |
|
||||
| ----------------------- | ------------------------------------------------ |
|
||||
| Zeile für Zeile | Übersetzt den ganzen Code auf einmal -> Bytecode |
|
||||
| Keine ausführbare Datei | Ausführbare Datei |
|
||||
| Fehler werden gezeigt | Fehler werden gesammelt und dann angezeigt |
|
||||
|
||||
### Codingstandards
|
||||
|
||||
**Zen of Python**
|
||||
|
||||
Mit `import this` erscheint das Zen of Python
|
||||
|
||||
**Beautiful is better than ugly.**
|
||||
Explicit is better than implicit.
|
||||
**Simple is better than complex.**
|
||||
Complex is better than complicated.
|
||||
Flat is better than nested.
|
||||
Sparse is better than dense.
|
||||
**Readability counts.**
|
||||
Special cases aren't special enough to break the rules.
|
||||
Although practicality beats purity.
|
||||
**Errors should never pass silently.**
|
||||
Unless explicitly silenced.
|
||||
In the face of ambiguity, refuse the temptation to guess.
|
||||
There should be one-- and preferably only one --obvious way to do it.
|
||||
Although that way may not be obvious at first unless you're Dutch.
|
||||
Now is better than never.
|
||||
Although never is often better than *right* now.
|
||||
**If the implementation is hard to explain, it's a bad idea.**
|
||||
**If the implementation is easy to explain, it may be a good idea.**
|
||||
Namespaces are one honking great idea -- let's do more of those!
|
||||
|
||||
**PEP8**
|
||||
|
||||
**Package:** lowercase
|
||||
**Module:** my_module.oy
|
||||
**Function:** my_function
|
||||
**Variable:** my_variable
|
||||
**Class:** MyClass
|
||||
**Method:** my_method
|
||||
**Exception:** HTTPSServerError
|
||||
**Constant:** HELLO_WORLD
|
||||
|
||||
Mit `type()` kann man den Datentyp auslesen. Mit `del()` kann man Variabeln löschen. Mit `hex()` erhalten wir die Hex des Wertes.
|
||||
|
||||
### Datentypen
|
||||
|
||||
**Numbers**
|
||||
- Bool (true, false)
|
||||
- Int (1, 2)
|
||||
- Float (1,234)
|
||||
- Complex (4j)
|
||||
|
||||
![[numbers_datatype.png]]
|
||||
|
||||
- [ ] Boolean, wenn Zahl höher ist
|
||||
|
||||
**Sequences**
|
||||
|
||||
![[sequences_datatype.png]]
|
||||
|
||||
#### Listen
|
||||
|
||||
Listen sind veränderbar.
|
||||
```
|
||||
my_list = [1, 2, "HelloWorld"]
|
||||
my_list[0]
|
||||
```
|
||||
|
||||
`reverse`
|
||||
`clear`
|
||||
`copy`
|
||||
`count`
|
||||
`extend`
|
||||
`index`
|
||||
`insert`
|
||||
`remove`
|
||||
#### Tuples
|
||||
|
||||
Nicht veränderbar nur auslesen ist erlaubt
|
||||
```
|
||||
tup = ("Test", 1, 4, False)
|
||||
```
|
||||
|
||||
**Settypes**
|
||||
|
||||
|
||||
![[settypes_datatype.png]]
|
||||
|
||||
#### Sets
|
||||
|
||||
Sind Sets ohne Duplikate
|
||||
|
||||
```
|
||||
colors = set(["blue", "red", "green"])
|
||||
colors = {"hello", "world"}
|
||||
colors.add("Hello")
|
||||
```
|
||||
#### Frozensets
|
||||
|
||||
Frozensets sind sets, die nicht Veränderbar sind
|
||||
|
||||
```
|
||||
colors2 = frozenset(["blue", "red", "green"])
|
||||
```
|
||||
|
||||
**Mappings**
|
||||
|
||||
![[mappings_datatype.png]]
|
||||
|
||||
#### Dictionary
|
||||
|
||||
```
|
||||
de_en = {"Milch" : "Milk", "Mehl" : "Flour"}
|
||||
print(de_en["Milch"])
|
||||
```
|
||||
|
||||
Zugriff key:value
|
||||
### Rechenoptionen
|
||||
|
||||
```
|
||||
Grundoperationen: +, -, *, /
|
||||
Gruppierung: ()
|
||||
Potenz: **
|
||||
Floor division: // -> Wieviel mal die Zahl hinein passt
|
||||
Modulo: %
|
||||
```
|
||||
|
||||
### Kontrollstrukturen Schleifen
|
||||
|
||||
If Schleifen werden wie folgt geschrieben:
|
||||
|
||||
```
|
||||
if "Milch" in de_en:
|
||||
print("Milch vorhanden")
|
||||
elif "Mehl" in de_en:
|
||||
print("Mehl vorhanden")
|
||||
else:
|
||||
print("Der Wert wurde nicht gefunden")
|
||||
```
|
||||
|
||||
For Schleifen, wobei `range(von,bis,schrittgrösse)` Wobei 5 Exklusiv ist.
|
||||
|
||||
```
|
||||
for i in range(5):
|
||||
print(i)
|
||||
|
||||
for value in de_en.values():
|
||||
if value == "Milk":
|
||||
print("Milk vorhanden")
|
||||
```
|
||||
Mit `break` wird der Loop beendet und mit `continue` überspringt er den restlichen Teil des Codes und macht mit der nächsten Iteration weiter.
|
||||
|
||||
### Funktionen
|
||||
|
||||
Grundregel: Alles was mindestens 2x gebraucht wird, sollte in eine funktion geschrieben werden. Funktionen können Optional Parameter haben und nur in der Funktion gültige Variabeln. Sie können auch einen Wert zurückgeben.
|
||||
|
||||
```
|
||||
def fun(x:int):
|
||||
"""This function returns the square of x"""
|
||||
return x**2
|
||||
|
||||
print(fun.__doc__)
|
||||
```
|
||||
|
||||
Funktionen können eine Anzahl an unbestimmten Funktionen erhalten, aber jedoch nur **einen Wert** unter anderem auch eine Liste zurückgeben.
|
||||
|
||||
**\*args:** Beliebige Argumente als Tupel
|
||||
**\*\*kwargs:** Beliebige Keyword Argumente
|
||||
|
||||
```
|
||||
def summe(*args):
|
||||
"""Berechnet die Summe aller übergebenen Zahlen."""
|
||||
total = 0
|
||||
for zahl in args:
|
||||
total += zahl
|
||||
return total
|
||||
```
|
||||
|
||||
```
|
||||
def print_info(**kwargs):
|
||||
"""Gibt die Schlüssel-Wert-Paare aus dem übergebenen Dictionary aus."""
|
||||
for key, value in kwargs.items():
|
||||
print(f"{key}: {value}")
|
||||
```
|
||||
### Rekursionen
|
||||
|
||||
Wiederaufruf von der eigenen Funktion, bis zur Erfüllungsbedienung vom Basisfall.
|
||||
|
||||
```
|
||||
def fakultaet(n):
|
||||
if n == 0:
|
||||
return 1
|
||||
else: # Rekursiver Fall
|
||||
return n * fakultaet(n-1)
|
||||
|
||||
print(fakultaet(5))
|
||||
```
|
||||
### Exception
|
||||
|
||||
Errorhandling in Python wird ähnlich wie bei anderen Sprachen gemacht, ausser statt **catch** mit **except** abgebildet.
|
||||
|
||||
Das **else** wird nachdem try ausgeführt jedoch nicht nachdem except und das **finally** wird in jedem Fall ausgeführt.
|
||||
|
||||
```
|
||||
while True:
|
||||
try:
|
||||
x = int(input("Please enter a number: "))
|
||||
except ValueError:
|
||||
print("Oops! That was no valid number. Try again...")
|
||||
else:
|
||||
print("You entered: ", x)
|
||||
break
|
||||
finally:
|
||||
print("Thank you for using this program.")
|
||||
```
|
||||
|
||||
Reference in New Issue
Block a user