Skip to content
Visual explainer 3h to learn 5 steps

Git basics for your projects

Commit, branch and push your projects to GitHub.

By Invicly Tech, , in Python Programming from Zero. About 12 minutes to read.

Topic 28 of 34

In short

Git records snapshots of your project called commits, so you can see history, undo mistakes and try ideas on branches. Pushing to GitHub backs up your work and lets others see it.

Explained simply

Git is a tool that remembers every saved version of your project. Each saved version is called a commit. If you break something, you can see exactly what changed and go back. If you want to try a risky idea, you can do it on the side and throw it away if it fails.

Saving a version takes two steps. First you choose which changes to include with git add; this is called staging. Then git commit saves them with a short message saying what you did and why. The two steps let you split a messy afternoon of work into clean, separate commits.

A branch is a separate line of work. You make a branch for a new feature, commit on it as much as you like, and main stays safe and working. When the feature is done, you merge it back into main.

GitHub is a website that stores a copy of your repository online. Pushing your commits there backs up your work, lets you work from other computers, and shows your projects to others. For a learner, a GitHub profile full of small finished projects is also a great portfolio.

Press Play on a diagram to walk through it one step at a time.

SequenceFrom edit to GitHub
Working folder
Staging area
Local repo
GitHub
  1. 1git add file.py
    Working folder to Staging area: git add file.py
  2. 2git commit -m "msg"
    Staging area to Local repo: git commit -m "msg"
  3. 3git push
    Local repo to GitHub: git push
  4. 4git fetch / pull
    GitHub to Local repo: git fetch / pull
  5. 5merge updates files
    Local repo to Working folder: merge updates files
CompareUndo tools: which one when
Not committed yet
  • git restore --staged f: unstage
  • git restore f: discard edits
  • Edits gone for good with restore
  • Nothing shared, no risk to others
Committed, not pushed
  • git commit --amend: fix last commit
  • git reset --soft HEAD~1: uncommit, keep changes
  • Rewrites local history only
  • Fine because nobody has it
Already pushed
  • git revert ID: new undo commit
  • History stays intact
  • Safe for shared branches
  • Never force-push shared main

In depth

What a commit really is

A Git repository is your project folder plus a hidden .git folder that stores the history. A commit is a snapshot of every tracked file at one moment, plus the author, the date, the message and a pointer to the previous commit (its parent). Each commit gets an ID, a long hash like 3f9a1c2..., which you usually shorten to the first seven characters.

Because each commit points to its parent, history forms a chain. A branch is just a name that points to one commit, and HEAD is Git's way of saying "the branch you are on now". When you commit, the current branch name moves forward to the new commit. That is why creating a branch is instant: Git only writes a tiny pointer, it does not copy any files.

  • git log --oneline --graph --all shows the history as a graph
  • git show 3f9a1c2 shows one commit's changes
  • git diff shows unstaged changes; git diff --staged shows what will be committed

Good commits and how to undo mistakes

A good commit contains one logical change, such as "Add CSV export" or "Fix total for empty list", and the code works after it. Write the subject line in the imperative mood, short (around 50 characters), and add a body after a blank line if the reason is not obvious. git add -p lets you stage only some parts of a file, so unrelated edits can go into separate commits.

Most mistakes are easy to undo. git restore --staged file unstages it but keeps your edits. git restore file throws away unstaged edits for good, so be careful. git commit --amend fixes the last commit's message or adds a forgotten file, but only do that before pushing. For a commit already pushed and shared, use git revert followed by its ID: it creates a new commit that undoes the old one, without rewriting history.

A .gitignore that fits Python projects

Some files must never be committed: your virtual environment (.venv/), bytecode caches (__pycache__/ and *.pyc), tool caches (.pytest_cache/, .ruff_cache/, .mypy_cache/), build output (dist/, build/, *.egg-info/), editor folders, and above all secrets in .env files. List them in a file named .gitignore at the repository root. GitHub publishes a ready-made Python template, which is a good start.

Pattern rules: a trailing slash matches only folders, a leading slash anchors to the repository root, * matches anything except a slash, and ! re-includes something excluded earlier. One surprise: .gitignore only affects untracked files. If a file is already committed, ignoring it does nothing until you run git rm --cached file, which stops tracking it but keeps it on disk.

  • .venv/ and __pycache__/ and *.pyc
  • .env (commit a .env.example with dummy values instead)
  • git check-ignore -v path explains which rule matched

Branches, merges and conflicts

git switch -c add-export creates a branch and moves to it; git switch main goes back. When you run git merge add-export on main, there are two cases. If main has not moved since you branched, Git just slides the main pointer forward to your latest commit: a fast-forward, with no new commit. If both branches have new commits, Git creates a merge commit with two parents.

If both sides changed the same lines, Git cannot choose and reports a conflict. The file then contains both versions between markers: <<<<<<< HEAD, your current branch's version, =======, then the other branch's version, ending with >>>>>>> and the branch name. Edit the file to the correct final text, delete the markers, git add the file, and git commit to finish. git merge --abort cancels and returns to before the merge.

FlowResolving a merge conflict
  1. 1
    git merge feature

    CONFLICT (content): Merge conflict in report.py

  2. 2
    git status

    Lists files with conflicts as both modified

  3. 3
    Edit the file

    Keep the right code, delete the markers

  4. 4
    git add report.py

    Marks the conflict as resolved

  5. 5
    git commit

    Creates the merge commit

Pushing to GitHub, and a README people can use

