Inhaltsverzeichnis

In Python ist das korrekte Einrücken von Zeilen sehr wichtig!

# Ganzzahlen (integers)
zahl = 42
print(zahl)  # Ausgabe: 42
 
# Gleitkommazahlen (float)
pi = 3.14
print(pi)  # Ausgabe: 3.14
 
# Zeichenketten (strings)
name = "Alice"
print("Hallo, " + name)  # Ausgabe: Hallo, Alice
 
# Boolesche Werte (boolean)
wahr = True
falsch = False
print(wahr)  # Ausgabe: True
# Arithmetische Operatoren
a = 5
b = 2
 
summe = a + b
differenz = a - b
produkt = a * b
quotient = a / b
rest = a % b
potenz = a ** b
 
print(summe, differenz, produkt, quotient, rest, potenz)
# Ausgabe: 7 3 10 2.5 1 25
# Bedingte Anweisung (if-else)
alter = 18
 
if alter >= 18:
    print("Du bist volljährig.")
else:
    print("Du bist minderjährig.")
 
# Schleife (for-Schleife)
fruits = ["Apfel", "Banane", "Orange"]
 
for fruit in fruits:
    print(fruit)
 
# Schleife (while-Schleife)
counter = 0
 
while counter < 5:
    print(counter)
    counter += 1
def greet(name):
    print("Hallo, " + name + "!")
 
greet("Bob")
# Ausgabe: Hallo, Bob!

Strings

https://docs.python.org/2/library/stdtypes.html#string-methods

s = "Hallo welt, ciao"
print len(s)
print s[0:11] # from:to

ACHTUNG: Strings sind immutable!!! (unveränderbar) Man muss Kopien erzeugen

a = "Hello"
b = "world"
print(a + b)
 
s = "Hello world"
s1 = s[5] + "moon"
s1 = 'abc'
s2 = '123'
print('s1.join(s2):', s1.join(s2))
print('s2.join(s1):', s2.join(s1))
 
// assoziativ
test =  {'mat': "1", 'that': "2"}
s = '->'
print(s.join(test))
test =  {"1":'mat', "2":'that'}
s = ', '
print(s.join(test))

Arrays

In Python nennt man Arrays auch Listen.

cars = []
vw = []
vw.append("golf3")
cars.append(vw)
audi = []
audi.append("a1")
cars.append(audi)
print(cars[0])

Funktionen

Build In Funktionen: https://www.programiz.com/python-programming/methods/built-in

def find(str, ch):
  index = 0
  while index < len(str):
    if str[index] == ch:
      return index
    index = index + 1
  return -1

Lambda

numbers = (1, 2, 3, 4)
result = map(lambda x: x*x, numbers)
print(result)
 
# converting map object to set
numbersSquare = set(result)
print(numbersSquare)

Parameter

import sys, getopt
 
def main(argv):
   inputfile = ''
   outputfile = ''
   try:
      opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
   except getopt.GetoptError:
      print 'test.py -i <inputfile> -o <outputfile>'
      sys.exit(2)
   for opt, arg in opts:
      if opt == '-h':
         print 'test.py -i <inputfile> -o <outputfile>'
         sys.exit()
      elif opt in ("-i", "--ifile"):
         inputfile = arg
      elif opt in ("-o", "--ofile"):
         outputfile = arg
   print 'Input file is "', inputfile
   print 'Output file is "', outputfile
 
if __name__ == "__main__":
   main(sys.argv[1:])

Dateien

f = open("file","mode") # r, w, w+, a
content = f.read()
for line in f.readlines():
    print(line)
f.write("Hello world")
f.close()

Datenstrukturen

Set

Sets, auch als Mengen bezeichnet, sind eine ungeordnete Sammlung einzigartiger Elemente in Python. Sie eignen sich gut, um Duplikate zu entfernen und mathematische Operationen wie Vereinigung, Schnittmenge und Differenz durchzuführen. Die Reihenfolge der Elemente in einem Set (Menge) wird in Python nicht garantiert.

