Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Module 10: Version control with Git and GitHub

Objectives: LO-10.1, LO-10.2, LO-10.3, LO-10.4
Prerequisites: Module 9, and Git and a GitHub account from Setting up your computer
Time: about 5.5 hours: 2 for this reading, 2 for Lab 10, and 1.5 for the practice

This module teaches you to record every version of a project with Git, publish it on GitHub, and undo mistakes without losing work. You have probably saved files as report-final.py and report-final-2.py to keep an old version safe. Git replaces that habit: it keeps every version you ask it to, says what changed between any two, and lets you try an idea without touching the version that works. Project 1, after this module, is a game you build and publish this way, and every project after it lives in a Git repository too.

The commands run in a terminal, as in Module 9. This module shows the output of Git 2.43; other versions word a few messages differently.

Git and GitHub

Git is a program on your computer that records the history of a folder. Each time you ask, it saves a commit: a snapshot of the files you chose, with a message saying what changed, your name, and the time. The folder and its history together are a repository (or repo).

GitHub is a website that stores copies of Git repositories, shows them to other people, and lets them copy your work. Git works without GitHub: everything until “Publishing on GitHub” below happens on your computer alone. GitHub is one of several such sites; the commands work the same with the others.

Setting up Git

Check that Git is installed (setup’s “Before Module 10” step installed it):

git --version
git version 2.43.0

Any version from 2.28 on works with this module. Then tell Git who you are. Git writes your name and email address into every commit, and GitHub shows them to anyone who looks at your project, so use the private noreply address from GitHub’s email settings (setup, step 3), not your own. It has the form [email protected], with your account’s number and username:

git config --global user.name "Ada Lovelace"
git config --global user.email "[email protected]"
git config --global init.defaultBranch main
git config --global core.editor "code --wait"

Put your own name and address in the first two. --global saves each setting for every repository on your computer, in a file in your home folder, so you run these only once. The third names the first branch of every new repository main, which GitHub also uses (branches come later in this module). The fourth makes VS Code the editor Git opens when it needs you to write a message; --wait makes Git wait until you close that file. On macOS, the code command works only after you open VS Code’s Command Palette (View > Command Palette) and run Shell Command: Install ‘code’ command in PATH.

git config --global --list prints your settings, so you can check them:

user.name=Ada Lovelace
[email protected]
init.defaultbranch=main
core.editor=code --wait

A repository and its three areas

Creating a repository

This module puts the dice roller from the Module 9 practice, its worked example “a tool with options”, under version control. In the terminal, in py101, make a folder for the project and turn it into a repository with git init:

mkdir dice-roller
cd dice-roller
git init
Initialized empty Git repository in /home/ada/py101/dice-roller/.git/

git init made a hidden folder, .git, where Git keeps the history. Never edit it by hand, and don’t delete it: deleting .git deletes the history, and leaves only the files as they are now.

git status says what Git sees. Run it often; it is the command that answers “where am I?”:

git status
On branch main

No commits yet

nothing to commit (create/copy files and use "git add" to track)

Now copy dice.py from your m09 folder into this one. (If you skipped that exercise, save the code from the practice page as dice.py here instead.) cp copies a file, in PowerShell and in the other shells; the . at the end means “this folder”:

cp ../m09/dice.py .
git status
On branch main

No commits yet

Untracked files:
  (use "git add <file>..." to include in what will be committed)
	dice.py

nothing added to commit but untracked files present (use "git add" to track)

Untracked means the file is in the folder, but Git isn’t recording it.

Staging and committing

Git keeps a project in three areas:

AreaWhat it holdsCommand that moves work into it
The working treeYour files, as you see them in VS CodeEditing and saving
The staging areaThe changes that will go into the next commitgit add <file>
The repositoryEvery commit, in the .git foldergit commit

Saving a file changes only the working tree. git add copies the file’s current contents to the staging area, and git commit records everything staged as one new commit:

git add dice.py
git status
On branch main

No commits yet

Changes to be committed:
  (use "git rm --cached <file>..." to unstage)
	new file:   dice.py
git commit -m "Add a dice roller with --sides, --rolls, and --seed"
[main (root-commit) e82a6bf] Add a dice roller with --sides, --rolls, and --seed
 1 file changed, 33 insertions(+)
 create mode 100644 dice.py

