23 Python Tips and Tricks with Examples
Write clearer Python with practical tips for strings, loops, dictionaries, files, functions, and debugging.
2026-10-20 ยท 4 min read
Small habits can make Python programs easier to read, test, and maintain. Here are practical Python tips and tricks with short examples you can try in your own projects.
1. Use f-strings to format text
F-strings let you include values directly inside a string. Put f before the opening quote and wrap each expression in braces:
name = "Mina"
score = 92
print(f"{name} scored {score} points.")
Output:
Mina scored 92 points.
You can also format numbers, such as showing two decimal places:
price = 12.5
print(f"Price: ${price:.2f}")
2. Loop with enumerate() when you need an index
Instead of maintaining a counter yourself, use enumerate():
fruits = ["apple", "orange", "pear"]
for index, fruit in enumerate(fruits, start=1):
print(f"{index}. {fruit}")
This starts numbering at 1 while keeping the list's normal zero-based indexing unchanged.
3. Use zip() to process related lists
zip() pairs items from iterables together:
names = ["Mina", "Dara", "Sok"]
scores = [92, 85, 98]
for name, score in zip(names, scores):
print(f"{name}: {score}")
By default, iteration stops when the shortest iterable runs out. Make sure that behavior fits your data.
4. Use a comprehension for simple transformations
A list comprehension can make a straightforward loop more concise:
numbers = [1, 2, 3, 4, 5]
squares = [number ** 2 for number in numbers]
print(squares)
Output:
[1, 4, 9, 16, 25]
For more complex logic, a regular for loop is often easier to understand.
5. Use .get() to read an optional dictionary value
Use .get() when a key may not exist. It returns a default value instead of raising a KeyError:
user = {"name": "Mina"}
city = user.get("city", "Unknown")
print(city)
Output:
Unknown
Use user["city"] instead when the key is required and a missing key should be treated as an error.
6. Use with when working with files
The with statement closes a file when the block finishes, even if an error occurs:
from pathlib import Path
file_path = Path("notes.txt")
file_path.write_text("Practice Python every day.\n", encoding="utf-8")
contents = file_path.read_text(encoding="utf-8")
print(contents)
Choose an explicit encoding such as UTF-8 for text files. Use a path that is appropriate for your project and environment.
7. Keep functions focused and return results
A function is easier to reuse when it does one clear job and returns a value:
def calculate_total(prices):
return sum(prices)
items = [4.50, 2.25, 3.00]
total = calculate_total(items)
print(f"Total: ${total:.2f}")
Return a result for other code to use; use print() when you specifically want to display something to a person.
8. Handle only errors you expect
Use try and except when an operation can fail for a known reason. Keep the protected block small and handle the specific exception:
text = "42"
try:
number = int(text)
except ValueError:
print("Please provide a whole number.")
else:
print(f"Number: {number}")
Avoid catching every exception without a plan for what to do. That can hide problems that should be fixed.
9. Use clear names and constants
Choose names that explain what a value means. Use uppercase names for values intended as constants:
SECONDS_PER_MINUTE = 60
minutes = 5
seconds = minutes * SECONDS_PER_MINUTE
Clear names reduce the need for comments that merely repeat what the code already says.
10. Read tracebacks from the bottom up
When Python displays a traceback, start with the final line to see the exception type and message. Then inspect the file name and line number immediately above it to find where the error occurred.
Test small pieces of code as you build them, and use the traceback to guide your next check instead of changing several things at once.