fruits = {'apple', 'banana', 'orange'}
fruits.add('grape')
print(fruits)

Dictionary

Dictionaries sind eine assoziative Datenstruktur, die Schlüssel-Wert-Paare enthält. Sie ermöglichen einen schnellen Zugriff auf Werte anhand der Schlüssel und eignen sich gut für die Speicherung und Abfrage von Daten.

student = {'name': 'John', 'age': 20, 'major': 'Computer Science'}
student['age'] = 21
print(student['name'])

Listen

Listen sind eine grundlegende Datenstruktur in Python, die verwendet wird, um eine geordnete Sammlung von Elementen zu speichern. Eine Liste kann Elemente verschiedener Datentypen enthalten und ermöglicht den Zugriff auf die Elemente über deren Position (Index) in der Liste.

# Listen erstellen
my_list = [1, 2, 3, 4, 5]
empty_list = []
 
my_list.append(6)  # Hinzufügen am Ende der Liste
my_list.insert(0, 0)  # Hinzufügen an einer bestimmten Position (Index)
 
my_list.remove(3)  # Entfernen eines bestimmten Elements
popped_element = my_list.pop()  # Entfernen des letzten Elements und Rückgabe
 
print(my_list[0])  # Zugriff auf ein bestimmtes Element über den Index
print(my_list[-1])  # Zugriff auf das letzte Element
 
length = len(my_list)  # Anzahl der Elemente in der Liste
 
sublist = my_list[1:4]  # Elemente mit Index 1 bis 3 (exklusiv)
sublist2 = my_list[:3]  # Elemente von Beginn bis Index 2 (exklusiv)
sublist3 = my_list[2:]  # Elemente von Index 2 bis Ende
 
reversed_list = my_list[::-1]  # Liste in umgekehrter Reihenfolge
 
combined_list = my_list + other_list  # Listen kombinieren
 
my_list.sort()  # Liste in aufsteigender Reihenfolge sortieren
my_list.sort(reverse=True)  # Liste in absteigender Reihenfolge sortieren

Listenkomprehension ist eine elegante Möglichkeit, Listen auf der Grundlage von vorhandenen Listen zu erstellen. Sie ermöglicht es uns, komplexe Operationen auf eine kompakte Weise auszudrücken.

numbers = [1, 2, 3, 4, 5]
squared_numbers = [x ** 2 for x in numbers]
print(squared_numbers)

Regular Expessions

Die grundlegende Funktion, um nach Mustern in einem String zu suchen, ist re.search():

import re
 
text = "Hello, my name is John."
pattern = r"name is (\w+)"
 
match = re.search(pattern, text)
if match:
    print("Gefunden:", match.group(0))  # Gesamter Treffer
    print("Name:", match.group(1))      # Erste Gruppe im Muster

Du kannst re.sub() verwenden, um Muster in einem String zu ersetzen:

import re
 
text = "Hello, my name is John."
pattern = r"John"
replacement = "Alice"
 
new_text = re.sub(pattern, replacement, text)
print(new_text)

Mit re.findall() kannst du alle Übereinstimmungen eines Musters in einem String extrahieren:

import re
 
text = "Phone numbers: 123-456-7890, 987-654-3210"
pattern = r"\d{3}-\d{3}-\d{4}"
 
phone_numbers = re.findall(pattern, text)
print(phone_numbers)

Du kannst Flags verwenden, um das Verhalten deiner regulären Ausdrücke zu ändern, z.B. für Groß-/Kleinschreibung:

import re
 
text = "Hello, hello, HELLO!"
pattern = r"hello"
matches = re.findall(pattern, text, re.IGNORECASE)  # Case-insensitive Suche
print(matches)

Sockets

Siehe Scapy.

import socket
 
