Python

Output “Hello World”: print(“Hello World”)

print “YES” if 5 is larger than 2: if 5 > 2: print(“YES”)

Kommentar: #Dies ist ein Kommentar

Mehrzeiliger Kommentar: ‘’’ Dies ist ein Kommentar In mehreren Zeilen Geschrieben ‘’’

Variable: Automodell = “Volvo”

Global: global x

int: 5 (ganze Zahlen)

str: “Text”

float: 20.5 (Kommazahlen)

Liste: list = […,…,…]

Tuple: tuple = (…,…,…)

Dict: dict = {“Name” : “Jana”, “Alter” : 22}

bool: bool = True

complex: len: fruits = […,…,…] print(len(fruits))

first character of the string txt: txt = “Hello World” x = txt[0]

index 2 to 4: x = txt[2:5]

string without any whitespace at the beginning or the end: txt.strip()

txt to upper case: txt = txt.upper()

txt to lower case: txt = txt.lower()

ersetze H mit J: txt = txt.replace(“H”,”J”)

placeholder: age = 36 txt = “Mein Name ist Jana, ich bin {} Jahre alt“ print(txt.format(age))

replace in list: fruits[0] =“kiwi“

insert to add „lemon“ as the second item fruits.insert(1, “lemon”)

add to the set: fruits = {“…”, “…”,”…”} fruits.add(“…”)

correct method to add multiple items: fruits.update(more_fruits)

discard method to remove from the set: fruits = {…,…,…} fruits.discard(“…”)

get method to print the value of the “model” key of the car dictionary: car = {“brand”:”…”,“model”:”…”,“year”:…} Print(car.get(“model”))

Change the year: car[“year”] = …

add key/value pair to dictionary: car[“color”] = “red”

pop method to remove “model” from the car dictionary: car.pop(“model”)

clear method to empty the car dictionary: car.clear()

one line short hand syntax: print(“YES”) if a == b else print(“NO”)

loop trough the items in the fruits list: for x in fruits: print(x)

range function to loop trough a code set 6 times: for x in range(6): print(x)

lambda function: takes one parameter and returns it x = lambda a:a

execute printname method of the object x: x.printname() print all variables and function names of the “mymodule” module: print(dir(mymodule))

importing only the person1 dictionary of the “mymodule” module: from mymodule import person1

return an iterator from a tuple: myit = iter(mytuple)

return an iterator form a string: myit = iter(mystr)

iterator that returns numbers, starting with 1: class MyNumbers: def iter(self): self.a = 1 return self

def next(self): x = self.a self.a += 1 return x

myclass = MyNumbers() myiter = iter(myclass)

stop after 20 iterations: def next(self): if self.a <= 20: x = self.a self.a += 1 return x else: raise StopIteration

greeting in mymodule: mymodule.greeting(“Name”)

import the datetime module: import datetime x = datetime.datetime.now() oder: x = datetime.datetime(Jahreszahl, Monat, Tag)

day: print(x.strftime(“%A”))

Eingabe Beschreibung Beispiel %a Wochentag Wed %A Wochentag lang Wednesday %w Wochentag als Zahl 0-6, 0 ist Sonntag 3 %d Tag im Monat (01-31) 31 %b Monatsname Dec %B Monatsname lang December %m Monatsnummer (1-12) 12 %y Jahr kurz 18 %Y Jahr lang 2018 %H Stunde 00-23 17 %I Stunde 00-12 05 %p AM/PM PM %M Minute (00-59) 41 %S Sekunde 00-59 08 %f Mikrosekunde 000000-999999 548513 %z UTC offset +0100 %Z Zeitzone CST %j Tagesnummer des Jahres 011-366 365 %U Wochenzahl, Sonntag Tag 1 der Woche, 00-53 52 %W Wochenzahl, Montag als erster Tag der Woche, 00-53 52 %c Lokale Version von Datum und Zeit Mon Dec 31 17:41:00 2018 %C Jahrtausend 20 %x Lokale Version vom Datum 21/31/2018 %X Lokale Version von der Zeit 17:41:00 %% Ein Prozentzeichen % %G ISO 8601 Jahr 2018 %u ISO 8601 Wochentag (1-7) 1 %V ISO 8601 Wochenzahl (01-53) 01

min(4,3,99)  gibt den kleinsten Wert an max(8,88,22)  gibt den größten Wert an abs(-7.23)  ändert ins positive pow(x, y)  Return the value of x to the power of y (same as xxx) import math  you can start using methods and constants of the module math.sqrt()  returns tge square root of a number math.ceil()  rounds a number upwards to its nearst integer math.floor()  rounds a number downwards to its nearst integer math.pi  returns the value of PI (3.14…) import json  syntax for storing and exchanging data json.loads()  parse a Json string json.dumps()  convert a Python object into a Json string Python JSON dict Object list Array tuple Array str String int Number float Number True true False false None null

