BoSott
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
      • Invitee
    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Versions and GitHub Sync Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
Invitee
Publish Note

Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

Your note will be visible on your profile and discoverable by anyone.
Your note is now live.
This note is visible on your profile and discoverable online.
Everyone on the web can find and read all notes of this public team.
See published notes
Unpublish note
Please check the box to agree to the Community Guidelines.
View profile
Engagement control
Commenting
Permission
Disabled Forbidden Owners Signed-in users Everyone
Enable
Permission
  • Forbidden
  • Owners
  • Signed-in users
  • Everyone
Suggest edit
Permission
Disabled Forbidden Owners Signed-in users Everyone
Enable
Permission
  • Forbidden
  • Owners
  • Signed-in users
Emoji Reply
Enable
Import from Dropbox Google Drive Gist Clipboard
   owned this note    owned this note      
Published Linked with GitHub
Subscribed
  • Any changes
    Be notified of any changes
  • Mention me
    Be notified of mention me
  • Unsubscribe
Subscribe
# Fragen mit Beispielen: - - - --- # Gruppe 1: Tag 1 ## Skalenniveaus und Datentypen: |nominal | ordinal | intervall | ratio | |--------|:-------:|:---------:|------:| |strings | --------|-----------|integer| |bool |---------|-----------|float | ## Datentypen und Operatoren: |string|int|float|boolean|None| |------|---|-----|-------|----| |Vergleichsoperatoren|Vergleich, arithmetisch|Vergleich, arithmetisch|Vergleichsoperatoren|| ## Operatorenvorrang - Punkt vor Strich gilt ## Unerwartete Ergebnisse - man kann Strings mit Strings addieren und mit Zahlen multiplizieren (Strings mit Strings multiplizieren funktioniert nicht) -> Reihenfolge entscheidet darüber, wie herum Wörter angezeigt # Gruppe 1: Tag 2 Aufgabe 2: 22.1103381805 (Flächeninhalt in km²) ## Aufgaben if-else-Ausdrücke Beispiel 1: Note B Beispiel 2: Winter Beispiel 3: Ticketpreis: 12€ ist das unten vom letzten jahr? # Gruppe 2 ## Simple Datentypen und Skalenniveaus |nominal |ordinal |intervall |Verhältniss | |----|----|----|----| |boolean|||integer| |string|||float| ## Datentypen und Operatoren |arithmetische |vergleichende |logische| |----|----|----| |integer|integer|integer| |float|float|float| ||string|string| |||boolean| # Lösungen Tag 4 ```python= with open('eissorten.txt', 'r') as f: lines = f.readlines() sorten = [] bewertungen = [] for line in lines: eissorte, bewertung = line.strip().split(', ') sorten.append(eissorte) bewertungen.append(bewertung) sorten.pop(0) bewertungen.pop(0) print("Eissorten:", sorten) print("Bewertungen:", bewertungen) input_eissorte = input('Geben Sie eine Eissorte an: ').strip() if input_eissorte in sorten: index = sorten.index(input_eissorte) bewertung_output = bewertungen[index] print(f'Die Eissorte "{input_eissorte}" hat eine Bewertung von {bewertung_output}.') else: print(f'Die Eissorte "{input_eissorte}" wurde nicht gefunden.') ``` ```python= eissorte = ("Schokolade", "Erdbeere", "Melone", "Zitrone", "Himbeere") bewertung = ("meh", "gut", "echt lecker", "Fave", "das Beste") sorte = input("Geben Sie die Sorte an, für die Sie die Bewertung abfragen wollen:") bewertungsliste= dict(zip(eissorte, bewertung)) for key, value in bewertungsliste.items(): if sorte.lower() in key.lower(): print(f"Für die Sorte {key} wurde die Bewertung {value} abgegeben.") break if sorte.lower() not in key.lower(): print("Diese Sorte ist leider noch nicht in unserem Sortiment") ``` ```python= file_path = eis_bewertung = {"Vanille": 4/10, "Schoko": 5/10, "Pistazie": 10/10, "Waldfrucht": 9/10, "Cookies": 10/10} try: with open(file_path, "w") as file: file.write("Eissorten, Bewertung\n") for eissorte, bewertung in eis_bewertung.items(): file.write(f"{eissorte}, {bewertung}\n") except IOError: print("Fehler beim Schreiben in die Datei.") try: with open(file_path, "r") as file: lines = file.readlines() neue_bewertungen = {} for line in lines[1:]: eissorte, alte_bewertung = line.strip().split(", ") neue_bewertungen[eissorte] = float(alte_bewertung) for eissorte in neue_bewertungen: while True: try: neue_bewertung = float(input(f"Geben Sie eine neue Bewertung für {eissorte} ein (derzeitige Bewertung: {neue_bewertungen[eissorte]}): ")) if neue_bewertung < 0 or neue_bewertung > 10: raise ValueError("Die Bewertung muss zwischen 0 und 10 liegen.") neue_bewertungen[eissorte] = neue_bewertung break except ValueError as e: print(f"Fehler: {e}. Bitte geben Sie eine gültige Bewertung ein.") with open(file_path, "w") as file: file.write("Eissorten, Bewertung\n") for eissorte, bewertung in neue_bewertungen.items(): file.write(f"{eissorte}, {bewertung}\n") print("Die neuen Bewertungen wurden erfolgreich gespeichert.") except IOError: print("Fehler beim Lesen/Schreiben der Datei.") ``` ''' mögliche Lösung aber nicht perfekt: ```python= #neue Datei erstellen, erste Zeile und Eissorte mit Bewertung eissorten=["vanille", "pistazie", "zartbitter", "erdbeere", "joghurt"] bewertungen = ["6/10", "10/10", "9/10", "1/10", "3/10"] try: with open("eissorten2.txt", "w") as file: file.write("Sorte, Bewertung\n") print("Datei erfolgreich erstellt") for sorte, bewertung in zip(eissorten, bewertungen): file.write(f"{sorte}, {bewertung}\n") print(f"erfolgreiche Speicherung von Eissorten und Bewertungen in eissorten2.txt.") except IOError: print("Fehler bei der Speicherung der Eissorten mit Bewertung in Datei") try: with open("eissorten2.txt", "r+") as file: file.readline() zeilen = file.readlines() bewertungen_dict = dict(zip(eissorten, bewertungen)) for zeile in zeilen: sorte, bewertung = zeile.strip().split(",") bewertung = bewertungen_dict[sorte] eissorte_abfrage = input("Welche Eissorte wollen Sie neu bewerten? Zur Auswahl stehen vanille, pistazie, zartbitter, erdbeere und joghurt. ") if eissorte_abfrage in bewertungen_dict: print(f"Bewertung für {eissorte_abfrage}: {bewertungen_dict[eissorte_abfrage]}") neue_bewertung = input("Wie bewertest du {eissorte_abfrage} (Angabe in Punkte/10): ") bewertungen_dict[eissorte_abfrage] = neue_bewertung file.seek(0) for sorte in bewertungen_dict: file.write(f"{sorte}, {bewertungen_dict[sorte]}\n") print(f"Aktualisierte Bewertung für {eissorte_abfrage}") else: print(f"{eissorte_abfrage} wurde nicht gefunden.") except IOError: print("Fehler") ``` # Lösungen Tag 3 ```python= import math class Shape: def area(self): raise NotImplementedError("Die Methode area() muss in einer Unterklasse implementiert werden.") class Rectangle(Shape): def __init__(self, width, height): self.width = width self.height = height def area(self): return self.width * self.height class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return self.radius * math.pi class Quadrat(Rectangle): def __init__(self, sidea): self.width = sidea self.height = sidea rectangle = Rectangle(5, 4) print(rectangle.area()) circle = Circle(3) print(circle.area()) quadrat = Quadrat(6) print(quadrat.area()) ``` ```python= class Quadrat(Rectangle): def __init__(self, length): super().__init__(length, length) self.length = length ``` # Lösungen Tag 2 ## Gruppe Mitte ```python= flaeche = [x.split()[0] for x in flaeche] print(flaeche) flaeche = [x.replace('.', '') for x in flaeche] print(flaeche) flaeche = [x.replace(',', '.') for x in flaeche] print(flaeche) einwohnerzahl = [x.split()[0] for x in einwohnerzahl] print(einwohnerzahl) einwohnerzahl = [x.replace('.', '') for x in einwohnerzahl] print(einwohnerzahl) flaeche = [float(x) for x in flaeche] einwohnerzahl = [float(x) for x in einwohnerzahl] einwohner_pro_Quadratkilometer = [x / y for x, y in zip(einwohnerzahl, flaeche)] print(einwohner_pro_Quadratkilometer) def Einwohnerdichte (x, y): einwohner_pro_Quadratkilometer = [x / y for x, y in zip(einwohnerzahl, flaeche)] return einwohner_pro_Quadratkilometer Bevoelkerungsdichte = Einwohnerdichte(einwohnerzahl, flaeche) print(Bevoelkerungsdichte) hauptstaedte_bevoelkerung = dict(zip(hauptstaedte, einwohnerzahl)) print(hauptstaedte_bevoelkerung) max_einwohnerzahl = max(hauptstaedte_bevoelkerung.values()) max_hauptstadt = max(hauptstaedte_bevoelkerung, key=hauptstaedte_bevoelkerung.get) print(f"Die groesste Bevölkerung hat: {max_hauptstadt} mit {max_einwohnerzahl} Einwohnern.") hauptstaedte_bevoelkerungsdichte = dict(zip(hauptstaedte, Bevoelkerungsdichte)) print(hauptstaedte_bevoelkerungsdichte) min_bevoelkerungsdichte = min(hauptstaedte_bevoelkerungsdichte.values()) min_hauptstadt = min(hauptstaedte_bevoelkerungsdichte, key=hauptstaedte_bevoelkerungsdichte.get) print(f"Die niedrgiste Bevoelkerungsdichte hat: {min_hauptstadt} mit {min_bevoelkerungsdichte} Einwohnern.") def arithmetrisches_Mittel(x): return sum(x) / len(x) flaeche_arithmetrisches_mittel = arithmetrisches_Mittel(flaeche) print(f"Die durschnittliche Groesse der Fläche aller Laender beträgt {flaeche_arithmetrisches_mittel} km^2.") print(len(laender)) print(len(hauptstaedte)) print(len(einwohnerzahl)) print(len(flaeche)) ``` Datenaufbereitung: ```python= area = [] for f in flaeche: head, sep, tail = f.partition(" ") head = head.replace(",", "") area.append(float(head)) inhabitants = [] for e in einwohnerzahl: head, sep, tail = e.partition(" ") head = head.replace(".", "") inhabitants.append(float(head)) # Berechnung der Einwohnerdichte: def dichte(bewo, flach): dicht = bewo/flach return dicht einwohnerdichte= [] for i in range(len(inhabitants)): dichte_stadt = dichte(inhabitants[i], area[i]) #print(laender[i]) einwohnerdichte.append(dichte_stadt) ``` ```python= max_einwohner= einwohnerzahl_neu.index(max(einwohnerzahl_neu)) max_stadt= hauptstaedte_1[max_einwohner] max_E=max(einwohnerzahl_neu) print("Die höchste Einwohnerzahl hat",max_stadt, "mit einer Anzahl von", max_E) min_einwohnerdichte=min(Einwohnerdichte_liste) min_dichte=Einwohnerdichte_liste.index(min(Einwohnerdichte_liste)) min_stadt=hauptstaedte_1[min_dichte] print("Die niedrigste Einwohnerdichte ist", min_einwohnerdichte, "in der Stadt", min_stadt) ``` # Sonstiges ```python def count_character(s, c): return s.count(c) def max_vocal(s): vocals = 'aeiou' max_vocal = '' max_vocal_count = 0 for vocal in vocals: count = count_character(s, vocal) if count > max_vocal_count: max_vocal = vocal max_vocal_count = count return max_vocal def count_max(wort, buchstaben): max_vowel = max(buchstaben, default=0, key=wort.count) return wort.count(max_vowel), max_vowel def titin(): # Define the path to your text file file_path = "titin.txt" # Open the file in read mode with open(file_path, "r") as file: # Read all lines and join them into a single string multiline_string = "".join([line.strip() for line in file.readlines()]) return multiline_string if __name__ == "__main__": word = "Donaudampfschifffahrtselektrizitätenhauptbetriebswerkbauunternehmenbeamtengesellschaft" anzahl, buchstabe = count_max(word, "aeiou") print(f'Haeufigster Buchstabe: {buchstabe} mit der Anzahl {anzahl}') word = titin() anzahl, buchstabe = count_max(word, "aeiou") print(f'Haeufigster Buchstabe: {buchstabe} mit der Anzahl {anzahl}') ``` ### Titin ``` word = "..." word = word.replace("\n", "") print(f"Gesamtlaenge {len(word)}") anzahl, buchstabe = zaehlen.count_max(word, 'aeiou') print(f'Haeufigster Buchstabe: {buchstabe} mit der Anzahl: {anzahl}') ``` # Gruppenarbeit Montagnachmittag ----- ## Gruppe hintenrechts Vokale zählen ``` def vowelcount(x): vow={"a":0, "e":0, "i":0, "o":0, "u":0} for char in x.lower(): if char in vow: vow[char]+=1 print(f"vowels in your string: {vow}") maxvow= max(vow, key=vow.get) print(f"most common vowel: {maxvow}") ``` ## Gruppe: Dennis & Lennart ---- #Vokale zaehlen ``` def vokal_a(my_word, buchstabe): anzahl = my_word.count(buchstabe) return anzahl for i in ['a','e','i','o','u']: vokal_a(word, i) def vokal_e(my_word): e = my_word.count('e') return e def vokal_i(my_word): i = my_word.count('i') return i def vokal_o(my_word): o = my_word.count('o') return o def vokal_u(my_word): u = my_word.count('u') return u vokale = {'a':vokal_a(my_word), 'e':vokal_e(my_word), 'i':vokal_i(my_word), 'o':vokal_o(my_word), 'u':vokal_u(my_word)} print(vokale) ``` ---- ## Gruppe: Mitte ---- ```python= def vowels_in_a_word(w): vowels = 'AEIUOaeiou' count = 0 for char in w: if char in vowels: count += 1 return count number_vowels = vowels_in_a_word(w) print(f'Das Wort hat {number_vowels} Vokale.') ``` ``` a = 1.45 b = 5.89 c = 1.609 flaeche_meilen= a*b flaeche_km = flaeche_meilen *c**2 print(f"Die Flaeche betraegt {flaeche_km} km^2") ``` **Erkennung Kilometer oder Meile:** ``` a = 1.45 b = 5.89 einheit = "meile" def umrechnung_km(): c = 1.609 flaeche_meilen= a*b flaeche_km = flaeche_meilen *c**2 print(f"Die Flaeche betraegt {flaeche_km} km^2") if "km" in einheit or "Kilometer" in einheit or "kilometer" in einheit: umrechnung_km () else: flaeche_meile=a*b print(f"Die Flaeche betraegt {flaeche_meile} mi^2") ``` **Schokoriegel** ``` schokoriegel = "Milky Way" if schokoriegel == "Snickers": print("Hervoragender Geschmack!") elif schokoriegel == "Twixx": print("Guter Geschmack!") elif schokoriegel == "Mars": print("Okayer Geschmack!") elif schokoriegel == "Bounty" or schokoriegel == "Milky Way": print("Schlechter Geschmack!") else: print("Fehlerhafte Eingabe!") ``` ``` for zahl in range (1,101): if zahl%3 == 0 and zahl%5 == 0: print('fizzbuzz') elif zahl%3 == 0: print('fizz') elif zahl%5 == 0: print('buzz') else: print(zahl) ``` ---- ## Gruppe: ---- ``` a = input('a in Meilen: ') b = input(' b in Meilen: ') Fläche_km= round( (float(a) * 1.609) * (float(b) * 1.609), 3) print('die Fläche beträgt: ' , str(Fläche_km) , 'km^2') ``` ---- ## Gruppe: Sina ``` riegel_liste = ["mars", "bounty", "snickers", "twixx", "milky way"] abfrage = input("Welcher der folgenden Schokoriegel bevorzugst du unter Mars, Bounty, Snickers, Twixx, Milky Way? Gebe an: ").lower() abfrage = abfrage.replace(" ", "m") print(abfrage) if abfrage in riegel_liste: print("Hallo") if abfrage == "mars": print("Das ist eine schlechte Wahl.") elif abfrage == "bounty": print("Das ist sogar schlimmer als Mars") elif abfrage == "snickers": print("Das wäre auch meine Wahl. Du bist sympathisch.") elif abfrage == "twixx": print("Das ist zwar akzeptabel, aber warum nur Karamell wenn man auch dazu Erdnüsse haben kann") elif abfrage == "milky way": print("Dass man die überhaupt noch kaufen kann finde ich schlimm") else: print("Eingabe falsch geschrieben") ``` ---- #Funktion Buchstabenzahl def Buchstabenzahl (x): buchstabenzahl = len(x) return buchstabenzahl result = Buchstabenzahl ("Donaudampfschifffahrtselektrizitätenhauptbetriebswerkbauunternehmenbeamtengesellschaft") print(result) #Vokale zählen def Vokale_zaehlen (x): anzahl_a= x.count("a") anzahl_e = x.count("e") anzahl_i = x.count("i") anzahl_o = x.count("o") anzahl_u = x.count("u") #dictionary erstellen vokale_anzahl = {"Anzahl a" : anzahl_a, "Anzahl e" : anzahl_e, "Anzahl i" : anzahl_i, "Anzahl o" : anzahl_o, "Anzahl u" : anzahl_u} sortiert_vokale_anzahl = sorted(vokale_anzahl.values()) return vokale_anzahl, sortiert_vokale_anzahl ergebnis = Vokale_zaehlen ("Donaudampfschifffahrtselektrizitätenhauptbetriebswerkbauunternehmenbeamtengesellschaft") print(ergebnis) ###output 86 ({'Anzahl a': 7, 'Anzahl e': 13, 'Anzahl i': 4, 'Anzahl o': 1, 'Anzahl u': 4}, [1, 4, 4, 7, 13]) ---- ## Gruppe: ---- ---- ## Gruppe: ---- Hier Code ---- ## Gruppe: ---- Hier Code ---- Gruppe : The Pythoneers ----- Datentypen und Skalenniveaus Integer == Float == String == Boolean == None Type == {} | | Integer | Float| String | Boolean | | -------- | -------- | -------- | ----|----| | + |1| 1 |1 |1 | | -|1 |1 |0 |1 | | * |1 |1 |1 |1 | |/ |1 |1 |0 |1 | |<|1 |1 |1 | 1 | |>|1 |1 |1|1 | % > / und * > + und - Mutable: Datentypen können nach Erstellung verändert werden, ohne ein neues Objekt zu erstellen. Beispiele: Listen (list), Sets (set), Dictionaries (dict). Immutable: Datentypen können nach der Erstellung nicht verändert werden. Beispiele: Strings (str), Tupel (tuple), Zahlen (int, float). def wordcountandvokalcount (x): word=x wlen=len(word) numa = word.count("a") nume = word.count("e") numi = word.count("i") numo = word.count("o") numu = word.count("u") if numa > nume and numa > numi and numa > numo and numa > numu: return f"a ist the most common vokal and appears {numa} times. The word has {wlen} letters" elif nume > numa and nume > numi and nume > numo and nume > numu: return f"e ist the most common vokal and appears {nume} times. The word has {wlen} letters" elif numi > nume and numi > numa and numi > numo and numi > numu: return f"i ist the most common vokal and appears {numi} times. The word has {wlen} letters" elif numo > nume and numo > numi and numo > numa and numo > numu: return f"o ist the most common vokal and appears {numo} times. The word has {wlen} letters" elif numu > nume and numu > numi and numu > numo and numu > numa: return f"u ist the most common vokal and appears {numu} times. The word has {wlen} letters" else: return f"No vokal appears more than the other. The word has {wlen} letters" x= input("Please give me any word if you want the letters and vokals counted: ") print(wordcountandvokalcount (x)) ----- Gruppe : ('JackyJacky', 5) ----- Welche der simplen Datentypen stellen welche Skalenniveaus dar? + String --> Nominalskala + Integer --> Ordinalskala + Float --> Ratioskala + Boolean --> Nominalskala Welche Datentypen (string, int, float, boolean, None) können wie mit welchen Operatoren (arithmetische, vergleichs und logische) verarbeitet werden? + Boolean --> Verleichsoperatoren + String --> logische + Integer --> arithmetisch, Vergleichsoperatoren + Float --> arithmetisch, Vergleichsoperatoren Welche Kombinationen funktionieren gar nicht? Welche dieser Kombinationen geben unerwartete Ausgaben? `>>> "Hase" < "Maus"` `True` `boolean + integer funktioniert (True = 1)` ----- Gruppe : vornelinks ----- Welche der simplen Datentypen stellen welche Skalenniveaus dar? Integer (Ganzzahlen wie 1;2;3;…) =Ordinalskala Float (Dezimalzahlen: 3,14; 4,59836532; …) =Intervallskala String (Buchstaben und Wörter) =Nominalskala Boolean (True, False) =Nominalskala None type (None - ‘nichts’)=Nominalskala Welche Datentypen (string, int, float, boolean, None) können wie mit welchen Operatoren (arithmetische, vergleichs und logische) verarbeitet werden? Welche Kombinationen funktionieren gar nicht? Welche dieser Kombinationen geben unerwartete Ausgaben? (testen Sie e.g. int + int, oder string / int, etc.) bspw.: String: arithmetische + Operator sinnvoll vergleichs ja logische ja Float/Integer: arithmetische ja vergleichs ja logische ja Boolean: arithmetische nein vergleichs ja logische ja was geht garnicht ? String + Float / Integer (Error) None type + Float / Integer Wie stehen die Operatoren bzgl. des Operatorenvorranges zueinander? -> Probieren Sie es aus! Hat bspw. ‘%’ Vorrang vor ‘+’ oder ‘*’? % hat vorrang vor + x = 'hello world' print(x) a_m= 1.45 b_m = 5.89 a_k = 1.45*1.609 b_k = 5.89*1.609 c = a_k*b_k print('Areal in m²:', c) # For Schleife ```python= for num in range(1, 101): if num % 3 == 0 and num % 5 == 0: print("FizzBuzz") elif num % 3 == 0: print("Fizz") elif num % 5 == 0: print("Buzz") else: print(num) ``` ```python= def anzahl_buchstaben(x): return len(x) # Wort wort = 'Donaudampfschifffahrtselektrizitätenhauptbetriebswerkbauunternehmenbeamtengesellschaft' # Anzahl der Buchstaben im Wort anzahl_buchstaben_wort = anzahl_buchstaben(wort) print("Anzahl der Buchstaben im Wort:", anzahl_buchstaben_wort) vokale = 'aeiou' haeufigster_vokal = max(vokale, key=wort.count) anzahl_haeufigster_vokal = wort.count(haeufigster_vokal) print("Häufigster Vokal:", haeufigster_vokal) print("Anzahl seiner Vorkommen im Wort:", anzahl_haeufigster_vokal) ``` ----- Gruppe : 3 ----- Integer, Float -> Ratioskala String, Character -> Nominalskala Boolean -> None -> Nominalskala ----- Gruppe : ----- Nominal: string, boolean --> Vergleichsoperatoren (=/!=), logische Operatoren, Strings können mit + addiert werden Ordinal: --> alle Vergleichsoperatoren, logische Operatoren Intervall: float Rational: Erst % dann + % und * gleichgestellt + bei String geht, - / nicht 1. Hello World print("Hello World") Hello World greeting = "Hello World" print(greeting) 2. Aufgabe **simpel:** a = 1.45 b = 5.89 km = 1.609 akm = a*km bkm = b*km flaecheninhalt=akm*bkm print(flaecheninhalt) **advanced** 3. Aufgabe riegel = "Bounty" if riegel == "Mars": print("Geschmack sehr schlecht") elif riegel == "Bounty": print("Geschmack schlecht") elif riegel == "Twix": print("Geschmack langweilig") else: print("Geschmack gut") 4. Aufgabe a = 1.45 b = 5.89 km = 1 factor = 1.609 flaecheninhalt = a*b einheit=input("In welcher Einheit liegen die Daten vor?:") if einheit in ["km", " km", "km "]: print("Ergebnis in km", flaecheninhalt) elif einheit in ["mi"," mi", "mi "]: print("Ergebnis in mi", a*b*factor) else: print("Einheit nicht bekannt.") ```` a = float(input("Enter rectangle length: ")) b = float(input("Enter rectangle width: ")) unit = input("Are inputs in miles or km? ") if unit == "miles": sq_km = a * b * 2.58998811 print("Area is" , round(sq_km,2), "km²") elif unit == "km": sq_mi = a * b * 0.38610216 print("Area is" , round(sq_mi,2), "mi²") else: print("Please enter valid unit (miles or km)!") ```` ----- Gruppe : Gruppe A ----- 1. ``` print("Hello World, Gruppe A") ``` 2. ``` unit = input("Meilen oder Kilometer: ") miles = ["m", "M", "miles", "Meilen", "Meile", "mile"] a = 1.45 b = 5.89 FACTOR = 1.609 if unit in miles: a_km = a_miles * FACTOR b_km = b_miles * FACTOR else: a_km = a b_km = b A_gesamt_km = a_km * b_km A_gesamt_km ``` 3. ``` best = input("Lieblingsschockoriegel: ") igitt = ["Twixx", "Bounty"] hmm = ["Mars", "Snickers"] ok = "Milky Way" if best in igitt: print("Alter, was is falsch bei dir") elif best in hmm: print("We'll meet at dawn. I will see this issue settled") else: print("Ok") ``` 4. ``` zahlen = [] for n in range (1, 101): if n%3 == 0 and n%5 == 0: zahlen.append("FizzBuzz") elif n%5 == 0: zahlen.append("Buzz") elif n%3 == 0: zahlen.append("Fizz") else: zahlen.append(n) zahlen ``` 5. ``` kontinente = ['Afrika', 'Antarktika', 'Asien', 'Europa', 'Nordamerika', 'Ozeanien', 'Südamerika'] for element in kontinente: print('---') print(element) kontinente.sort(reverse = True) print(kontinente) a_kontinente = [kontinent for kontinent in kontinente if kontinent[0] =="A"] a_kontinente ``` **Tag 2** ``` capitals = ["Wellington", "Rabat", "Ottawa", "Sucre", "Bern"] countries = ["NewZealand", "Marokko" , "Canada", "Bolivia", "Switzerland"] c_and_c =[] for i in range(len(countries)): c_and_c.append(capitals[i]) c_and_c.append(countries[i]) c_and_c ``` ``` neue_liste = c_and_c #Wenn neue Liste mit pop gekürzt wird dann ist c_and_c auch kürzer um das selbe Elmement. Wenn allerdings neue_liste über das Indexing gekürtzt wird dann ist c_and_c nicht betroffen. #neue_liste = neue_liste[0:-2] neue_liste.pop(-2) print(f"Length of neue_liste = {len(neue_liste)}") print(f"Length of c_and_c = {len(c_and_c)}") ``` ``` #anlegen eines Dict mit Ländern und Hauptstädten capitals = ["Manila", "Bischkek", "Wellington", "Rabat", "Ottawa", "Sucre", "Bern"] countries = ["Philippinen", "Kirgistan", "NewZealand", "Marokko" , "Canada", "Bolivia", "Switzerland"] dic_c = {} for i in range(len(countries)): dic_c[capitals[i]] = countries[i] #ausgeben von ländern und Hauptstädten aus dem Dict. for n in range(len(dic_c)): key_n = list(dic_c.keys())[n] value_n = list(dic_c.values())[n] print(key_n) print(value_n) print("-----") ``` 8. ``` coordinates = [(14.5958, 120.9772), (42.8667, 74.5667), (-41.2889, 174.7772), (34.0253, -6.8361), (45.4247, -75.6950), (-19.0431, -65.2592), (46.9480, 7.4474)] cap_cor = [] cap_cor = list(zip(capitals, coordinates)) dic_ccc = {} for i in range(len(countries)): dic_ccc[countries[i]] = cap_cor[i] dic_ccc ``` 9. ``` #Unsere Lösung ist nicht schön aber sie funktioniert. hl1 = hauptstaedte + laender lh1 = laender + hauptstaedte hllh = zip(hl1, lh1) answers = dict(hllh) ``` ``` question = input("Input a country or capital: ") #in der Abfrage kann man nichts großschreiben Question = question[0].upper() + question[1:len(question)+1] if Question in hauptstaedte: print(f"{Question} ist die Hauptstadt von {answers[Question]}.") elif Question in laender: print(f"Die Hauptstadt von {Question} ist {answers[Question]}.") else: print("Hähh") #answers[Question] ``` Aufgaben Tag 3: 1. ``` def division(a, b): div = a/b return div a = 8958937768937 b = 2851718461558 res = division(a, b) res #pi ``` 2. ``` def multiplication(*mults): answ = 1 for mult in mults: answ = mult * answ return answ leap_year = input("Is it a leapyear (y/n): ") if leap_year == "n": seconds = multiplication(60, 60, 24, 365) elif leap_year == "y: seconds = multiplication(60, 60, 24, 366) seconds ``` 3. ``` word = 'Donaudampfschifffahrtselektrizitätenhauptbetriebswerkbauunternehmenbeamtengesellschaft' def laenge(word): length = len(word) return length def vokale(word): vocs = ["a", "e", "i", "o", "u"] anzahl = [] for i in vocs: count = word.count(i) anzahl.append(count) if "ä" in word: anzahl[0] = anzahl[0] + word.count("ä") anzahl[1] = anzahl[1] + word.count("ä") if "ö" in word: anzahl[3] = anzahl[3] + word.count("ö") anzahl[1] = anzahl[1] + word.count("ö") if "ü" in word: anzahl[4] = anzahl[4] + word.count("ü") anzahl[1] = anzahl[1] + word.count("ü") print(anzahl) anzahl_max = anzahl[0] m = 0 for n in range(len(anzahl)): if anzahl[n] > anzahl_max: anzahl_max = anzahl[n] m = n else: pass print(f"Der häufigste Vokale ist {vocs[m]} mit {anzahl[m]} mal.") anzahl_vokale =zip(vocs, anzahl) vokale_dict = dict(anzahl_vokale) return vokale_dict vokale_dict = vokale(word) ``` 4. ``` #buchstaben = list(map(chr, range(97, 123))) #buchstaben #die Zeilenumbrüche im Text machen das Wort 1845 Zeichen länger aber das hat nichts mit den Buchstaben zu tun def buchstaben(word): buchstaben = list(map(chr, range(97, 123))) anzahl = [] for i in buchstaben: count = word.count(i) anzahl.append(count) # im Englischen gibt es keine Umlaute # if "ä" in word: # anzahl[0] = anzahl[0] + word.count("ä") # anzahl[1] = anzahl[1] + word.count("ä") # if "ö" in word: # anzahl[3] = anzahl[3] + word.count("ö") # anzahl[1] = anzahl[1] + word.count("ö") # if "ü" in word: # anzahl[4] = anzahl[4] + word.count("ü") # anzahl[1] = anzahl[1] + word.count("ü") # print(anzahl) anzahl_max = anzahl[0] m = 0 for n in range(len(anzahl)): if anzahl[n] > anzahl_max: anzahl_max = anzahl[n] m = n else: pass print(f"Der häufigste Buchstabe ist {buchstaben[m]} mit {anzahl[m]} mal.") anzahl_vokale =zip(buchstaben, anzahl) vokale_dict = dict(anzahl_vokale) return vokale_dict buch_titin = buchstaben(titin) # Der häufigste Vokale ist l mit 43781 mal. ``` **Debugging** 1. ``` ostereier_pro_person = [5, 8, 15, 3] total_eggs = 0 for p in range(0,4): eggs = ostereier_pro_person[p] total_eggs += eggs print("Du hast insgesamt", total_eggs, "Ostereier gefunden.") sum(ostereier_pro_person) ``` 2. ``` import random as rnd def schokoei(): '''Gibt einen random Wert der Möglichkeiten 1,2,3,4,5 aus''' return rnd.randint(0, 6) def bewertung(schokoei): '''Bewertet Schokoeier eins nach dem anderen''' if schokoei == 0: print("gar nicht mal so lecker") elif schokoei == 1: print("Nicht gut, aber ansatzweise essbar") elif schokoei == 2: print("essbar aber noch nicht wirklich lecker") elif schokoei == 4: print("Richtig gut!") elif schokoei == 5: print("Absoluter Himmel") else: print("nicht auf der Skala enthalten") bewertung(schokoei()) ``` 3. ``` import random as rnd def schokoei(): '''Gibt einen random Wert der Möglichkeiten 1,2,3,4,5 aus''' return rnd.randint(1,5) def bewertung(): '''Bewertet Schokoeier eins nach dem anderen''' schokoei = schokoei() print(schokoei) if schokoei == 0: print("gar nicht mal so lecker") elif schokoei == 1: print("Nicht gut, aber ansatzweise essbar") elif schokoei == 2: print("essbar aber noch nicht wirklich lecker") elif schokoei == 3: print("Richtig gut!") elif schokoei >= 4: print("Absoluter Himmel") else: print("nicht auf der Skala enthalten") bewertung() ``` Datenaufbereitung: ``` area = [] for f in flaeche: head, sep, tail = f.partition(" ") head = head.replace(",", "") area.append(float(head)) #area inhabitants = [] for e in einwohnerzahl: head, sep, tail = e.partition(" ") head = head.replace(".", "") inhabitants.append(float(head)) #inhabitants ``` Berechnung der Einwohnerdichte: ``` def dichte(bewo, flach): dicht = bewo/flach return dicht einwohnerdichte= [] for i in range(len(inhabitants)): dichte_stadt = dichte(inhabitants[i], area[i]) #print(laender[i]) einwohnerdichte.append(dichte_stadt) einwohnerdichte ``` # Aufgabe 3 ``` max_einwohner= einwohnerzahl_neu.index(max(einwohnerzahl_neu)) max_stadt= hauptstaedte_1[max_einwohner] max_E=max(einwohnerzahl_neu) print("Die höchste Einwohnerzahl hat",max_stadt, "mit einer Anzahl von", max_E) min_einwohnerdichte=min(Einwohnerdichte_liste) min_dichte=Einwohnerdichte_liste.index(min(Einwohnerdichte_liste)) min_stadt=hauptstaedte_1[min_dichte] print("Die niedrigste Einwohnerdichte ist", min_einwohnerdichte, "in der Stadt", min_stadt) ``` **Tag 4 Classes and Exceptions** 1. ``` list1 = [1, 2, 3] a = 10 try: print(list1[a]) #throws IndexError since list is only 0 to 2 except IndexError: print(f"list1 has no position {a}") ``` 2. ``` studentin1 = Student("Alice", 20, "12345") try: studentin1.studienfach_anzeigen() except AttributeError: print("Definiere zuerst studienfach_anzeigen in der class Student") ``` 3. ``` import math class Shape: def area(self): raise NotImplementedError("Die Methode area() muss in einer Unterklasse implementiert werden.") class Rectangle(Shape): def __init__(self, width, height): self.width = width self.height = height def area(self): return self.width * self.height class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return self.radius**2 * math.pi class Quadrat(Rectangle): def __init__(self, side): self.width = side self.height = self.width ``` ``` class Square(Rectangle): def __init__(self, side): self.height = side self.width = side ``` Schockoriegelwahl: ``` answer = "not found" igitt = ["TWIXX", "BOUNTY", "TWIXX ", "BOUNTY "] hmm = ["MARS", "SNICKERS", "MARS ", "SNICKERS "] ok = ["MILKY WAY", "MILKYWAY", "MILKY WAY ", "MILKYWAY "] while answer == "not found": best = input("Aus Twixx, Bounty, Mars, Snicker und Milky Way Welcher Schockoriegel schmeckt dir am besten?: ") # print(best.upper()) if best.upper() in igitt: print("Alter, was is falsch bei dir") answer = "found" elif best.upper() in hmm: print("We'll meet at dawn. I will see this issue settled") answer = "found" elif best.upper() in ok: print("Ok") answer = "found" else: print(f"Die Eingabe {best} war keine gegebene Möglichkeit, bist du sicher, dass du den Riegel richtig geschrieben hast?") ``` Eisbewertungen ``` eissorten = ["Vanille", "Erdbeere", "Straciatella", "Schokolade", "Joghurt"] bewertung = ["5/10", "2/10", "7/10", "8/10", "8/10"] try: # Öffnen der Datei im Schreibmodus ('w') mit with with open("Eissorten.txt", "a") as file: file.write("\n") for i in range(len(eissorten)): file.write(eissorten[i]) file.write(",") file.write(bewertung[i]) file.write("\n") print("Datei erfolgreich geschrieben und automatisch geschlossen.") except FileNotFoundError as fnf_error: print(fnf_error) except IOError: print("Fehler beim Schreiben in die Datei.") ``` Abfrage Eissorten: ``` try: with open("Eissorten.txt", "r") as file: lines = file.readlines() print(lines) except IOError: print("Fehler beim Lesen in die Datei.") sorte = input("Die Bewertung welcher Eissorte möchtest Du wissen?: ").capitalize() if sorte in eissorten: ind = eissorten.index(sorte) + 1 ans = lines[ind].replace("\n", "") head, sep, tail = ans.partition(",") print(f"Die Eissorte {sorte} hat die Bewertung {tail}.") ``` # Ende Gruppe A import webbrowser geschmack= input("Welcher dieser Schokoriegel ist ihrer Meinung nach der leckerste? Mars, Bounty, Snickers, Twixx, Milky_Way: ") if geschmack == "Mars" or geschmack == "Bounty" or geschmack == "Snickers": url = "https://www.youtube.com/watch?v=1GxBIARAGog" webbrowser.open(url, new=0, autoraise=True) elif geschmack == "Milky_Way": print("Kann man machen") elif geschmack == "Twixx": print("Einfach Feinschmecker") else: print("Hä was gibst du da ein?")import webbrowser while True: geschmack = input("Welcher dieser Schokoriegel ist ihrer Meinung nach der leckerste? Mars, Bounty, Snickers, Twixx, Milky_Way: ") if geschmack == "Mars" or geschmack == "Bounty" or geschmack == "Snickers": url = "https://www.youtube.com/watch?v=1GxBIARAGog" webbrowser.open(url, new=0, autoraise=True) break # Exit the loop if a valid option is selected elif geschmack == "Milky_Way": print("Kann man machen") break # Exit the loop if a valid option is selected elif geschmack == "Twixx": print("Einfach Feinschmecker") break # Exit the loop if a valid option is selected else: print("Hä was gibst du da ein? Bitte wähle einen der angegebenen Schokoriegel.") Traceback (most recent call last): File "C:\Users\pascu\PycharmProjects\pythonProject4\main.py", line 1, in <module> import whisper File "C:\Users\pascu\AppData\Local\Programs\Python\Lib\site-packages\whisper.py", line 69, in <module> libc = ctypes.CDLL(libc_name) ^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\pascu\AppData\Local\Programs\Python\Python311\Lib\ctypes\__init__.py", line 366, in __init__ if '/' in name or '\\' in name: ^^^^^^^^^^^ TypeError: argument of type 'NoneType' is not iterable

