I/O and Error Handling
Interacting with Users and Handling the Unexpected
A robust program needs to be able to take user input, format its output nicely, and handle unexpected errors gracefully without crashing.
Getting User Input
The input()
function is the standard way to get input from the user in the console. It pauses the program and waits for the user to type something and press Enter. Important: input()
always returns the user\'s input as a string, even if they type numbers.
username = input("Enter your name: ")print("Hello, " + username)
# You must cast the input if you want to treat it as a numberage_str = input("Enter your age: ")age = int(age_str)print(f"You will be {age + 1} next year.")
Formatting Output with F-Strings
While you can concatenate strings with +
, a more powerful and readable way to format strings is with F-strings (formatted string literals). You prefix the string with an f
and place your variables directly inside curly braces {}
.
name = "Alice"item_count = 5total_price = 75.5
# F-string (recommended)print(f"Hello, {name}! You have {item_count} items in your cart.")# You can even format numbers!print(f"The total price is ${total_price:.2f}.")
The try...except
Block
Errors, called exceptions in Python, will stop your program if not handled. The try...except
block is Python\'s way of handling these exceptions gracefully.
- The code inside the
try
block is executed first. - If an error occurs in the
try
block, Python looks for a matchingexcept
block and executes its code. - If no error occurs, the
except
block is skipped. - The
else
block is optional and runs only if no exceptions were raised in thetry
block. - The
finally
block is also optional and runs no matter what, whether an exception occurred or not. It\'s often used for cleanup operations.
try: num_str = input("Enter a number: ") num = int(num_str) result = 100 / numexcept ValueError: print("That was not a valid number!")except ZeroDivisionError: print("You can\'t divide by zero!")except Exception as e: print(f"An unexpected error occurred: {e}")else: print(f"100 divided by {num} is {result}.")finally: print("Execution finished.")