Python Tutorial — Learn Python Step by Step
Key takeaway: Master Python programming from scratch — variables, loops, functions, OOP, file handling, and libraries — with clear human-readable explanations and runnable code examples.
Python Exception Handling
Exception handling uses try, except, else, and finally blocks to gracefully manage errors, run cleanup code, and keep programs running.
try / except / else / finally
# Full exception handling structure
try:
# Code that might raise an exception
file = open("data.txt", "r")
content = file.read()
number = int(content.strip())
except FileNotFoundError:
# Runs if file does not exist
print("File not found — using default value")
number = 0
except ValueError:
# Runs if content is not a valid integer
print("File content is not a number")
number = 0
else:
# Runs ONLY if no exception was raised
print(f"Successfully read number: {number}")
finally:
# ALWAYS runs — for cleanup
print("Done processing")
# Output depends on what happens:
# File missing → "File not found..." → "Done processing"
# Bad content → "File content is..." → "Done processing"
# Success → "Successfully read..." → "Done processing"Catching Multiple Exceptions
# Multiple except blocks (most specific first)
def parse_config(filename):
try:
with open(filename) as f:
data = f.read()
config = eval(data) # risky but illustrative
return config["database"]["host"]
except FileNotFoundError:
print(f"Config file {filename} not found")
except (KeyError, TypeError) as e:
# Catch multiple exceptions in one block
print(f"Invalid config structure: {e}")
except Exception as e:
# Catch-all for unexpected errors (use sparingly)
print(f"Unexpected error: {type(e).__name__}: {e}")
return None
# Catch any exception (last resort)
try:
risky_operation()
except Exception as e:
# Logs the error but does not hide KeyboardInterrupt/SystemExit
print(f"Error: {e}")The finally Block
# finally ALWAYS runs — even if you return or raise inside try/except
def divide(a, b):
try:
result = a / b
return result
except ZeroDivisionError:
return None
finally:
print("divide() completed") # always prints
print(divide(10, 2)) # "divide() completed" then 5.0
print(divide(10, 0)) # "divide() completed" then None
# Common use: resource cleanup
connection = None
try:
connection = connect_to_database()
connection.execute("SELECT * FROM users")
except DatabaseError as e:
print(f"Query failed: {e}")
finally:
if connection:
connection.close() # always close, even on error
print("Connection closed")Practical Error Handling Patterns
# Pattern 1: Retry with backoff
import time
def fetch_with_retry(url, max_retries=3):
for attempt in range(max_retries):
try:
response = make_request(url)
return response
except ConnectionError:
if attempt < max_retries - 1:
wait = 2 ** attempt # exponential backoff
print(f"Retry {attempt + 1} in {wait}s...")
time.sleep(wait)
else:
raise # re-raise on final attempt
# Pattern 2: Input validation loop
def get_positive_number():
while True:
try:
value = int(input("Enter a positive number: "))
if value <= 0:
raise ValueError("Must be positive")
return value
except ValueError as e:
print(f"Invalid: {e}. Try again.")
# Pattern 3: Graceful degradation
def load_user_settings(path):
"""Load settings from file, fall back to defaults on any error."""
defaults = {"theme": "light", "font_size": 14, "language": "en"}
try:
import json
with open(path) as f:
settings = json.load(f)
# Merge with defaults (user settings override)
return {**defaults, **settings}
except (FileNotFoundError, json.JSONDecodeError, PermissionError):
return defaultsBest Practices
# DO: Catch specific exceptions
try:
value = my_dict[key]
except KeyError:
value = default
# DON'T: Bare except catches everything (including Ctrl+C!)
# try:
# do_something()
# except: # BAD — catches KeyboardInterrupt too
# pass
# DO: Use context managers instead of try/finally for files
with open("file.txt") as f:
content = f.read()
# File is automatically closed, even if an error occurs
# DO: Log errors before handling them
import logging
try:
process_order(order)
except PaymentError as e:
logging.error(f"Payment failed for order {order.id}: {e}")
notify_customer(order, "payment_failed")
raise # or handle gracefullyelseruns only if no exception occurred — put success logic there.finallyalways runs — use it for cleanup (closing files, connections).- Catch specific exceptions, not bare
except:which hides bugs. - Use
withstatements (context managers) instead of try/finally for resources. - Log errors before handling them — silent failures are hard to debug.
Python Programming Tutorial — Learn Python in a practical, step-by-step way. According to the official Python documentation, Python emphasizes code readability and simplicity, making it ideal for beginners.
Related tools: Python Online Compiler | Python Examples | JavaScript Tutorial | Java Tutorial
Python Career & Learning Guide
Python is the world's most popular programming language for beginners, data science, AI/ML, web development, and automation. This tutorial teaches Python step-by-step with clear explanations and runnable code examples in our free Python Compiler.
Why Learn Python in 2026?
- #1 Most Popular Language: Ranked first on TIOBE, Stack Overflow, and GitHub.
- AI and Data Science: The primary language for machine learning (TensorFlow, PyTorch, scikit-learn) and data analysis (Pandas, NumPy).
- Web Development: Django and Flask power scalable backends at companies like Instagram and Spotify.
- Automation & Scripting: Automate files, emails, web scraping, and data processing in minutes.
Python vs Other Languages
| Feature | Python | Java | JavaScript | C++ |
|---|---|---|---|---|
| Syntax | Very clean, readable | Verbose | Moderate | Complex |
| Typing | Dynamic, strong | Static, strong | Dynamic, weak | Static, strong |
| Best For | AI/ML, Data, Web | Enterprise, Android | Web Frontend/Backend | Systems, Games |
| Learning Time | 2–4 weeks basics | 4–6 weeks basics | 3–4 weeks basics | 8–12 weeks basics |
Frequently Asked Questions
Do I need prior programming experience to learn Python?
No! Python is specifically designed to be beginner-friendly. This tutorial starts from zero and builds up gradually.
Which Python version should I use?
Python 3.10+ is recommended. All examples in this tutorial use Python 3 syntax.
Is this Python tutorial completely free?
Yes, 100% free with no registration or sign-up required. Access all lessons and code examples anytime.