Home » Uncategorized » Python (Merkpunkte für den Java-Gewohnten)

Python (Merkpunkte für den Java-Gewohnten)

Contents

Hierarchy of Online Resources

–> From Udacity training: Hierarchy of Online Resources

Ausführung

Python ist normalerweise im Windows enthalten. Also: Konsole öffnen, dann python eintippen und schon wartet der Python-Interpreter auf deine Kommandos.

Fancy Interpreter: Wenn der Standard Interactive Interpreter nicht genügt, wäre IPython eine konfortablerer Alternative.

Operators

Speziell:

CodeBedeutung
x**2x hoch 2

Variables and Assignment Operators

Variablen müssen nicht mit Typ deklariert werden.

CodeBedeutung
x, y, z = 3, 4, 5Werte werden der Reihe nach den variablen x, y, z zugeordnet.
i = 1Definition eines Int
f = 1.0Definition eines Float
i1 = int(f)Umwandlung Float zu Int
f1 = float(i)Umwandlung Int zu Float
boolNot ‚boolean‘!
type(i)Typenprüfung
print(type(x))Drucken des Typen
> print(.1 + .1 + .1 == .3)
False
Float hat nur diskrete Werte, kann also 0.1 nicht genau abbilden!
not (i1 > i2 or (i3 == i4 and i4 != i5))boolean expression demo 🙂

String

CodeBedeutung
this_string = 'Simon\'s skateboard is in the garage.'
this_string2 = "Simon\'s skateboard is in the garage.
String demo
>>> print("Hello" * 5) HelloHelloHelloHelloHello
>>> print(len("Hanspeter"))
9

„Hanspeter“[2]
–> „n“

print(‚Hanspeter ist so lang: ‚ + str(len(‚Hanspeter‘)))
Hanspeter ist so lang: 9
Int zu String Konvertierung
Nötig bei Print-Ausgabe
>>>my_string = „ab“
>>> my_string.islower()
True
>>> my_string.count('a')
2
>>> my_string.find('a')
3

firstName, lastName = „Max“, „Muster“
„Hello! My name is {} {}„.format(firstName, lastName)

String Interpolation Demo
>new_str = "The cow jumped over the moon." >new_str.split()
['The', 'cow', 'jumped', 'over', 'the', 'moon.']
Split demo.
A list is created.
new_str.split('.')Split with ‚.‘ as delimiter.
>“Nomen est omen“.find(‚om‘)
1
erstes Vorkommen finden
>“Nomen est omen“.rfind(‚om‘)
10
letztes Vorkommen finden
>“Nomen est omen“.count(‚omen‘)
2
Anzahl Vorkommen eruieren

Lists

CodeMeaning
list_of_random_things = [1, 3.4, 'a string', True]Listen könnne heterogenen Inhalt haben!
>>> list_of_random_things[0]
1
>>> list_of_random_things[-1]
True
Letztes Element der Liste selektieren!
>>> list_of_random_things = [1, 3.4, 'a string', True]
>>> list_of_random_things[1:2]
[3.4]
Range einer Liste extrahieren
>>> list_of_random_things[2:]
['a string', True]
End-Range einer Liste extrahieren
>>> list_of_random_things[:2]
[1, 3.4, 'a string']
Anfangs-Range einer Liste extrahieren
>>> 'this' in 'this is a string'
True
>>> 'in' in 'this is a string'
True
>>> 'isa' in 'this is a string'
False
>>> 5 not in [1, 2, 3, 4, 6]
True
>>> 5 in [1, 2, 3, 4, 6]
False
‚in‘ / ’not in‘ demo
len(list) returns how many elements are in a list.
max(list)returns the greatest element of the list. How the greatest element is determined depends on what type objects are in the list. The maximum element in a list of numbers is the largest number. The maximum elements in a list of strings is element that would occur last if the list were sorted alphabetically. This works because the the max function is defined in terms of the greater than comparison operator. The max function is undefined for lists that contain elements from different, incomparable types.
min(list) returns the smallest element in a list. min is the opposite of max, which returns the largest element in a list.
sorted(list)returns a copy of a list in order from smallest to largest, leaving the list unchanged.
„-„.join([„Anna“, „Maria“])
‚Anna-Maria‘
Join List Demo
>>>letters = ['a', 'b', 'c', 'd'] >>>letters.append('z') >>>print(letters)
['a', 'b', 'c', 'd', 'z']
Hinzufügen von objekten in die Liste
list1 = [„Hans“, „Karl“, „Guido“]
for s in enumerate(list1):
… print(s)

