Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lernen Funktionen in Python Ändern | Funktionen in Python
Einführung in Python
course content

Kursinhalt

Einführung in Python

Einführung in Python

1. Erste Bekanntschaft mit Python
2. Variablen und Typen in Python
3. Bedingte Anweisungen in Python
5. Schleifen in Python
6. Funktionen in Python

book
Funktionen in Python Ändern

Überdenken Sie das Beispiel mit den Länderinformationen. Was passiert, wenn der angegebene name-Parameter nicht im Datensatz gefunden wird?

1234567891011121314
# Data countries_dict = {'USA': (9629091, 331002651), 'Canada': (9984670, 37742154), 'Germany': (357114, 83783942), 'Brazil': (8515767, 212559417), 'India': (3166391, 1380004385)} # Defining a function def country_information(d, name): print('Country:', name) print('Area:', d[name][0], 'sq km') print('Population:', round(d[name][1]/1000000, 2), 'MM') # Testing the function country_information(countries_dict, 'USA') country_information(countries_dict, 'Ukraine')
copy

Können wir diese Situation handhaben? Absolut, indem wir bedingte Anweisungen implementieren!

1234567891011121314151617
# Data countries_dict = {'USA': (9629091, 331002651), 'Canada': (9984670, 37742154), 'Germany': (357114, 83783942), 'Brazil': (8515767, 212559417), 'India': (3166391, 1380004385)} # Modify our function def country_information_mod(d, name): if name not in d.keys(): print("There is no information about", name) else: print("Country:", name) print("Area:", d[name][0], 'sq km') print("Population:", round(d[name][1]/1000000, 2), 'mln') # Testing the function country_information_mod(countries_dict, "USA") country_information_mod(countries_dict, "Ukraine")
copy

Hinweis

Die Methode d.keys() ist eine Wörterbuchmethode, die eine Ansicht mit allen Schlüsseln des Wörterbuchs d zurückgibt. Hier wird sie verwendet, um zu überprüfen, ob der angegebene name unter den Schlüsseln des Wörterbuchs existiert.

Wie gezeigt, ist die Fehlermeldung in diesem überarbeiteten Format benutzerfreundlicher. Obwohl viele andere potenzielle Fehler existieren, gibt es zahlreiche Methoden, um sie zu behandeln.

War alles klar?

Wie können wir es verbessern?

Danke für Ihr Feedback!

Abschnitt 6. Kapitel 9
We're sorry to hear that something went wrong. What happened?
some-alt