- CodeCraft by Dr. Christine Lee
- Posts
- 5 Python Tricks Every Newbie Should Know
5 Python Tricks Every Newbie Should Know
(That Will Make You Look Like a Pro)
TL;DR
Learn simple Python tips that will boost your coding confidence and make your code cleaner, faster, and more professional.
Introduction
Starting out with Python?
You’re in the right place!
In this tutorial, we’ll explore five tricks that beginners often overlook but will instantly elevate your Python game.
These are techniques used by experienced developers—and soon by you!
So, let’s dive in.
1. String Formatting with f-strings
Tired of clunky string concatenation with +
?
Say hello to f-strings!
Old way:
name = "Alexa"
age = 50
print("Hello, my name is " + name + " and I am " + str(age) + " years old.")
Pro way (f-strings):
name = "Alexa"
age = 50
print(f"Hello, my name is {name} and I am {age} years old.")
With f-strings, you can directly insert variables inside {}
brackets, making your code more readable and elegant.
You can even format numbers:
pi = 3.14159
print(f"The value of π rounded to 2 decimal places is {pi:.2f}.")
2. Using List Comprehensions
List comprehensions are a concise way to create lists.
They replace long for
loops with just a single line of code!
Traditional way:
squares = []
for i in range(10):
squares.append(i ** 2)
print(squares)
Pro way (List comprehension):
squares = [i ** 2 for i in range(10)]
print(squares)
Not only is it shorter, but it’s also easier to read!
You can even add conditional logic:
even_squares = [i ** 2 for i in range(10) if i % 2 == 0]
print(even_squares) # [0, 4, 16, 36, 64]
3. Handling Exceptions with try-except
Errors happen.
The trick is to handle them gracefully. Instead of your program crashing, use try-except
to manage errors.
Without exception handling:
number = int(input("Enter a number: "))
print(f"The result is {100 / number}")
# Crashes if the user enters 0 or non-integer input
With exception handling:
try:
number = int(input("Enter a number: "))
print(f"The result is {100 / number}")
except ValueError:
print("Please enter a valid integer.")
except ZeroDivisionError:
print("Division by zero is not allowed!")
This approach ensures your code keeps running even when unexpected input occurs.
Pro tip:
You can also use finally
to execute code that should run no matter what (like closing a file).
4. Reading and Writing Files
Reading from and writing to files in Python is easy, but many beginners overlook how powerful it can be.
Reading a file:
with open("sample.txt", "r") as file:
content = file.read()
print(content)
The with
keyword ensures the file is properly closed, even if an error occurs.
Now, let’s write something to a file:
Writing to a file:
with open("output.txt", "w") as file:
file.write("Hello, Python!")
This creates (or overwrites) a file named output.txt
with the content "Hello, Python!"
.
You can also use "a"
mode to append text without overwriting.
5. Using Lambda Functions
Sometimes you need a quick, anonymous function.
That’s where lambda functions come in.
They’re useful for short operations that don’t need a full def
block.
Traditional function:
def add(a, b):
return a + b
print(add(3, 5)) # 8
Using lambda:
add = lambda a, b: a + b
print(add(3, 5)) # 8
You can also use lambdas with Python’s sorted()
function to sort complex data structures:
students = [("Alexa", 90), ("Bob", 85), ("Charlie", 95)]
sorted_students = sorted(students, key=lambda x: x[1])
print(sorted_students) # [('Bob', 85), ('Alexa', 90), ('Charlie', 95)]
Lambdas are concise and powerful—use them wisely!
Summary
In this tutorial, we explored five essential Python tricks:
f-strings for better string formatting.
List comprehensions for concise loops.
try-except for error handling.
Reading and writing files for working with external data.
Lambda functions for quick, anonymous operations.
These tricks may seem small, but mastering them will improve your code and build your confidence as a developer.
Final Thoughts
Python’s beauty lies in its simplicity, and these tricks are great examples of that.
They’ll help you write cleaner, more efficient code—and give you that professional touch.
The more you practice, the more these techniques will become second nature.
Keep learning, keep coding, and most importantly, have fun!
Let’s Inspire Future AI Coders Together! ☕
I’m excited to continue sharing my passion for Python programming and AI with you all.
If you’ve enjoyed the content and found it helpful, do consider supporting my work with a small gift.
Just click the link below to make a difference – it’s quick, easy, and every bit helps and motivates me to keep creating awesome contents for you.
Thank you for being amazing!
🎉 We want to hear from you! 🎉 How do you feel about our latest newsletter? Your feedback will help us make it even more awesome! |