-m gives the commit’s message. The output names the branch (main), says this is the repository’s first commit (root-commit), and gives the start of the commit’s hash, e82a6bf: a 40-character code, computed from the commit’s contents, that names the commit. Your hash will differ, because it depends on your name and the time too. create mode 100644 means Git recorded a new, ordinary file.

Why two steps instead of one? The staging area lets you choose what goes into each commit. If you fix a bug and also rename a variable somewhere else, you can stage and commit the fix alone, then the rename, and each commit says one thing.

Reading the history

git log lists the commits, newest first:

git log
commit e82a6bf73e7453ad2069f1ecf6deb9e1ed4d6636
Author: Ada Lovelace <[email protected]>
Date:   Fri Dec 4 12:37:25 2026 -0700

    Add a dice roller with --sides, --rolls, and --seed

When the output is longer than the terminal, Git shows it one screen at a time, in a program called a pager. Press Space for the next screen, and q to quit and get the prompt back.

Seeing what changed

Open dice.py in VS Code, add a line after the one that prints the total, and save:

    print("Total:", sum(results))
    print("Highest:", max(results))

git status now reports the file as modified: changed since the last commit, and not staged. git diff shows exactly what changed:

git diff
diff --git a/dice.py b/dice.py
index 5093c58..19b5d9a 100644
--- a/dice.py
+++ b/dice.py
@@ -27,6 +27,7 @@ def main():
     results = roll(args.sides, args.rolls)
     print("Rolls:", results)
     print("Total:", sum(results))
+    print("Highest:", max(results))
 
 
 if __name__ == "__main__":

Read a diff from the @@ line down. -27,6 +27,7 says that this part starts at line 27 and shows 6 lines of the old version and 7 of the new. A line starting with + was added, a line starting with - was removed, and lines starting with a space are unchanged context, shown so you can see where the change is. A changed line appears as a - line followed by a + line.

git diff compares the working tree with the staging area, so it shows the changes you haven’t staged yet. After git add dice.py, it prints nothing, and git diff --staged shows the same change, now staged. Commit it:

git add dice.py
git commit -m "Print the highest roll after the total"
[main f4a8dc4] Print the highest roll after the total
 1 file changed, 1 insertion(+)

git log --oneline prints one line per commit: the short hash and the message’s first line.

git log --oneline
f4a8dc4 Print the highest roll after the total
e82a6bf Add a dice roller with --sides, --rolls, and --seed

git show followed by a hash prints that commit’s message and its diff, so git show f4a8dc4 shows the line you added. You can type the first few characters of a hash, as long as no other commit starts the same way.

Writing commit messages

A commit message is a note to the next person who reads the history, who is often you, months later, wondering why a line changed. The conventions most projects follow come from the Git project itself (Pro Git, section 5.2):

MessageProblemBetter
updateSays nothing a reader can usePrint the highest roll after the total
Fixed stuffVague, and not imperativeReject --sides below 2 with an error
Add average, sort rolls, fix typo in helpThree changes in one commitThree commits, one for each
Changed line 30 from results to sorted(results)Says how, which the diff already showsPrint the rolls in order, lowest first

To write a body, give -m twice. Git makes each one a paragraph, with the blank line between:

git commit -m "Reject --sides below 2 with an error" -m "With 0 sides, randint crashed."

Or run git commit with no -m. Git opens a file in VS Code for the message; write the summary on the first line, a blank line, then the body, and save and close the file to finish the commit. A commit with an empty message is canceled.

Ignoring files with .gitignore

Some files in a project folder shouldn’t be in its history: a virtual environment, which anyone can rebuild from requirements.txt; the __pycache__ folders Python writes when it imports your modules (Module 9); and anything with a password or other secret in it. Give the project its own environment, as Module 9 did (python -m venv .venv on Windows, python3 -m venv .venv on macOS and Linux), and import dice once with python -c "import dice" (-c runs the code that follows it), which writes __pycache__. git status then lists both:

On branch main
Untracked files:
  (use "git add <file>..." to include in what will be committed)
	.venv/
	__pycache__/

nothing added to commit but untracked files present (use "git add" to track)

That is the output with Python 3.12. From Python 3.13, venv also writes a .gitignore inside the environment’s folder that ignores everything in it, so with a newer Python git status lists only __pycache__/. Ignore .venv/ in your project anyway, so that it stays out of the history for anyone who builds the environment with Python 3.12.

A file named .gitignore in the repository’s top folder lists what Git should leave alone. Create it in VS Code, with one pattern on each line:

