Day 14 of 80

Environment Variables & Git Basics

Phase 1: Python Foundation

What You'll Build Today

Today is a turning point. For the last two weeks, you have been writing code that runs on your machine, likely inside a single file. Today, we are going to professionalize your workflow. We are going to stop "hardcoding" secrets and start managing your code history like a real software engineer.

You are going to build a Secure Project Skeleton. This is the exact setup used by professional developers at Google, Meta, and OpenAI to keep their credentials safe.

Here is what you will learn and why:

* Environment Variables (.env): Because putting passwords directly in your code is like leaving your house key taped to the front door.

* The os Library: Because your Python script needs to talk to your operating system to find those hidden keys.

* Git Initialization: Because you need a "Save Game" feature for your code. If you break something, you need to be able to go back.

* The .gitignore File: Because there are some files (like your API keys) that should never, ever be saved to the public history of your project.

The Problem

Let's imagine a scenario. You have spent weeks building a specialized chatbot using the OpenAI API. It works perfectly. You are so proud that you decide to upload the code to GitHub (a site where developers share code) to show a potential employer.

Here is what your code looks like:

# my_chatbot.py

# DANGER: This is what we are trying to avoid!

import openai

# You pasted your real key right here

api_key = "sk-proj-1234567890abcdef1234567890abcdef"

client = openai.OpenAI(api_key=api_key)

print("Chatbot initialized!")

You upload this file. You go to sleep.

While you are sleeping, automated "scraper bots" that scan GitHub 24/7 find your code. They recognize the pattern sk-proj.... Within seconds, they copy your key. They use your key to generate millions of words of spam or run expensive AI models for their own businesses.

You wake up to an email from OpenAI: "Your credit card has been charged $1,500."

This happens every single day to new developers.

Beyond the security risk, hardcoding variables is annoying. If you change your API key, you have to find every single Python file where you pasted it and update it manually.

There has to be a way to keep your keys separate from your code, so you can share the code without sharing the keys.

Let's Build It

We are going to fix this using Environment Variables. These are variables set outside your Python script, usually in a hidden file on your computer. Your Python script will just ask the computer, "Hey, do you have a variable named API_KEY?"

Step 1: Install python-dotenv

Python doesn't read hidden configuration files by default. We need a popular library called python-dotenv to help us.

Open your terminal (Command Prompt or Shell) and run:

``bash

pip install python-dotenv


Step 2: Create the .env file

In your project folder, create a new file named exactly .env. Note the dot at the beginning. This usually indicates a "hidden" or system file.

Inside this file, paste your fake API key. Do not use quotes and do not put spaces around the equals sign.

File:
.env
OPENAI_API_KEY=sk-proj-this-is-my-secret-key-12345

DATABASE_PASSWORD=super_secret_password

Step 3: Access the variables in Python

Now, let's write a Python script that reads this file. We will use the os module (built into Python) and the dotenv library we just installed.

File: main.py
import os

from dotenv import load_dotenv

# 1. Load the variables from the .env file into the system's memory

load_dotenv()

# 2. Ask the system for the specific variable

api_key = os.getenv("OPENAI_API_KEY")

db_pass = os.getenv("DATABASE_PASSWORD")

# 3. Check if it worked

if api_key:

print("Success! I found the API key.")

# We print the first few characters just to verify, never the whole thing!

print(f"Key starts with: {api_key[:7]}...")

else:

print("Error: No API key found.")

if db_pass:

print("Success! I found the database password.")

Run the code:
bash

python main.py


Output:
Success! I found the API key.

Key starts with: sk-proj...

Success! I found the database password.

Why this matters: Your Python code no longer contains the secret. It just contains the name of the secret. You could email
main.py to a friend, and they wouldn't get your key.

Step 4: Initialize Git

Now we have a working project. We want to save our progress using Git. Git is a version control system—it tracks changes to your files over time.

In your terminal, inside your project folder, run:

bash

git init


This sets up a hidden folder .git that tracks changes.

Step 5: The Safety Net (.gitignore)

This is the most critical step. Before we save our files to Git, we must tell Git specifically to ignore the
.env file. If we don't, Git will save the .env file (and your secrets) into the history.

Create a new file named .gitignore (again, note the dot).

File: .gitignore
# Ignore the environment file containing secrets

.env

# Ignore Python cache files (these are junk files Python creates automatically)

__pycache__/

*.pyc

Step 6: Add and Commit

Now that we have a safety net, we can tell Git to look at our files.

  • Check Status: Run this to see what Git sees.
  • bash

    git status

        You should see main.py and .gitignore listed as "Untracked files". You should NOT see .env. If you see .env, check your .gitignore file again!
    
    
  • Add Files: This stages the files to be saved.
  • bash

    git add .

        (The . means "add all files in this folder, except the ignored ones").
    
    
  • Commit: This actually saves the snapshot.
  • bash

    git commit -m "Initial commit: Setup project with environment variables"

    ` Output:
    [master (root-commit) a1b2c3d] Initial commit: Setup project with environment variables
    

    2 files changed, 20 insertions(+)

    create mode 100644 .gitignore

    create mode 100644 main.py

    You have now successfully created a secure, version-controlled Python project.

    Now You Try

    It is time to reinforce these habits.

  • Add a Configuration Variable:
  • Add a new line to your .env file: APP_MODE=debug. Update your main.py to print "Running in Debug Mode" if that variable equals "debug", and "Running in Production" otherwise.

  • The "Example" File:
  • If you share your code, others won't have your .env file (because you ignored it). Create a file called .env.example. Inside, put OPENAI_API_KEY=your_key_here. Do not put the real key in it. Add this file to git (git add .env.example, git commit -m "Add example env"). This serves as instructions for other developers.

  • Break it (Safely):
  • Create a temporary file called secrets.txt. Put some text in it. Run git status. Notice it shows up. Now, add secrets.txt to your .gitignore file. Run git status again. Watch the file disappear from Git's radar.

    Challenge Project: The Secure AI Starter

    You are going to create a fresh project folder intended for a future AI application. You need to prove you can set it up securely from scratch.

    Requirements:
  • Create a new folder named secure_ai_bot.
  • Initialize it as a Git repository.
  • Create a .env file containing AI_MODEL_NAME=gpt-4 and MAX_TOKENS=100.
  • Create a .gitignore that excludes .env.
  • Create a script bot_config.py that loads these variables and prints a configuration summary string: "Bot configured to use [model] with limit of [tokens] tokens."
  • Commit ONLY the python script and the gitignore file to Git.
  • Example Output (when running python bot_config.py):
    Loading configuration...
    

    Bot configured to use gpt-4 with limit of 100 tokens.

    System ready.

    Hints:

    * Remember to pip install python-dotenv if you change virtual environments (though for now, you are likely in the same global environment).

    * Always write the .gitignore before running git add.

    * If git status shows .env, stop immediately and fix your ignore file.

    What You Learned

    Today was about professional discipline. You moved from "writing scripts" to "engineering software."

    * Security: You learned that secrets live in .env, never in .py files.

    * Access: You used os.getenv() to pull those secrets into your code safely.

    * Version Control: You used git init, add, and commit to save snapshots of your work.

    * Hygiene: You used .gitignore` to keep your project clean and secure.

    Why This Matters:

    In the coming days, we will start connecting to real external services. You will get real API keys. If you do not practice what you learned today, you risk leaking those keys. This setup is the foundation for every complex application you will build in Phase 2.

    Phase 1 Complete!

    You have mastered Python basics, file I/O, error handling, libraries, and now environment security.

    Tomorrow: We begin Phase 2. We are going to learn the language of the internet. We will explore HTTP, REST APIs, and how to make your Python code talk to servers halfway across the world.