HOST = "127.0.0.1"  # Standard loopback interface address (localhost)
PORT = 65432  # Port to listen on (non-privileged ports are > 1023)
 
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind((HOST, PORT))
    s.listen()
    conn, addr = s.accept()
    with conn:
        print(f"Connected by {addr}")
        while True:
            data = conn.recv(1024)
            if not data:
                break
            conn.sendall(data)
import socket
 
HOST = "127.0.0.1"  # The server's hostname or IP address
PORT = 65432  # The port used by the server
 
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.connect((HOST, PORT))
    s.sendall(b"Hello, world")
    data = s.recv(1024)
 
print(f"Received {data!r}")

Binary

# convert a decimal ip address string into a binary ip address string
def test1(ip):
    ipparts = ip.split(".")
    print( bin(int(ipparts[0]))[2:].zfill(8) + "." + bin(int(ipparts[1]))[2:].zfill(8) + "." + bin(int(ipparts[2]))[2:].zfill(8) + "." + bin(int(ipparts[3]))[2:].zfill(8) )
 
# convert a decimal ip address string to Int32  
# x = 192.168.0.13
# x = {13} + 2**0 * 0  +  2**8 * {0}  +  2**16 * {168}  +  2**24 * {192}
def test2(ip):
    ipparts = ip.split(".")
    x = int(ipparts[3]) + 2**0 * 0 + 2**8 * int(ipparts[2]) + 2**16 * int(ipparts[1]) + 2**24 * int(ipparts[0])
    print( bin(x)[2:].zfill(32) )
 
 
test1("172.16.32.13")
test2("172.16.32.13")

Security

python -c "import pty; pty.spawn('/bin/bash');"

JSON

// [{"a":"aaa"},{"b":"bbb"}]
import json
with open("json.txt") as file:
    data = json.load(file)
print(data[0].get("key"))

PyGame

Pong

import pygame
from pygame.locals import *
 
# Initialisierung von Pygame
pygame.init()
 
# Fenstergröße
WIDTH, HEIGHT = 640, 480
WINDOW_SIZE = (WIDTH, HEIGHT)
 
# Farben
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
 
# Erstellung des Spielfensters
window = pygame.display.set_mode(WINDOW_SIZE)
pygame.display.set_caption("Pong")
 
# Spieler
PLAYER_WIDTH, PLAYER_HEIGHT = 10, 60
player1_pos = pygame.Rect(50, HEIGHT/2 - PLAYER_HEIGHT/2, PLAYER_WIDTH, PLAYER_HEIGHT)
player2_pos = pygame.Rect(WIDTH - 50 - PLAYER_WIDTH, HEIGHT/2 - PLAYER_HEIGHT/2, PLAYER_WIDTH, PLAYER_HEIGHT)
player1_speed = 0
player2_speed = 0
 
# Ball
BALL_RADIUS = 10
ball_pos = pygame.Rect(WIDTH/2 - BALL_RADIUS/2, HEIGHT/2 - BALL_RADIUS/2, BALL_RADIUS, BALL_RADIUS)
ball_speed_x = 3
ball_speed_y = 3
 
# Spiel-Loop
running = True
clock = pygame.time.Clock()
 
