Zum Hauptinhalt springen
tsecurity.de LIVE
Echtzeit-Radar & Feeds
Alle RSS Feeds
👥 Community & Social
IT Security NachrichtenEntwickler: Claude Code macht Job seelenlos(23.09.2026 um 10:06 Uhr)
IT Security NachrichtenBW/4HANA oder Business Data Cloud: Migration als Grundsatzentscheidung(23.09.2026 um 10:32 Uhr)
IT Security NachrichtenZukunftssichere Unternehmenssteuerung im Mittelstand(23.09.2026 um 10:50 Uhr)
IT Security NachrichtenWhy security belongs in the network(23.09.2026 um 10:00 Uhr)
IT Security NachrichtenNeue Cybersecurity-Pflichten für den Maschinenbau(23.09.2026 um 11:00 Uhr)
IT Security NachrichtenOpus 5.5: Anthropics neues KI-Modell - mehr Leistung, geringere Kosten(23.09.2026 um 09:50 Uhr)
IT Security NachrichtenFBI gehackt: Täter erbeuten angeblich die Daten aller Mitarbeiter(23.09.2026 um 10:30 Uhr)
IT Security NachrichtenTiefpreis-Tage: 13 Deals bei Media Markt & Saturn, die sich lohnen(23.09.2026 um 10:51 Uhr)
IT Security NachrichtenPatchday: Adobe Connect ist unter Android, macOS und Windows verwundbar(23.09.2026 um 10:45 Uhr)
IT Security DownloadsFoxit PDF Reader Download - PDF-Dateien anzeigen(23.09.2026 um 09:39 Uhr)
IT Security NachrichtenEntwickler: Claude Code macht Job seelenlos(23.09.2026 um 10:06 Uhr)
IT Security NachrichtenBW/4HANA oder Business Data Cloud: Migration als Grundsatzentscheidung(23.09.2026 um 10:32 Uhr)
IT Security NachrichtenZukunftssichere Unternehmenssteuerung im Mittelstand(23.09.2026 um 10:50 Uhr)
IT Security NachrichtenWhy security belongs in the network(23.09.2026 um 10:00 Uhr)
IT Security NachrichtenNeue Cybersecurity-Pflichten für den Maschinenbau(23.09.2026 um 11:00 Uhr)
IT Security NachrichtenOpus 5.5: Anthropics neues KI-Modell - mehr Leistung, geringere Kosten(23.09.2026 um 09:50 Uhr)
IT Security NachrichtenFBI gehackt: Täter erbeuten angeblich die Daten aller Mitarbeiter(23.09.2026 um 10:30 Uhr)
IT Security NachrichtenTiefpreis-Tage: 13 Deals bei Media Markt & Saturn, die sich lohnen(23.09.2026 um 10:51 Uhr)
IT Security NachrichtenPatchday: Adobe Connect ist unter Android, macOS und Windows verwundbar(23.09.2026 um 10:45 Uhr)
IT Security DownloadsFoxit PDF Reader Download - PDF-Dateien anzeigen(23.09.2026 um 09:39 Uhr)
Intelligence View
⚡ tsecurity.de Intelligence

The Secret Life of Python: The Safety Net ('try' and 'except')

Understanding try, except, and Input Validation. Timothy was beaming. "I learned my lesson from last time," he told Margaret. "I updated my guessing game. Now I use int() to cast the user's input into a number immediately. No more…

0
↗ Quelle (dev.to)
Reagiere als Erste:r — dein Feedback zählt!

Understanding try, except, and Input Validation.






Timothy was beaming. "I learned my lesson from last time," he told Margaret. "I updated my guessing game. Now I use int() to cast the user's input into a number immediately. No more silent bugs!"



"That is excellent progress," Margaret said, moving her chair closer. "But what happens if the user doesn't follow instructions?"



"What do you mean?" Timothy asked. "It says 'Guess a number'. Why wouldn't they type a number?"



"Users are creative," Margaret smiled. "Watch."



She leaned over and ran his program.

Prompt: Guess the number (1-10):

Margaret typed: five



Output:




Traceback (most recent call last):
File "game.py", line 3, in <module>
guess = int(input("Guess the number (1-10): "))
ValueError: invalid literal for int() with base 10: 'five'







The program crashed instantly.



Timothy sighed. "It blew up. Because int() doesn't know how to turn the word 'five' into a number."






Catching the Fall



"Exactly," Margaret said. "When Python encounters something it can't handle—like trying to do math with a word—it raises an Exception. By default, an exception stops the program dead in its tracks."



"So I need to force the user to type digits?" Timothy asked.



"You can't force them," Margaret corrected gently. "But you can catch them when they fall."



She drew a simple trapeze artist on the whiteboard with a net underneath. "Think of your code as a performance. Usually, the acrobat catches the bar perfectly. But sometimes, they slip. If there is no net, the show ends in disaster. If there is a net, they simply bounce back and try again."



"In Python," she continued, "we call this net a try / except block."



She took the keyboard and wrapped his risky code in a safety structure.




