Advanced
Searching inSummaries
How to search
  • Words find lesson titles, text and code. Filter by type (guides, courses, programs, books) or stay in this book.
  • book:rhcsa and ch:8 narrow the search; #code finds a word only in commands of the lessons.
  • "two words" finds the exact phrase.
  • Plain words find names, texts and examples.
  • ↑ ↓ to move · Enter to open · Esc to close · / to search
Try:

Course 10Name in the course: Introduction to Python

Introduction to Python

Course 10 of 13 in the Alta3 Academy library. Alta3 Academy self-paced course.

Note

My result — Lessons read: all 34/34; Course progress: 100%.

  • 12 Lessons
  • 17 Commands
  • 1 Labs

$ run as a normal user# run as root (or with sudo)

10.1

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, and for.
  • How to read and write files. How to import modules and install packages with pip.
  • How to catch errors with try and except. How to write classes and inheritance.
  • Optional PCEP review: numbers, loops, data structures, and four mock exams.

Commands in this lesson

10.2

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, and touch. mv moves or renames a file. history shows old commands. man ls opens the manual.
  • Each code block has a copy icon. Paste with right-click, Shift + Insert, or Ctrl + Shift + V.
  • If the terminal closes by accident, press Enter to start a new session.
  • VIRGIL is the AI lab coach. You can ask it for help.

10.3

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. z zooms one pane. [ enters scroll mode, and q leaves it. exit or Ctrl + d closes a pane.

10.4

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 store saves your token for later pushes. user.name and user.email label your commits.
  • Then you clone the repo and push your code. A good repo has a README and a license.

Commands in this lesson

10.5

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 python3 and runs with python3 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 in trek.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.
  • if runs code when a test is true. elif adds more tests. else is the catch-all.
  • while repeats while a test is true. for walks through a collection. break leaves a loop early. continue skips to the next turn.
  • open() makes a file object. Mode w overwrites a file. Mode a adds to the end. Mode r reads. Use with so the file closes by itself.
  • A for loop 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 wget first. 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 if test inside.
  • Modules are files of Python code. import os and import shutil use the standard library. os.chdir() changes the current directory.
  • shutil copies and moves files. The modules lab changes the working directory so a relative path works.
  • pip installs packages from PyPI. python3 -m venv myenv makes a virtual environment. source myenv/bin/activate turns it on. The system Python stays clean.
  • try runs code that may fail. except handles the error. else runs when there is no error. finally always runs. Name the error you expect, such as ValueError or KeyError.
  • One try can have many except blocks. Each block handles a different error type.
  • A class is a blueprint. class makes 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(), and if tests. The trivia challenge ignores upper and lower case when it checks an answer.

10.6

Optional- PCEP Certification Guide

The PCEP exam has 30 questions in 45 minutes. You need 70% to pass.

  • Scientific notation writes 3e8 for 300000000.0. Number prefixes mark the base: 0b for binary, 0o for octal, and 0x for hex.
  • The guide covers scientific notation, binary, octal, and hex numbers. It also covers arithmetic and bitwise operators.
  • pass does nothing. range() pairs with for. for-else and while-else have an else that runs when the loop ends without break.
  • break stops a loop. continue skips the rest of the turn and starts the next one.
  • List copies matter. original[:] makes a new list. shallow = original points 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.
  • None means "no value". Recursion means a function calls itself, and it needs a base case. A name can be local or global.

10.7

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.

10.8

Key commands and tools

  • python3 starts the interpreter. python3 script.py runs a file.
  • vim file.py opens a file in Vim. Press i to insert. Press Esc to stop.
  • Ctrl + b, then % splits a tmux pane. Ctrl + b, then " splits the other way.
  • git add *, git commit -m "message", and git push origin send work to GitHub.
  • git clone <url> copies a remote repo to your machine. git config --global credential.helper store saves 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 as report_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:, and for x in vendors:
  • while True: with break stops a loop from the inside.
  • with open("file.txt", "r") as foo: then foo.read()
  • for line in foo: reads one line at a time.
  • numbers = [1, 2, 3] then numbers.append(4) adds one item.
  • mkdir -p ~/mycode/lab/, chmod u+x script.py, and python3 script.py
  • echo "text" > /tmp/test.txt writes a short test file.
  • python3 -m pip install pytest and python3 -m pip freeze
  • python3 -m venv myenv makes a virtual environment. source myenv/bin/activate turns it on.
  • man ls opens the manual. Press q to quit.
  • import os, os.chdir("/tmp"), import shutil, import random, random.randint(1, 6)
  • try: with except ValueError: and finally:
  • class Player: with def __init__(self):

10.9

Key terms

The words of this course in one table. Learn them before the quiz or exam.

TermMeaning
ArgumentA value you give to a function when you call it.
AttributeData that belongs to an object.
Built-in functionA function that Python gives you, such as len() or print().
ClassA blueprint for making objects.
ConditionalCode that runs only when a test is true.
DictionaryA group of key: value pairs inside {}.
ExceptionAn error that stops the normal flow of a program.
FunctionA named block of code that does one job.
IndexThe position of an item in a list. The first item is at 0.
InheritanceA child class takes features from a parent class.
InterpreterThe program that runs Python code line by line.
ListAn ordered group of items that you can change.
MethodA function that belongs to an object, called with a dot.
ModuleA file of Python code that you can import.
MutableCan be changed after it is made.
ObjectA value made from a class.
PackageA bundle of Python code that you install with pip.
PCEPAn entry-level Python certificate exam.
RecursionA function that calls itself.
ReturnTo send a value back from a function.
SliceA part of a list, written as list[start:end].
StringText in Python, inside quotes.
Try/exceptA block that runs code and handles errors.
TupleAn ordered group of items that cannot change.
Virtual environmentA private space for one project's packages.

Commands in this lesson

10.10

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.

Commands in this lesson

Practice

All commands in this chapter