while running:
    # Hintergrund zeichnen
    window.fill(BLACK)
 
    for event in pygame.event.get():
        if event.type == QUIT:
            running = False
        elif event.type == KEYDOWN:
            if event.key == K_w:
                player1_speed = -3
            elif event.key == K_s:
                player1_speed = 3
            elif event.key == K_UP:
                player2_speed = -3
            elif event.key == K_DOWN:
                player2_speed = 3
        elif event.type == KEYUP:
            if event.key == K_w or event.key == K_s:
                player1_speed = 0
            elif event.key == K_UP or event.key == K_DOWN:
                player2_speed = 0
 
    # Spieler bewegen
    player1_pos.y += player1_speed
    player2_pos.y += player2_speed
 
    # Kollision mit Fenster-Rändern überprüfen
    if player1_pos.top <= 0:
        player1_pos.top = 0
    if player1_pos.bottom >= HEIGHT:
        player1_pos.bottom = HEIGHT
    if player2_pos.top <= 0:
        player2_pos.top = 0
    if player2_pos.bottom >= HEIGHT:
        player2_pos.bottom = HEIGHT
 
    # Ball bewegen
    ball_pos.x += ball_speed_x
    ball_pos.y += ball_speed_y
 
    # Kollision mit Schlägern überprüfen
    if ball_pos.colliderect(player1_pos) or ball_pos.colliderect(player2_pos):
        ball_speed_x *= -1
    if ball_pos.top <= 0 or ball_pos.bottom >= HEIGHT:
        ball_speed_y *= -1
 
    # Ball-Ausrichtung umkehren, wenn das Spielfeld verlassen wird
    if ball_pos.left <= 0 or ball_pos.right >= WIDTH:
        ball_pos.x = WIDTH/2 - BALL_RADIUS/2
        ball_pos.y = HEIGHT/2 - BALL_RADIUS/2
        ball_speed_x *= -1
 
    # Objekte zeichnen
    pygame.draw.rect(window, WHITE, player1_pos)
    pygame.draw.rect(window, WHITE, player2_pos)
    pygame.draw.ellipse(window, WHITE, ball_pos)
 
    # Fenster aktualisieren
    pygame.display.flip()
    clock.tick(60)
 
# Pygame beenden
pygame.quit()

Tensorflow

Siehe Tensorflow.

# -*- coding: utf-8 -*-
 
import tensorflow as tf
import numpy as np
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.optimizers import Adam
 
# Beispiel-Datensatz
sentences = [
    "Ich liebe diesen Film!",
    "Das Essen war köstlich.",
    "Der Service war schrecklich.",
    "Der Film war enttäuschend.",
    "Ich kann dieses Restaurant nicht empfehlen.",
    "Ich gehe dort nie wieder hin",
    "Das Konzert war fantastisch.",
    "Der Urlaub war wunderbar.",
    "Der Kundenservice war großartig."
]
 
labels = np.array([1, 1, 0, 0, 0, 0, 1, 1, 1])  # 1 für positiv, 0 für negativ
 
# Tokenisierung und Vektorisierung der Sätze
tokenizer = tf.keras.preprocessing.text.Tokenizer()
tokenizer.fit_on_texts(sentences)
sequences = tokenizer.texts_to_sequences(sentences)
word_index = tokenizer.word_index
max_length = max([len(seq) for seq in sequences])
padded_sequences = tf.keras.preprocessing.sequence.pad_sequences(sequences, maxlen=max_length)
 
# Modell erstellen
model = Sequential()
model.add(Dense(16, activation="relu", input_shape=(max_length,)))
model.add(Dense(1, activation="sigmoid"))
 
# Modell kompilieren
model.compile(loss="binary_crossentropy", optimizer=Adam(learning_rate=0.001), metrics=["accuracy"])
 
# Modell trainieren
model.fit(padded_sequences, labels, epochs=10000)
 
# Neue Sätze vorhersagen
new_sentences = [
    "Der Film hat mir gut gefallen.",
    "Es war ein schrecklicher Abend.",
    "Die sehen mich nie wieder",
    "Das Konzert war erstaunlich gut."
]
new_sequences = tokenizer.texts_to_sequences(new_sentences)
new_padded_sequences = tf.keras.preprocessing.sequence.pad_sequences(new_sequences, maxlen=max_length)
predictions = model.predict(new_padded_sequences)
 
for sentence, prediction in zip(new_sentences, predictions):
    sentiment = "positiv" if prediction > 0.5 else "negativ"
    print(f"Satz: {sentence}")
    print(f"Sentiment: {sentiment}")
    print()

Torch

Siehe Torch

Transformers

Siehe Transformers.