try:
# The risky move: Trying to cast text to a number
guess = int(input("Guess the number (1-10): "))
print(f"You guessed: {guess}")
except ValueError:
# The safety net: Catches ONLY the ValueError crash
print("Oops! Please type a digit, like '5', not the word 'five'.")







"Now watch," she said. She ran it again and typed five.



Output:




Oops! Please type a digit, like '5', not the word 'five'.







"It didn't crash!" Timothy said. "It just printed the message and... stopped."






The Infinite Patience



"But for a game," Timothy mused, "I don't want it to stop. I want it to ask me again until I get it right."



"Then we combine our Safety Net with a Loop," Margaret said. "This is a very common pattern called an Input Validation Loop."



She modified the code to be persistent.




while True:
try:
user_input = input("Guess the number (1-10): ")
guess = int(user_input)

# Challenge: Check if it's actually 1-10
if guess < 1 or guess > 10:
print("Please pick a number between 1 and 10.")
continue # Loop back to the start

# If we get here, it's a number AND it's in range!
break

except ValueError:
# If int() crashes, we jump here immediately.
print("That wasn't a valid number. Please try again.")

print(f"Great! You chose {guess}.")







Timothy ran it.

He typed five. -> Program: That wasn't a valid number.

He typed 99. -> Program: Please pick a number between 1 and 10.

He typed 7. -> Program: Great! You chose 7.



"It’s surprisingly patient," Timothy laughed.



"It is," Margaret agreed. "It creates a safe space where the user can make mistakes without breaking the whole application."



She added one final, serious note. "Notice that I wrote except ValueError. Never just write except: by itself."



"Why not?" Timothy asked. "Wouldn't it be easier to catch everything?"



"If you catch everything," Margaret warned, "you might catch things you didn't mean to—like the user trying to quit the program. You want a safety net for the acrobat, not a giant dome that traps everyone inside the building. Be specific."






Margaret’s Cheat Sheet



Margaret opened her notebook to the "Error Handling" section.





  • The Concept: Exception Handling.

  • The Keywords:


  • try: "Attempt this code, but watch out for errors."

  • except: "If a specific error happens, run this code instead of crashing."


  • The Pattern: The Input Loop.


  • Use while True to keep asking.


  • Use break to escape the loop only when the input is valid.


  • The Golden Rule: Always catch specific errors (like ValueError) rather than using a bare except:. You want to fix the error, not hide it.




Timothy nodded. "So the int() function isn't dangerous anymore. It just needed a spotter."



"Exactly," Margaret smiled. "And now, your game is truly user-friendly."






In the next episode, Margaret and Timothy will face "The Identity Crisis"—where Timothy discovers that two things can look exactly the same but still be completely different objects.






Aaron Rose is a software engineer and technology writer at tech-reader.blog and the author of Think Like a Genius.

Ähnliche Beiträge
🔍 Verwandte News

Auch interessante Nachrichten The Secret Life of Python: The Safety Net ('try' and 'except')

Thematisch verwandte Begriffe: Secret, Life, Python, Safety · 6 Treffer

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Zum Aktualisieren ziehen
ZERO-DAY CVE-2026-96258 | A vulnerability has been found in onSite internet GmbH Auktion NG Auktio…
Advisory →
TTS Reader • tsecurity.de Voice
tsecurity.de Icon
tsecurity.de App
Offline-Lesen, Eilmeldungen & 0ms Ladezeit

Installiere tsecurity.de direkt auf deinen Home-Bildschirm für das ultimative Vollbild-Magazinerlebnis ohne Browser-Leisten.

Nächster Beitrag
Themen-Radar & Intelligence Matrix
Echtzeit-Taxonomie nach Angriffsvektoren & Plattformen

tsecurity.de Live Threat Radar

🔴 LIVE RADAR
MONITORING
AKTIV
CVE-DATENBANK
LIVE
🔍
Community Radar & Live Chat
Sentinel Bot online • Live-Stream
Dein Cluster: Security Explorer
Match:
lädt…
Verbindung zum Community-Stream wird aufgebaut...
Bearbeitungsmodus — Senden überschreibt deine Nachricht
Community-Puls — was gerade passiert
lädt…
Aktivitäten deiner Analysten
lädt…
Neues Thema oder Eilmeldung einreichen

Reiche interessante Links, Zero-Days oder Debatten ein. Die Community entscheidet per Upvote über die Veröffentlichung.

Heiß diskutierte Einreichungen
🔖 Gespeicherte Artikel
📂 Keine gespeicherten Artikel vorhanden.
Zurück Ziehen Vor
Links: vorheriger Artikel Rechts: nächster Artikel unten: schließen
News NIS-2 Frühwarnung Tier-1 Intel ⏱️ 3 Min vor 10 Min
Artikeldaten werden geladen...

Zurück: vorheriger Vor: nächster
↗ Original-Quelle
Social Reaktionen Deine Reaktion zählt
Einstufung & Relevanz-Poll 0 Stimmen
In sozialen Netzwerken teilen 1-Klick