Import from clipboard

Paste your markdown or webpage here...

Advanced permission required

Your current role can only read. Ask the system administrator to acquire write and comment permission.

This team is disabled

Sorry, this team is disabled. You can't edit this note.

This note is locked

Sorry, only owner can edit this note.

Reach the limit

Sorry, you've reached the max length this note can be.
Please reduce the content or divide it to more notes, thank you!

Import from Gist

Import from Snippet

or

Export to Snippet

Are you sure?

Do you really want to delete this note?
All users will lose their connection.

Create a note from template

Create a note from template

Oops...
This template has been removed or transferred.
Upgrade
All
  • All
  • Team
No template.

Create a template

Upgrade

Delete template

Do you really want to delete this template?
Turn this template into a regular note and keep its content, versions, and comments.

This page need refresh

You have an incompatible client version.
Refresh to update.
New version available!
See releases notes here
Refresh to enjoy new features.
Your user state has changed.
Refresh to load new user state.

Sign in

Forgot password

or

By clicking below, you agree to our terms of service.

Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
Wallet ( )
Connect another wallet

New to HackMD? Sign up

Help

  • English
  • 中文
  • Français
  • Deutsch
  • 日本語
  • Español
  • Català
  • Ελληνικά
  • Português
  • italiano
  • Türkçe
  • Русский
  • Nederlands
  • hrvatski jezik
  • język polski
  • Українська
  • हिन्दी
  • svenska
  • Esperanto
  • dansk