__pycache__/
.venv/

A name ending in / matches a folder of that name, anywhere in the project, and everything in it. A * matches any characters, so *.log matches every file ending in .log, and a line starting with # is a comment. Now git status lists only .gitignore itself, which you commit, so that everyone who copies the project ignores the same files:

git add .gitignore
git commit -m "Ignore the virtual environment and Python's cache"

git check-ignore -v names the line that ignores a path, which helps when a pattern doesn’t do what you expected. It prints nothing for a path that isn’t ignored:

git check-ignore -v .venv __pycache__/dice.cpython-312.pyc dice.py
.gitignore:2:.venv/	.venv
.gitignore:1:__pycache__/	__pycache__/dice.cpython-312.pyc

The cache file’s name includes the version of Python that wrote it, so with Python 3.15 it is dice.cpython-315.pyc; type the name your __pycache__ folder holds. Two more things to know:

Never commit a password, an access token, or any other secret. A commit stays in the history even after a later commit deletes the file, and once it’s on GitHub, other people may already have copied it. If you publish a secret by mistake, change it at its source (a new password, a new token) as well as removing it.

A README for strangers

A README is the file that explains a project to someone who has never seen it. GitHub shows the README.md in a repository’s top folder below the list of files, so it’s the first thing a visitor, or an employer, reads. GitHub’s guide About READMEs lists what one usually covers: what the project does, why it is useful, and how to get started with it. For a program, that means:

  1. Its name, as a # heading, and one or two sentences on what it does.

  2. What a user needs first, such as a Python version or packages to install.

  3. The exact command to run it, and what it prints.

  4. Its options, if it has any.

A README is written in Markdown, the plain-text format these course pages use. Its basics:

You typeYou get
# Title, ## SectionHeadings, from the largest down
A blank line between lines of textA new paragraph
Lines starting with - A bulleted list
`dice.py`Code formatting, for names of files, commands, and options
Three backticks on a line, then lines of code, then three moreA block of code, shown exactly as typed
[Python](https://www.python.org/)A link

Here is the README for the dice roller, as README.md in the repository’s top folder:

# Dice roller

A command-line program that rolls dice and prints each roll, the total, and the highest roll.

## How to run

You need Python 3.12 or later. The program uses only Python's standard library, so there is
nothing to install. In a terminal, in this folder:

```bash
python dice.py --rolls 3 --seed 9
```

```text
Rolls: [4, 5, 3]
Total: 12
Highest: 5
```

Options:

- `--sides N`: the number of sides on each die (default 6)
- `--rolls N`: how many dice to roll (default 1)
- `--seed N`: a seed, so that a run can be repeated

VS Code shows how it will look: open the file, then the Command Palette, and run Markdown: Open Preview to the Side. Commit it:

git add README.md
git commit -m "Add a README that explains how to run the roller"

Publishing on GitHub

So far the history is only on your computer. Publishing puts a copy on GitHub, where others can see it and where it survives if your computer doesn’t.

Creating the repository on GitHub

  1. Sign in at https://github.com/. In the upper-right corner of the page, select +, then New repository.

  2. Name it dice-roller, the same as the folder, and give it a one-sentence description.

  3. Choose Public, so that others can see it.

  4. Leave every option that adds a file turned off: the README, the .gitignore, and the license. Your project already has its own, and GitHub’s guide warns that adding them here, to a project you are about to push, can cause a merge conflict.

  5. Select Create repository. GitHub shows an empty repository and its address, which looks like https://github.com/USERNAME/dice-roller.git, with your username.

Signing in to GitHub from Git

GitHub must know that a push comes from you, and Git can no longer send it your account’s password; GitHub removed password authentication for Git. Set up one of the two tools GitHub recommends for this before your first push. Each asks you to sign in to GitHub once, in your browser, and stores the result, so later pushes don’t ask:

Pushing

A remote is another copy of the repository that yours can send commits to. Add GitHub’s copy as a remote named origin, the usual name for the main one, and push your commits to it:

git remote add origin https://github.com/USERNAME/dice-roller.git
git push -u origin main

After a sign-in the first time, and a few lines of progress, the push ends with:

To https://github.com/USERNAME/dice-roller.git
 * [new branch]      main -> main
branch 'main' set up to track 'origin/main'.

git push origin main sends the main branch’s commits to origin, and -u remembers that pairing, so from now on git push alone does the same. git remote -v lists a repository’s remotes, in case you mistype the address; git remote set-url origin <address> fixes it.

Reload the repository’s page on GitHub: it shows your files, your README below them, and, under the commit count, the history with your messages.

A commit is still only on your computer until you push it. After the next commit, git status says so:

On branch main
Your branch is ahead of 'origin/main' by 1 commit.
  (use "git push" to publish your local commits)

Copying a repository

git clone <address> copies a repository from GitHub, history and all, into a new folder named after it, with origin already set up. Use it to get your project onto another computer, or to try someone else’s. If the copy on GitHub has commits that yours doesn’t (because you pushed them from your other computer, say), git pull brings them into your copy.

Undoing mistakes

Git can undo most mistakes, as long as the work was committed. Choose the command by where the mistake is:

The mistakeThe commandWhat it does
You edited a file and want the last committed version backgit restore <file>Replaces the file with its version in the staging area, which is the last commit’s unless you staged since. Your edits are gone for good.
You staged a change you don’t want in the next commitgit restore --staged <file>Takes the change out of the staging area and leaves it in the file
You committed a change that turns out to be wrong, and maybe pushed itgit revert <hash>Makes a new commit that undoes that commit’s changes. The history keeps both.

Restoring a file

Say you delete the line that prints the total by mistake, and save. git status reports dice.py as modified. Before you commit, get the last committed version back:

git restore dice.py

The command prints nothing, and git status reports nothing to commit, working tree clean. Be sure before you run it: Pro Git calls git restore <file> “a dangerous command”, because the edits you discard were never committed, so Git can’t bring them back.

Reverting a commit

Now say you commit a change, push it, and then decide it was a mistake: you shortened the labels to R: and T:, and they are harder to read. The first lines of git log --oneline show the commit:

9da3b10 Shorten the output labels to one letter
2fb580a Add a README that explains how to run the roller

git revert makes a new commit that changes the lines back:

git revert --no-edit 9da3b10
[main 4bc4eaa] Revert "Shorten the output labels to one letter"
 Date: Fri Dec 4 12:37:56 2026 -0700
 1 file changed, 2 insertions(+), 2 deletions(-)

Without --no-edit, Git opens the message in VS Code first, so you can say why you reverted; save and close it to finish. The history now has both commits, with the revert on top, and its message names the commit it undid. That is why revert is the safe way to undo a pushed commit: it adds to the history instead of changing it, so a copy someone cloned yesterday still agrees with yours. (Git also has commands that rewrite history, such as git reset; they are for commits you haven’t pushed, and this course doesn’t need them.)

Branches

A branch is a line of commits with a name. Your repository has one, main. Making another lets you try a change, commit as often as you like, and come back to main exactly as it was if the idea doesn’t work out. When it does work, you merge the branch into main.

Trying a change on a branch

git switch -c creates a branch and moves to it:

git switch -c sorted-rolls
Switched to a new branch 'sorted-rolls'

Change the line that prints the rolls to print("Rolls:", sorted(results)), then commit as usual. The commit goes on sorted-rolls, and main doesn’t change. git branch lists the branches, with a * beside the one you are on:

  main
* sorted-rolls

Switch back with git switch main, and look at dice.py in VS Code: the line is print("Rolls:", results) again, because Git changed the files to match main’s latest commit. Switching brings the branch’s version of every file with it. (Commit or restore your changes before you switch; if they would be overwritten, Git refuses to switch and says why.)

Merging

On main, merge the branch to bring its commits in:

git merge sorted-rolls
Updating 4bc4eaa..6c0eac0
Fast-forward
 dice.py | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

main had no new commits since the branch started, so Git could move main forward to the branch’s latest commit. That is a fast-forward. The branch has done its job, so delete it: git branch -d sorted-rolls. Its commits stay in main’s history. (-d refuses to delete a branch whose commits aren’t merged anywhere, and says so; -D deletes it anyway.)

When both branches have new commits, Git makes a merge commit that combines them. Say you add an average on a branch named average, and meanwhile, on main, you update the README’s example. git merge average opens VS Code with the message Merge branch 'average'; close it to accept, and Git prints:

Merge made by the 'ort' strategy.
 dice.py | 1 +
 1 file changed, 1 insertion(+)

(ort is the name of the method Git uses to combine the changes.) git log --oneline --graph draws the shape of the history. Its first lines show the two lines of work joining at the merge commit:

*   af825d1 Merge branch 'average'
|\  
| * b1a648d Print the average roll
* | 46f8e0a Show the sorted rolls in the README's example
|/  
* 6c0eac0 Print the rolls in order, lowest first

Merge conflicts

Git combines changes to different lines, or to different files, without help. When both branches changed the same lines, it can’t choose, and stops with a merge conflict. Say a branch named sum-label changed the total’s label to Sum:, and main changed it to Total of all rolls::

git merge sum-label
Auto-merging dice.py
CONFLICT (content): Merge conflict in dice.py
Automatic merge failed; fix conflicts and then commit the result.

Git has written both versions into dice.py, between conflict markers:

    print("Rolls:", sorted(results))
<<<<<<< HEAD
    print("Total of all rolls:", sum(results))
=======
    print("Sum:", sum(results))
>>>>>>> sum-label
    print("Highest:", max(results))

The lines between <<<<<<< HEAD and ======= are the version on the branch you are on (HEAD means your current commit), and the lines from ======= to >>>>>>> sum-label are the other branch’s. To resolve the conflict:

  1. Edit the file so it holds what you want: one version, the other, or a mix. Delete all three marker lines. Here, keep one line: print("Sum of all rolls:", sum(results)).

  2. Run the program to check that it works.

  3. Stage the file with git add dice.py, which tells Git the conflict is resolved.

  4. Run git commit with no -m. VS Code opens with the message Merge branch 'sum-label'; close it to finish the merge.

VS Code highlights the two versions in the file and offers Accept Current Change, Accept Incoming Change, and Accept Both Changes above them, which do step 1 for you. If you would rather not merge yet, git merge --abort puts everything back as it was before git merge.

Common misconceptions

BeliefWhat happensExample that breaks it
Saving a file saves it in GitOnly a commit records a versionAfter you save an edit, git status reports the file as modified, not committed
git add once makes Git record every later changegit add stages the file as it is at that momentEdit a file after staging it, and git status lists it under both “Changes to be committed” and “Changes not staged”
A commit goes to GitHubA commit stays on your computer until you pushgit status says Your branch is ahead of 'origin/main' by 1 commit.
Git and GitHub are the same thingGit runs on your computer; GitHub is a website that stores copies of repositoriesEverything before “Publishing on GitHub” in this module works with no internet connection
Adding a file to .gitignore removes it from the repositoryIt only keeps untracked files outA __pycache__ folder committed before the .gitignore stays tracked until git rm -r --cached __pycache__
Git can always bring back lost workGit can bring back only what was committedgit restore dice.py discards uncommitted edits for good
Deleting a branch deletes its workAfter a merge, its commits are part of maingit branch -d sorted-rolls leaves Print the rolls in order, lowest first in git log

Summary

Self-check

Answer each question before you open its answer.

  1. You edit dice.py and save it, then run git add dice.py, then edit and save dice.py again. What does git commit -m "…" record?

    Answer

    The file as it was when you ran git add: the first edit only. The second edit stays in the working tree, and git status still reports it as not staged. Run git add dice.py again to include it.

  2. In a diff, what do these lines mean?

    -    print("Total:", sum(results))
    +    print("Sum:", sum(results))

    Answer

    The line print("Total:", sum(results)) was replaced by print("Sum:", sum(results)). A changed line shows as the old line, removed (-), followed by the new one, added (+).

  3. Rewrite the commit message changed some stuff in the scoring so it follows the conventions, for a commit that makes a game give 2 points for a draw instead of 1.

    Answer

    For example, Give 2 points for a draw, in the imperative and specific about the change. If the reason isn’t obvious, add a body, such as “The rules say a draw is worth 2 points; 1 was a typo.” Other wordings that say what changed are fine.

  4. You pushed a commit that broke the program, and a classmate has already cloned your repository. Which command undoes the commit, and why that one?

    Answer

    git revert <hash>. It undoes the commit with a new commit, so the history only grows, and the classmate’s copy still agrees with yours; they get the fix with git pull. A command that removed the commit from the history would leave the two copies disagreeing.

  5. A merge stops with a conflict in game.py. What are the steps to finish it?

    Answer

    Edit game.py so it holds the version you want, deleting the <<<<<<<, =======, and >>>>>>> lines; run the program to check it; git add game.py; and git commit. Or run git merge --abort to go back to how things were before the merge.

Further reading