Python 003: Python Basics 1: Structure & Syntax
This will help you:
Write basic programs in Python.
This is intended to provide a quick introduction and reference for common features used in basic Python programs. To practice and learn more about each feature, references are included.
Time: 1-2 hours / Level: A1
You should already:
Have Python installed, and have an IDE or text editor (see Python Basics 0)
Know how to use the command line to navigate files and run programs (see Command Line Quickstart)
Get the code and resources for this activity by clicking below. It will allow you to download the files from a Google Drive folder. Unzip the folder and save it in a sensible location.
Index
0_printing.py
- Learn to print data to the screen.1_variables.py
- Learn to store data under a name, called a variable.2_lists_tuples.py
- Learn 2 of the ways to store groups of data.3_loops.py
- Learn to make things happen repeatedly.4_if_else.py
- Learn to make decisions based on some condition.5_math_logic.py
- Learn about mathematical operations and logic in Python.
Glossary
Interpreter - The program that reads your code, parses the code to understand what it should do, and executes it.
Error - When the interpreter runs into an instruction that doesn't make sense, or a running program reaches a step it can't do, the program will stop completely and print an error message in the terminal.
Command/Instruction/Step/Operation - One thing for the computer to do.
Run/Execute - The computer doing steps.
Flow/Thread of execution - The order in which the steps of the program will run. Without functions, loops, or conditions, it would execute each line from top to bottom of the file.
Functions, loops and conditions - Pieces of code that can be executed in a slightly different order - see below.
Debugging - When you think you wrote an instruction right, and the interpreter says "No you didn't!", and you say "Are you sure?" and try to figure out what mistake you made.
Note
Each of these activities can be run by typing python name_of_file.py
in the terminal. If you don't know how to use the terminal/command line, you should read the Command Line Quickstart.
Sometimes you will see lines in the code files that are surrounded by """ """
or ''' '''
, or begin with a #
.
# This is a single-line comment. The interpreter will ignore
# anything on the line after '#'.
this = 'Not a comment, executable code!'
"""
This is a multi-line comment. It starts and ends with
triple-(single or double)quotes. You can write as much as you want,
and the interpreter will ignore until you close it with """
this = "More actual code"
''' You can also use these triple-quotes
as long as the start and end types match. '''
Lastly, sometimes you will see this line:
input("Press Enter to continue...")