Documents

Help & Tutorial

How to use Book mode

Slide Example

API Docs

Edit in VSCode

Install browser extension

Contacts

Feedback

Discord

Send us email

Resources

Releases

Pricing

Blog

Policy

Terms

Privacy

Cheatsheet

Syntax Example Reference
# Header Header 基本排版
- Unordered List
  • Unordered List
1. Ordered List
  1. Ordered List
- [ ] Todo List
  • Todo List
> Blockquote
Blockquote
**Bold font** Bold font
*Italics font* Italics font
~~Strikethrough~~ Strikethrough
19^th^ 19th
H~2~O H2O
++Inserted text++ Inserted text
==Marked text== Marked text
[link text](https:// "title") Link
![image alt](https:// "title") Image
`Code` Code 在筆記中貼入程式碼
```javascript
var i = 0;
```
var i = 0;
:smile: :smile: Emoji list
{%youtube youtube_id %} Externals
$L^aT_eX$ LaTeX
:::info
This is a alert area.
:::

This is a alert area.

Versions and GitHub Sync
Get Full History Access

  • Edit version name
  • Delete

revision author avatar     named on  

More Less

Note content is identical to the latest version.
Compare
    Choose a version
    No search result
    Version not found
Sign in to link this note to GitHub
Learn more
This note is not linked with GitHub
 

Feedback

Submission failed, please try again

Thanks for your support.

On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

Please give us some advice and help us improve HackMD.

 

Thanks for your feedback

Remove version name

Do you want to remove this version name and description?

Transfer ownership

Transfer to
    Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

      Link with GitHub

      Please authorize HackMD on GitHub
      • Please sign in to GitHub and install the HackMD app on your GitHub repo.
      • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
      Learn more  Sign in to GitHub

      Push the note to GitHub Push to GitHub Pull a file from GitHub

        Authorize again
       

      Choose which file to push to

      Select repo
      Refresh Authorize more repos
      Select branch
      Select file
      Select branch
      Choose version(s) to push
      • Save a new version and push
      • Choose from existing versions
      Include title and tags
      Available push count

      Pull from GitHub

       
      File from GitHub
      File from HackMD

      GitHub Link Settings

      File linked

      Linked by
      File path
      Last synced branch
      Available push count

      Danger Zone

      Unlink
      You will no longer receive notification when GitHub file changes after unlink.

      Syncing

      Push failed

      Push successfully