(0, ‚Hans‘)
(1, ‚Karl‘)
(2, ‚Guido‘)
Enumerate-Demo
Erstellen eines Iterable über Tupels, wobei das Tupen eine Fortlaufenden Sequenzunummer und den jeweiligen Wert aus der Liste enthält.
cities = [„amsterdam“, „paris“, „berlin“]
capitalizedCities = city.title() for city in cities
List Comprehension Demo
Action Block, Laufvariable, behandelte Liste
even_squares = n**2 for n in range(9) if n**2%2==0List Comprehension Demo mit Condition
nonsensList = n**2 if n%2 == 0 else „-„ for n in range(9)List Comprehension Demo mit Condition and Else value
list(iterator)Liste aus Iterator erstellen

Tuple

CodeMeaning
t1 = („Max“, „Muster“, „Zürich“) Tupel erstellen
t2 = „Max“, „Muster“, „Zürich“Tupel erstellen
vn, nn, ort = t1Tupel auspacken 1
vn = t1[0]Tupel auspacken 2
t1[2] = „Zürich“
Traceback (most recent call last):
File „“, line 1, in
TypeError: ‚tuple‘ object does not support item assignment
Tupel ist immutable?
listOfTupels = zip(listA, listB)Zip Demo
Erstellen eines Iterable über Tupels die jeweils einen Wert aus beiden Ursprungslisten enthalten.
for t in zip([„Karl“, „Lagerfeld“], [„Heidi“, „Klum“]):
… print(t)

(‚Karl‘, ‚Heidi‘)
(‚Lagerfeld‘, ‚Klum‘)
Zip example
Erstellen eines Iterable über Tupels die jeweils einen Wert aus beiden Ursprungslisten enthalten.

Sets

CodeMeaning
set1 = {„Hans“, „Karl“, „Guido“}Set erstellen
>list1 = [„Hans“, „Karl“, „Guido“, „Hans“]
>set2 = set(list1)
>set2
{‚Karl‘, ‚Guido‘, ‚Hans‘}
Set aus Liste erstellen
set2.add(„Hermann“)Hinzufügen

Dictionaries (Maps)

CodeMeaning
elements = {"Karl": 1, "Mark": 2, "John": 6}Set erstellen
print(elements["John"]) Zugriff
elements[„John“] = 77Update
>elements[„Inexisting_Name“]
Traceback (most recent call last):
File „“, line 1, in
KeyError: ‚Inexisting_Name‘
Error bei nicht gefundener Key
Besser:
>v1 = map1.get(‚Inexisting_Name‘)
>print(v1)
None
Oder (mit Default):
v1 = map1.get(‚Inexisting_Name‘, 99)
print(v1)
99
print(map1)
{‚Hans‘: 1, ‚Peter‘: 2}
>"Inexisting_Name" in elements
False
Präsenz-Test
map1[„Hermann“]
Traceback (most recent call last):
File „“, line 1, in
KeyError: ‚Hermann‘

Generators

Generators werden benutzt um einen Iterator zu definieren. Dazu wird eine Funktion programmiert, die yield Statements enthält. Der basierend auf dieser Funktion definierte Iterator durchläuft die Funktion dann bei jedem Next-Aufruf eine yield -Position weiter.

-> Udacity Explaination

Control Flow

