In this article, we’ll cover three underrated but super important Python habits that every developer should learn early.
We’ll talk about how to isolate your projects using virtual environments, keep sensitive information safe with .env files, and use try/except blocks to stop your code from crashing when things don’t go as planned.
These might sound “advanced,” but trust me, they’re pretty simple to use, and they’ll instantly level up the way you build things in Python. Let’s dive in!
Use Virtual Environments
Ever installed a package in one project, then broke another one by accident? So, this is where virtual environments save the day.
When you create a virtual environment, you’re making a little sandbox. Everything you install, packages, dependencies, tools — stays inside that sandbox, isolated from the rest of your system.
Create the Virtual Environment
python -m venv venv
This creates a folder named venv/ that holds all the files for your virtual environment.
Then, activate the virtual environment using the following command.
source venv/bin/activate
You’ll know it’s active when you see (venv) at the start of your terminal prompt.
Now, any package you install with pip will go inside that environment and not system-wide. When you’re finished working, type:
deactivate
And you’re back to your normal system environment.
Keep Secrets Safe with .env Files
So, you just got your first API key. Maybe for OpenAI, Stripe, or a weather API. You copy-paste it right into your Python file like this:
API_KEY = “abc123supersecretkey”
Cool, it works. But then, you push your code to GitHub. And just like that, your API key is now public. Bots are scanning GitHub 24/7 for stuff like that. Your account might get suspended or billed for thousands of requests you didn’t make.
That’s why you need to use .env files. A .env file is a simple text file where you store sensitive stuff like API keys, database passwords, secret tokens, etc.
Install the Library
In your virtual environment, run:
pip install python-dotenv
Then, in your project folder, make a file called .env (no filename, just .env as the name). Inside, add your secrets like this:
API_KEY=abc123supersecretkey
DB_PASSWORD=hunter2
DEBUG=True
No quotes, no commas, just key=value format.
Load it in your Python Script
Now, use it in your code like this:
from dotenv import load_dotenv
import os
# Load environment variables from .env file
load_dotenv()
api_key = os.getenv("API_KEY")
db_password = os.getenv("DB_PASSWORD")
print("Your key is:", api_key)
If everything’s set up right, your script will now safely access your secrets without ever hardcoding them into your code.
Use try/except to Keep Your Code from Crashing
So, you’re writing a Python script. Everything’s going smoothly… until a user enters bad input. Or your internet connection drops, and your whole program crashes.
Sound familiar? That’s where try/except comes in. It’s like putting safety nets around the risky parts of your code.
Let’s say you wrote this:
number = int(input("Enter a number: "))
print(10 / number)
Looks fine, right? Until someone types:
0 or hello
Python doesn’t like dividing by zero or converting letters into numbers. It will throw an error and stop the program.
How try/except Helps
You can wrap that risky code in a try block and catch specific problems using the except.
try:
number = int(input("Enter a number: "))
result = 10 / number
print("Result:", result)
except ZeroDivisionError:
print("You can't divide by zero, buddy!")
except ValueError:
print("That's not even a number!")
print("Program continues...")
Output:
Enter a number: hello
That's not even a number!
Program continues...
No crash, just a friendly message, and the rest of your code still runs.
Conclusion
By using virtual environments, you’re keeping your projects clean and conflict-free. With .env files, you’re protecting your sensitive info like a pro. And, using try/except, you’re writing code that can handle unexpected crashes.
The tips might seem small, but they’re the kind of behind-the-scenes practices that help turn good projects into great ones. So, next time you start a new Python project, bring these habits with you. You’ll thank yourself later.
Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered
Author comment test. Experts have done special research on the topic and estimate that at least 65% of all pictures on the internet are of naked women. In addition, about 28,000 internet users are watching X rated videos at any given time.
Ipsam voluptatem anim ea risus erat litora! Amet congue eaque, velit earum elit, potenti, minus error modi aptent congue mattis nec arcu, occaecati aenean, eum viverra, anim turpis, irure? Luctus corrupti! Adipisci excepturi morbi. Qui eum eleifend quis deleniti veritatis? Sociis euismod, malesuada eaque tortor aenean, ridiculus quisquam occaecati sapien.
Voluptates magnis placeat autem cillum rhoncus fusce ornare soluta aptent erat maxime, sociosqu, incididunt. Eiusmod, iaculis? Deleniti convallis, praesentium quia, vel maecenas impedit vestibulum? Conubia sagittis dignissim iure dapibus, sint! Nibh dolore doloremque sem magnam consequuntur? Sem curabitur nemo nascetur, ad cubilia semper est totam condimentum pretium soluta, suscipit, mollis.
Author comment.
Header one
Header two
Header three
Header four
Header five
Header six
Blockquote Tests
Blockquote:
This part isn’t quoted. Here’s a longer quote:
And some trailing text.
Table Layout Test
List Type Tests
Definition List
Unordered List (Nested)
Ordered List
HTML Element Tag Tests
All other HTML tags listed in the FAQ:
Here is the address for Automattic, using the
355 1st Street Suite 202<address>
tag:San Francisco, CA 94105
United States
This is an example of an
<anchor>
(otherwise known as a link). This abbr. is an example of an <abbr> tag in the middle of a sentence. Here is a TLA showing off the<acronym>
tag. What, you want to see some over-sized text using the<big>
tag? Can you cite a reference for that, using the<cite>
tag? Have you noticed that all of the tag names are displayedin code-form
, using the<code>
tag? Similarly, I could emulate keyboard text, using the<kbd>
text tag, or emulate teletype text using the<tt>
tag.Oh no! I wrote something incorrectly.
I’d better delete it, using the<del>
tag. I could alternately strike something out using the<strike>
tag, or strike something out using the<s>
tag. So many choices, which I emphasize using the<em>
tag. Just to clarify, this is some inserted text, that I’ll highlight using the<ins>
tag.Need to display completely unformatted text, such as a large block of code? Use the
<pre>
tag, which lets you display:Want to quote the WordPress tagline
? Use the<q>
tag to add quotes around it. This is strong text (otherwise known as bold), using the<strong>
tag.Need to write H2O or E = MC2? You may find great use for subscripting text using the
<sub>
tag, or for superscripting text using the<sup>
tag. Need to call out a variable? Use the<var>
tag.Div and Span Tests
Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
<div>
tag.Sed odio nibh, tincidunt adipiscing, pretium nec, tincidunt id, enim. Fusce scelerisque nunc vitae nisl.
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. This is a span inside of a paragraph, using the
<span>
tag. Sed odio nibh, tincidunt adipiscing, pretium nec, tincidunt id, enim. Fusce scelerisque nunc vitae nisl.Anonymous person pretending to be Matt.
LOL
Eaque aenean donec ac quae porro mus phasellus sem mollit aliquid distinctio, nascetur aliquam magnis officia fermentum similique.
Elit porro proident excepturi sit dolores? Voluptatibus. Tempus, a, blanditiis elementum proin! Ligula voluptatem congue.
Deleniti voluptates molestie faucibus quasi condimentum felis quos laborum, laudantium mollis perspiciatis pariatur impedit penatibus varius ipsa perspiciatis?
Eius debitis, duis diamlorem placeat vulputate? Similique iure commodi at, doloribus reprehenderit? Sem aute condimentum.