Create an empty repository on GitHub (without adding a README there, so histories do not clash). Then connect and push: git remote add origin with the repository URL, git branch -M main to make sure your branch is called main (older Git versions default to master), and git push -u origin main. The -u sets the upstream, so later a plain git push and git pull know where to go. git pull is a fetch (download new commits) followed by a merge.

GitHub does not accept your account password for Git over HTTPS. Use the GitHub CLI (gh auth login), a personal access token, or an SSH key with a git@github.com: URL. A README.md at the root is the front page of the repository. It should say what the project does, how to install it, one or two usage examples with real commands, and how to run the tests.

MapWhat a useful README contains
README.md
  • What and why
    • One-sentence description
    • A screenshot or sample output
  • Install
    • python -m venv .venv
    • pip install -r requirements.txt
  • Usage
    • 2 or 3 real commands
    • Expected output
  • Development
    • How to run tests
    • How to run Ruff

Learn it in 5 short steps

About 35m each. Track them with a timer in your plan.

  1. 1
    Initialise a repo and make commits~35m
  2. 2
    Write a useful .gitignore~35m
  3. 3
    Create and merge branches~35m
  4. 4
    Push a project to GitHub~35m
  5. 5
    Write a clear README~35m

Key points

  • git status shows what changed; git diff shows exactly how.
  • Stage with git add, then commit with a short message saying why.
  • Create a branch per feature: git switch -c add-export.
  • A .gitignore keeps .venv/, __pycache__/ and secrets out of the repo.
  • A README explains what the project does and how to run it.

Key terms

Tap a card to flip it. 0/6 known

Examples

bash
git init
printf ".venv/\n__pycache__/\n.env\n" > .gitignore
git add .
git commit -m "Initial commit"

git switch -c add-export
# ...edit files...
git commit -am "Add CSV export"
git switch main
git merge add-export

git remote add origin https://github.com/you/tracker.git
git push -u origin main

Fixing three everyday mistakes

Mistake 1: you staged notes.txt by accident; unstage it and keep the file. Mistake 2: the last commit message has a typo and is not pushed yet; amend it. Mistake 3: .env with a real password was committed; add it to .gitignore and stop tracking it. The password is still in older commits, so treat it as leaked and change it. Finally, revert a bad commit that was already pushed.

bash
git restore --staged notes.txt          # unstage, keep the edits
git commit --amend -m "Add CSV export"  # fix last message (not pushed yet)

echo ".env" >> .gitignore
git rm --cached .env                    # stop tracking, keep the file on disk
git commit -m "Stop tracking .env"
# then rotate the leaked password: it is still in history

git log --oneline -5                    # find the bad pushed commit, e.g. a1b2c3d
git revert a1b2c3d                      # new commit that undoes it

A feature branch with a conflict

Step 1: create a branch and change how totals are rounded. Step 2: meanwhile main changed the same line. Step 3: merging reports a conflict, and the file shows both versions between markers. Step 4: choose the final line, delete the markers, stage and commit. Step 5: delete the merged branch to keep things tidy.

bash
git switch -c fix-rounding
# edit report.py, then: git commit -am "Round totals to 2 places"
git switch main
git merge fix-rounding
# CONFLICT (content): Merge conflict in report.py
# report.py now contains:
#   <<<<<<< HEAD
#       return round(total)
#   =======
#       return round(total, 2)
#   >>>>>>> fix-rounding
# keep the correct line, delete the 3 marker lines, then:
git add report.py && git commit --no-edit
git branch -d fix-rounding

Quick reference

  • git status and git diff first; git diff --staged shows what the next commit contains
  • git add -p stages parts of a file, so each commit stays focused
  • git switch -c name creates a branch; git switch main goes back
  • git log --oneline --graph --all shows branches and merges
  • Ignoring a tracked file needs git rm --cached file as well
  • Amend or reset only unpushed commits; use git revert for pushed ones
  • git push -u origin main once; later just git push and git pull
  • A committed secret is leaked even after deletion: rotate it

Common mistakes

  • Committing passwords or API keys; they stay in history even if deleted later.
  • Huge commits that mix unrelated changes.
  • Messages like "stuff" that explain nothing.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1You added secrets.txt to .gitignore, but git status still shows it as modified. Why?

Question 2

2Which command safely undoes a commit that teammates have already pulled?

Question 3

3You merge feature into main and main has no new commits since you branched. What happens?

Question 4

4What does git add do?

Question 5

5git push asks for a password and rejects your GitHub account password. What should you use instead?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Turn a project folder into a repository with a Python .gitignore and a first commit, and check that .venv is not included.

  2. Exercise 2medium

    Create a branch add-readme, commit a README.md on it, merge it into main, delete the branch and show the history graph.

  3. Exercise 3hard

    Publish the project to a new empty GitHub repository, set the upstream, then push a feature branch so it can be opened as a pull request.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

What is the difference between Git and GitHub?
Git is the version control program that runs on your computer. GitHub is a website that hosts Git repositories and adds pull requests, issues and collaboration features.
What is the difference between git fetch and git pull?
fetch downloads new commits from the remote but does not change your files. pull does a fetch and then merges (or rebases) them into your current branch.
Should my branch be called main or master?
Either works, but main is the default on GitHub. Set git config --global init.defaultBranch main so new repositories start with main.
I committed an API key. Is deleting the file enough?
No. It is still in the history, and if it was pushed, assume it is compromised. Revoke and replace the key first, then clean the history with a tool like git filter-repo if needed.

Go deeper

ShareXLinkedInWhatsApp