$ run as a normal user# run as root (or with sudo)
What the course covers
How to use the Alta3 lab: the shell, Vim, and tmux.
- How to keep your code in GitHub or GitLab.
- Built-in functions, custom functions, and object methods.
- Lists and dictionaries: how to store and change data.
- Conditions and loops:
if,elif,else,while, andfor. - How to read and write files. How to import modules and install packages with
pip. - How to catch errors with
tryandexcept. How to write classes and inheritance. - Optional PCEP review: numbers, loops, data structures, and four mock exams.
Welcome to Alta3 Research Labs!
The first lessons explain the lab. You get a Linux machine and a user named student.
- The prompt
student@bchd:~$shows the user, the host, and the home folder. - Common commands are
pwd,ls,cd,mkdir, andtouch.mvmoves or renames a file.historyshows old commands.man lsopens the manual. - Each code block has a copy icon. Paste with right-click,
Shift+Insert, orCtrl+Shift+V. - If the terminal closes by accident, press
Enterto start a new session. - VIRGIL is the AI lab coach. You can ask it for help.
Required Tools
Vim is a modal editor. Press i to insert text. Press Esc to stop. Type :wq to save and quit. Type :q! to quit and drop your changes.
- tmux is a terminal multiplexer. It splits one window into many panes.
- Start a tmux command with
Ctrl+b. Press%to split left and right. Press"to split top and bottom. - After
Ctrl+b, the arrow keys move between panes.zzooms one pane.[enters scroll mode, andqleaves it.exitorCtrl+dcloses a pane.
Source Code Management
Lesson 006 compares GitHub and GitLab. Both work for this course. GitHub is the most popular. GitLab has built-in DevOps tools.
- You make a free account. You make a repository. You make a personal access token.
git config --global credential.helper storesaves your token for later pushes.user.nameanduser.emaillabel your commits.- Then you clone the repo and push your code. A good repo has a README and a license.
Foundational Python
Built-in functions are ready to use. len() counts items. range() makes a number sequence. sum() adds numbers. print() shows output.
print()has options.sep=changes the text between values.end=changes the line ending.- The interpreter is good for quick tests. A script file starts with
#!/usr/bin/env python3and runs withpython3 file.py. - You write custom functions with
def. A function can take arguments and return a value. It runs only when you call it. - A function can have a default argument.
def homer(sd="salad")uses "salad" when you pass nothing. - The functions lab has a broken function to fix. The challenge asks you to find the bad name or the missing call.
dir()lists an object's methods and attributes.help()shows the docs for one method. Methods use dot notation, as intrek.lower().- Lists are ordered and mutable. The first item is at index
0.list[1:3]slices a list. A list can hold mixed types. append()adds one item to the end.print(list[0])reads one item.len(list)counts the items.- Dictionaries hold key: value pairs inside
{}..keys()and.values()return the two sides. Use a key to get its value..get()is safe when a key may be missing. - The dictionary lab uses Pokémon records. It adds a key, changes a value, and prints all values.
ifruns code when a test is true.elifadds more tests.elseis the catch-all.whilerepeats while a test is true.forwalks through a collection.breakleaves a loop early.continueskips to the next turn.open()makes a file object. Modewoverwrites a file. Modeaadds to the end. Moderreads. Usewithso the file closes by itself.- A
forloop over a file reads one line at a time. This uses little memory. The log lab counts "Authorization failed" lines in a Keystone log. - The file lab downloads the log with
wgetfirst. Then the script opens it and counts each match with a loop. - A loop can hold logic. The vendor loop prints each name. The second loop adds an
iftest inside. - Modules are files of Python code.
import osandimport shutiluse the standard library.os.chdir()changes the current directory. shutilcopies and moves files. The modules lab changes the working directory so a relative path works.pipinstalls packages from PyPI.python3 -m venv myenvmakes a virtual environment.source myenv/bin/activateturns it on. The system Python stays clean.tryruns code that may fail.excepthandles the error.elseruns when there is no error.finallyalways runs. Name the error you expect, such asValueErrororKeyError.- One
trycan have manyexceptblocks. Each block handles a different error type. - A class is a blueprint.
classmakes it. A method is a function inside the class. An object is made from the class. A child class can inherit from a parent class. - The classes lab builds a dice game twice. The first version uses plain functions. The second uses a class with dice and roll methods.
- The guessing game lab mixes
random,input(), andiftests. The trivia challenge ignores upper and lower case when it checks an answer.
Optional- PCEP Certification Guide
The PCEP exam has 30 questions in 45 minutes. You need 70% to pass.
- Scientific notation writes
3e8for300000000.0. Number prefixes mark the base:0bfor binary,0ofor octal, and0xfor hex. - The guide covers scientific notation, binary, octal, and hex numbers. It also covers arithmetic and bitwise operators.
passdoes nothing.range()pairs withfor.for-elseandwhile-elsehave anelsethat runs when the loop ends withoutbreak.breakstops a loop.continueskips the rest of the turn and starts the next one.- List copies matter.
original[:]makes a new list.shallow = originalpoints to the same list. - A tuple cannot change after you make it. A list inside a list makes a matrix. A list of lists of lists makes a cube.
Nonemeans "no value". Recursion means a function calls itself, and it needs a base case. A name can be local or global.
PCEP Mock Exams
Four mock exams follow the PCEP format. Each question has a hidden answer.
- Read the question first. Say your answer in your head. Then open the answer and check.
- Each answer explains why it is right. Learn the rule, not just the letter.
- The exams repeat the core ideas. That helps you find weak spots before the real test.
Key commands and tools
python3starts the interpreter.python3 script.pyruns a file.vim file.pyopens a file in Vim. Pressito insert. PressEscto stop.Ctrl+b, then%splits a tmux pane.Ctrl+b, then"splits the other way.git add *,git commit -m "message", andgit push originsend work to GitHub.git clone <url>copies a remote repo to your machine.git config --global credential.helper storesaves the token.len(character_name),list(range(1, 11)),sum(force_levels),print("Total:", total, sep=" -> ")def report_ghost_sighting():defines a function. Call it asreport_ghost_sighting().dir("ncc 1701-D")shows string methods.help(trek.lower)shows help."text".upper()changes case.pikachu["type"],pikachu.update({"ability": "Quick Attack"}),pikachu.get("level")if x < 10:,elif,else,while x < 10:, andfor x in vendors:while True:withbreakstops a loop from the inside.with open("file.txt", "r") as foo:thenfoo.read()for line in foo:reads one line at a time.numbers = [1, 2, 3]thennumbers.append(4)adds one item.mkdir -p ~/mycode/lab/,chmod u+x script.py, andpython3 script.pyecho "text" > /tmp/test.txtwrites a short test file.python3 -m pip install pytestandpython3 -m pip freezepython3 -m venv myenvmakes a virtual environment.source myenv/bin/activateturns it on.man lsopens the manual. Pressqto quit.import os,os.chdir("/tmp"),import shutil,import random,random.randint(1, 6)try:withexcept ValueError:andfinally:class Player:withdef __init__(self):
Key terms
The words of this course in one table. Learn them before the quiz or exam.
| Term | Meaning |
|---|---|
| Argument | A value you give to a function when you call it. |
| Attribute | Data that belongs to an object. |
| Built-in function | A function that Python gives you, such as len() or print(). |
| Class | A blueprint for making objects. |
| Conditional | Code that runs only when a test is true. |
| Dictionary | A group of key: value pairs inside {}. |
| Exception | An error that stops the normal flow of a program. |
| Function | A named block of code that does one job. |
| Index | The position of an item in a list. The first item is at 0. |
| Inheritance | A child class takes features from a parent class. |
| Interpreter | The program that runs Python code line by line. |
| List | An ordered group of items that you can change. |
| Method | A function that belongs to an object, called with a dot. |
| Module | A file of Python code that you can import. |
| Mutable | Can be changed after it is made. |
| Object | A value made from a class. |
| Package | A bundle of Python code that you install with pip. |
| PCEP | An entry-level Python certificate exam. |
| Recursion | A function that calls itself. |
| Return | To send a value back from a function. |
| Slice | A part of a list, written as list[start:end]. |
| String | Text in Python, inside quotes. |
| Try/except | A block that runs code and handles errors. |
| Tuple | An ordered group of items that cannot change. |
| Virtual environment | A private space for one project's packages. |
Check yourself
Answer each question first, then open it to check the answer.
1What does len("Luke Skywalker") return?
14. The space between the two words counts as one character.
2How do you get the value for the key "type" from a dictionary named pikachu?
pikachu["type"]. If the key may be missing, use pikachu.get("type").
3What is the difference between "w" mode and "a" mode in open()?
Mode w erases the old file and writes from the start. Mode a adds new lines to the end.
4What does except do in a try block?
It catches the error. The program does not stop. The code in except runs instead.
5Why should a recursive function have a base case?
Without a base case, the function calls itself forever. The program runs out of memory and stops.
Useful links
Official documentation and pages for this course.
- Alta3 Research — alta3.com
- Alta3 on YouTube — @Alta3Research
- Alta3 on GitHub — github.com/alta3