CodeMeaning
if a > b:
doSomething()
!Der Block ist limitiert zu beginn durch das ‚:‘ und zum ende durch die Leerzeile!
Zeileneinzug ist obligatorisch!
if a > b:
doSomething()
elif a = b:
doSthOther()
else
for i in array1:
doSomething()
For-Loop-Demo
range(start, end[, stepWidth])
>for(i in range(1, 9)):
> print(i**2)
1
4
9
for k in dictionary: Keys der Map holen
for k,v in dict.items(): Key/Value Items der Map holen
for v in dict.values(9:Values der Map holen
while <condition>:
doSomething()
While-Loop-Demo
try:
# some code
except (ValueError, KeyboardInterrupt): # some code
finally
# some code
Try-Catch:
Except ohne Error-Angabe möglich
Mehrere Except-Blöcke mit unterschiedlichen Prozeduren möglich
try:
# some code
except Exception as e:
print("ZeroDivisionError occurred: {}".format(e))
Error-Message benutzen

Functions

CodeMeaning
>def cyl_vol(height, radius=5):
> return height * PI * radius**2
>
>cyl_vol(10)
785.72425
Function definition mit Defaultwert-Vorgabe
cyl_vol(radius=2, height=10)
Equivalent:
dyl_vol(10, 2)
call with named parameters
def cyl_vol(height, radius=5):
„““Berechnet das Zylinder-Volumen
INPUT:
height: float, höhe des Zylinders
radius: float, radius des Zylinders
OUTPUT:
float, berechnetes Volumen
„““
return height * PI * radius**2
Methoden-Dokumentation
height, radius: height * PI * radius**2Lambda definition
map(function, iterable)Map Definition
cities = [„amsterdam“, „berlin“, „rome“]
capitalized_cities = map(lambda c: c.title(), cities)
Map Demo
filter(filter_fn, iterator)Filter Definition
cities = [„amsterdam“, „berlin“, „rome“]
a_cities = filter(lambda c: c[0]==’a‘, cities)
Filter Demo

Scope:
Globale Variablen können nicht innerhalb einer Funktion verändert werden.

Scripting

CodeMeaning
>python script1.pyPython-Script ausführen
a = input(„Gib eine Zahl:“)
aQuadrat = int(a)**2
Einen wert von der Konsole einlesen
print(eval(„3**3“))
27
Eval-Funktion: Ein String wird als Python-Code interpretiert.

Files I/O

CodeMeaning
f = open('my_path/my_file.txt', 'r') file_data = f.read()
f.close()
Opening and reading a file
with open('my_path/my_file.txt', 'r') as f: file_data = f.read()… alternatively (including the close op)
f = open('my_path/my_file.txt', 'w') f.write("Hello there!") f.close()Write to a file (erases the preliminarlily existin content!)
# Open a file with access mode ‚a‘
file_object = open(’sample.txt‘, ‚a‘)

# Append ‚hello‘ at the end of file
file_object.write(‚hello‘)

# Close the file
file_object.close()
Append to an existing file
camelot_lines = []
with open("camelot.txt") as f:
for line in f:
camelot_lines.append(line.strip())
print(camelot_lines)
Read file, line by line
f = open('my_path/my_file.txt', 'r') file_data = f.readLine()
f.close()
.. alternatively

Imports/Libraries/Modules

CodeLabel
#This is a library file
def doSth():
# some code

def main():
# Code that runs only if this file is called directly by
# >python libraryfile.py
# –> see below how / when this function is called!

#Trick to evaluate if this file is called directly by
# >python libraryfile.py and only then call main()
if __name__ == '__main__':
main()
Library definition
(Trick to code main part there that is only called when it runs as root)
import useful_functions as uf

mean = uf.mean(scores)
Import of library in Main file

‚as uf‘ is optional
import random

print(random.randint(1,10))
Import der standard Random library
from ranwom import randint as rdInt
import doSth from sillylib
Similar as in Java:
import static com.lib.Myclass.doSth;
from mylib import *Do not use this!
import os.path
os.path.isdir(„mypath“)
Importing a Submodule or a Module
from datetime import datetimeImports a class from a module (both having the same name)
>python
>>>import myscript as my
>>>from myother import MyEntityClass, db
MyEntityClass.query.all()
Imports können selbstvertändlich auch innerhalb der python interaktiven Konsole gemacht werden. Damit ein eigenes File importiert werden kann, muss dessen Mame Python-Kompatibel sein (z.B. keine ‚-‚)
Import ohne „.py“-Endung!
Python Standard Libraries
vs.
3rd Pary Libraries
Usefull 3rd-Party Libraries
PipStandard Phython Package Manager
AnnacondaPython Package Manger specifically designed for Data Science
pip install package_namePackage ‚package_name‘ installieren
Danach kann es genau wie Python Standard Libs im Code benutzt werden.
requirements.txt:
meineLibrary==1.2.5
andereLibrary==9.30.3

>pip install -r requirements.txt
Definition aller Dependencies in einem Requirments-File und installieren derselben via PIP.


Hinterlasse einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert