lehrkraefte:blc:informatik:glf24:python:cheat-sheet

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
Next revision
Previous revision
lehrkraefte:blc:informatik:glf24:python:cheat-sheet [2024/10/29 14:11] – [Wiederholungen] Ivo Blöchligerlehrkraefte:blc:informatik:glf24:python:cheat-sheet [2024/11/04 21:06] (current) – [Formatierte Ausgabe] Ivo Blöchliger
Line 1: Line 1:
 +====== Python Cheat Sheet ======
 +===== Variablen und Operationen =====
 +<code python>
 +a = 42      # Zuweisung
 +a = a + 1   # Variable um 1 erhöhen
 +b = a % 9   # Rest der Division von (hier 43 durch 9) also 7.
 +c = b*7     # Multiplikation
 +d = b/2     # Division
 +c = a**2 + b**2   # Potenzen
 +w = c**0.5  # Wurzel     (alternative via import math, dann math.sqrt(c))
 +</code>
 +===== Verzweigungen =====
 +<code python>
 +a = 3
 +if a>2:
 +   print("grösser 2")
 +else:
 +   print("kleiner gleich 2")
 +
 +b=5
 +if a%2==0 and b%2==0:      # Beide gerade?
 +   print("Beide gerade")
 + 
 +if a%2==1 or b<3:           # oder (vielleicht auch beides)
 +   print("Humpfdidumpf")
 +  
 +</code>
 +===== Wiederholungen =====
 +<code python>
 +n = 10
 +i = 0
 +while i<n:
 +   print("i ist jetzt ", i)
 +   i = i+1       # Laufvariable am Schluss erhöhen nicht vergessen!
 +</code>
 +
 +   
 +===== Formatierte Ausgabe =====
 +<code python>
 +a = 3.3453521
 +print(f"a={a} oder a={a:.2f}")
 +</code>
 +
 +===== Zufallszahlen =====
 +Ganzzahlen
 +<code python>
 +from random import randrange
 +z = randrange(10)  # Zufallszahl von 0 bis und mit 9 (also 10 Möglichkeiten)
 +print(z)
 +</code>
 +
 +«Reelle» Zahlen zwischen 0 und 1:
 +<code python>
 +from random import random
 +z = random()  # Zufallszahl zwischen 0 (inklusive) und 1 (exklusive)
 +print(z)
 +</code>