Json.dumps(x, ident=4, separators=(“. ”, “ = “))  Beispiel; to defined the number of idents and change the default separator sort_keys=True  specify if the result should be sorted or not import re  can be used to work with Regular Expressions re.search(“…”.*…$”,txt)  search the string to see if starts with … and ends with … re.findall()  sucht enthaltene Inhalte Funktion Beschreibung findall Returns a list containing all matches search Returns a Match object if there is a match anywhere in the string split Returns a list where the string has been split at each match sub Replaces one or many matches with a string

Charakter Beschreibung Erklärung/Beispiel [] A set of characters “[a-m]” \ Signals a special sequence (also to escape special characters) “\d” . Any character (except newline character) “he…o” ^ Starts with “^hello” $ Ends with “planet$”

  • Zero or more occurrences “he.*o”
  • One or more occurrences “he.+o” ? Zero or one occurrences “he.?o” {} Exactly the specified number of occurrences “he.{2}o” | Either or “falls|stays” () Capture and group \A Returns a match if the specified characters are at the beginning of the string “\AThe” \b Returns a match where the specified characters are at the beginning or at the end of a word ( “r” in the beginning makes sure that the string is being treated as a “raw string”) r"\bain”

\B Returns a match where the specified characters are present, but NOT at the beginning or end of a word r”\Brain”

\d Returns a match where the string contains digits (numbers from 0-9) “\d” \D Returns a match where the string DOESN’T contain digits “\D” \s Returns a match where the string contain a white space character “\s” \S Returns a match where the string DOESN’T contain a white space character “\S” \w Returns a match where the string contains any word characters (a to z, 0-9 or _) “\w” \W Returns a match where the string DOESN’T contain any word characters “\W” “\W” \Z Returns a match if the specified characters are at the end of the string “Spain\Z”

Set/Beispiel Beschreibung [arn] Returns a match where one of the specified characters) is present [a-n] Returns a match for any lower case character, alphabetically between a and n [^arn] Returns a match for any characters EXCEPT a,r and n [01234] Returns a match where any of the specified digits are present [0-9] Returns a match for any digit between 0 and 9 [0-5][0-9] Returns a match for any two-digit numbers from 00 and 59 [a-zA-Z] Returns a match for any character alphabetically between a and z, upper case OR lower case [+] In sets, +,*,.,|,(),$,:,{} has no special meaning, so [+] means. Return a match for any + character in the string

re.split()  split at each specified character (,) re.sub()  replaces every specified character with an other specified character re.search  sagt wo das gesuchte ist .span() returns a tuple containing the start-, and end positions of the match. .string returns the string passed into the function .group() returns the part of the string where there was a match PIP  package manager  Installieren und dann kann es verwendet werden  Über PIP Befehl Pakete installieren  Pip list  listet alle installierten Pakete für Python mit der Versionsnummer auf try block lets you test a block of code for errors except block  lets you handle the error else block  lets you execute code when there is no error finally block  lets you execute code, regardless of the result of the try- and except blocks raise Exception(““)  Fehlermeldung anzeigen, wenn Bedingung erfüllt raise TypeERROR  zeigt an, welche Art von Error erzeugt wurde input()  Benutzereingabe f““  allows to format selected parts of a string; to specify a string as an f-string, put an f in front of the string {}  to format (values) in f-sting, add placeholders; modifier is included by adding a : followed by legal formatting type; if-Abfrage: f"It is very {‘Expensive’ if price>50 else ‘Cheap’}" .upper  Alle Buchstaben werden groß geschrieben Zeichen Erklärung Beispiel :< Left aligns the result (within the available space); Macht in diesem Beispiel 6 Leerzeichen nach der Zahl f"We have {49:<6} chickens." :> Right align the result (within the available space); macht in diesem Beispiel 8 Leerzeichen vor der Zahl f"We have {49:>8} chickens." :^ Center aligns the result (within the available space); macht in diesem Fall 6 Leerzeichen vor und nach der Zahl f"We have {49:^6} chickens." := Places the sign to the left most position; setzt das Zeichen vor der Zahl nach links und macht in diesem Beispiel 6 Leerzeichen zwischen dem Zeichen und der folgenden Zahl f"The temperature is {-5:=6} degrees celsius." :+ use to indicate if the result is positive or negative :- Use for negative values only : Use a space to insert an extra space before positive numbers :, Use as a thousand separator :_ Use as a thousand separator :b Binary format :c Converts the value into the corresponding Unicode character :d Decimal format :e Scientific format, with lower case e :E Scientific format, with upper case e :f Fix point number format :F Fix point number format, in uppercase format ( show inf and nan as INF and NAN) :g General format :G General format (using a upper case E for scientific notations) 😮 Octal format 😡 Hex format, lower case :X Hex format, upper case :n Number format :% Percentage format