Python Programming Fundamentals: From Zero to Useful Scripts
Learn Python from scratch and write small, safe scripts that read CSV files and automate office tasks, using an AI assistant to help you write and check code.
What you will learn
- Install Python, run a script and use variables, basic types, input and f-strings correctly.
- Control program flow with comparisons, if/elif/else, for loops and while loops.
- Write functions with parameters and return values, and avoid the common scope and default-argument traps.
- Store and process data with lists, dictionaries, tuples, sets and strings.
- Read and write text files safely and handle errors with try/except.
- Use modules and the standard library, and manage packages with a virtual environment and pip.
- Build a small CSV data script and use an AI assistant to write, review and test code responsibly.
Modules
- Getting started: install, run, variables and types
- Decisions and loops
- Functions: reuse your code
- Lists, dictionaries and strings
- Files and errors
- Modules, packages and virtual environments
- Project: a CSV data script, and working with an AI assistant
Course facts
- Estimated study time
- about 60 minutes
- Final assessment
- 40 questions · Pass mark 80%
- Available in
- English, Français, العربية
- Price
- Free. Optional verifiable certificate: $7
- Last updated
- Published by
- AMAADOR ACADEMY
Who this course is for
Beginners with no coding experience: office, finance, HR, HSE, quality and operations staff, students and career changers who want to automate repetitive work or prepare for the PCEP entry-level exam.
Prerequisites
None. You need a computer on which you may install software (Windows, macOS or Linux) and a plain text editor. Basic comfort with files and folders helps.
Course content
1. Getting started: install, run, variables and types
Python is a general-purpose language that reads almost like plain English, which is why analysts, engineers and office teams often start with it. You write instructions in a text file ending in .py and the Python interpreter runs them line by line.
Install a current release from python.org. Python 3.15 was released in October 2026, 3.14 still receives bug fixes and 3.10 reached end of life that month, so always choose a supported version.
| Command | What it does |
|---|---|
| python --version | Shows the installed version (py --version on Windows, python3 --version on macOS and Linux) |
| python hello.py | Runs the file hello.py |
| python | Opens the interactive prompt (REPL) to test one line at a time |
- Create — a file hello.py containing print('Hello, Morocco!')
- Open — a terminal in the same folder
- Run — python hello.py (on Windows py hello.py also works)
- Read — the output, or the error message if something failed
When a program fails, Python prints a traceback. Read it from the bottom: the last line gives the error type and message, the lines above give the file and the line number. Three errors appear in almost every first week.
2. Decisions and loops
Programs make decisions with comparisons, which give True or False, and with the keywords if, elif and else. A colon ends the condition line and the block below it is indented by four spaces. In Python, indentation is not decoration: it defines what belongs to the decision.
| Operator | Meaning |
|---|---|
| == != | equal, different (a single = assigns a value, it never compares) |
| < > <= >= | smaller, greater, smaller or equal, greater or equal |
| and or not | combine or reverse conditions, such as age >= 18 and has_id |
| Code | Result |
|---|---|
| total = 120 | |
| if total >= 200: | |
| discount = 0.10 | |
| elif total >= 100: | |
| discount = 0.05 | |
| else: | |
| discount = 0 | |
| print(discount) | 0.05 |
Python tests the branches from top to bottom and runs only the first one that is True, so put the most demanding condition first. Some values count as False: 0, 0.0, an empty text '', an empty list [] and None. Everything else counts as True.
Do
- Use == to compare
- Indent with four spaces
- Test the strictest condition first
3. Functions: reuse your code
A function is a named block of code you can reuse. You define it with def, give it parameters and send a result back with return. You call it by name with arguments. Functions stop you from copying the same lines ten times and let you fix a bug in one place.
| Code | Result |
|---|---|
| def area(width, height): | |
| return width * height | |
| print(area(3, 4)) | 12 |
| def greet(name, greeting='Hello'): | |
| return f'{greeting}, {name}!' | |
| greet('Sara') | 'Hello, Sara!' |
| greet('Sara', 'Bonjour') | 'Bonjour, Sara!' |
| greet(greeting='Salam', name='Sara') | 'Salam, Sara!' |
A parameter with a value after = has a default and becomes optional. Arguments can be given by position or by name; named arguments make calls easier to read.
Do not confuse print() and return. print() only shows a value on the screen. return hands the value back to the caller so it can be stored, tested or used in another calculation. A function that never reaches a return gives back None, and None cannot be multiplied or added.
Do
- Give one job to each function
- Name it with a verb: calculate_total
- Return results and print them outside
4. Lists, dictionaries and strings
Real data comes in groups: prices, names, stock levels. Python has four built-in containers. Choose by asking whether you look items up by position or by name, whether they may change, and whether duplicates matter.
| Type | Example | Changeable | Duplicates | Use it for |
|---|---|---|---|---|
| list | [12, 8, 20] | Yes | Yes | An ordered collection you update |
| tuple | (33.57, -7.59) | No | Yes | A fixed record, such as coordinates |
| dict | {'pen': 10} | Yes | Keys are unique | Look-up by name |
| set | {1, 2, 3} | Yes | No | Removing duplicates, membership tests |
| Code | Result |
|---|---|
| prices = [12, 8, 20]; prices.append(5) | [12, 8, 20, 5] |
| prices[0], prices[-1] | 12, 5 |
| prices[1:3] | [8, 20] |
| sorted(prices) | [5, 8, 12, 20] |
| stock = {'pen': 10, 'book': 3}; stock['pen'] += 5 | stock['pen'] is 15 |
| stock.get('lamp', 0) | 0 |
| stock['lamp'] | KeyError |
| set([1, 2, 2, 3]) | {1, 2, 3} |
List positions start at 0 and negative positions count from the end. In a slice such as prices[1:3] the stop position is excluded. Loop over a dictionary with for item, qty in stock.items(). Use get() when a key may be missing. Note that {} creates an empty dictionary; an empty set is written set().
5. Files and errors
Scripts become useful when they read your files and write reports. Open files with with open(...): Python closes the file for you, even if an error happens inside the block. Always pass encoding='utf-8' so that accents and Arabic letters survive on every computer.
| Mode | Meaning |
|---|---|
| 'r' | Read (the default). The file must exist. |
| 'w' | Write. Creates the file, or ERASES the old content if it exists. |
| 'a' | Append. Adds to the end and keeps the old content. |
| 'x' | Create a new file. Fails if the file already exists. |
| Code | Result |
|---|---|
| with open('notes.txt', 'w', encoding='utf-8') as f: | |
| f.write('Audit done\n') | file created |
| with open('notes.txt', encoding='utf-8') as f: | |
| for line in f: | |
| print(line.strip()) | Audit done |
write() does not add a line break, so include \n yourself. When you loop over a file, each line keeps its \n at the end; strip() removes it. read() returns the whole text and readlines() returns a list of lines.
The pathlib module builds paths that work on Windows, macOS and Linux: Path('reports') / 'jan.txt'. Useful methods are exists(), read_text(encoding='utf-8'), write_text(...) and parent.mkdir(exist_ok=True). A relative path such as 'sales.csv' is looked up in the folder where you run the command, not necessarily where the script is saved. A FileNotFoundError often means you are in the wrong folder.
6. Modules, packages and virtual environments
A module is simply a .py file whose code you can reuse with import. Python also ships with a large standard library, installed together with Python, so you can read files, work with dates, do statistics and more without installing anything.
Standard-library modules you will use most in office scripts.
| Code | Result |
|---|---|
| import math; math.sqrt(16) | 4.0 |
| math.ceil(2.1) | 3 |
| import statistics; statistics.mean([2, 4, 6]) | 4 |
| from datetime import date; date.today() | today's date |
| import random; random.choice(['A', 'B']) | 'A' or 'B' |
You can write your own module: save def area(w, h) in tools.py, then write import tools and call tools.area(3, 4) from a script in the same folder. Add if __name__ == '__main__': at the bottom of a file for code that should run only when you start that file directly, not when another file imports it.
Do
- Check the standard library before installing anything
- Import at the top of the file
- Give your files clear, specific names
Don't
- Name your file random.py, csv.py or math.py
- Use from module import * in real scripts
- Install a package for something math or statistics already does
7. Project: a CSV data script, and working with an AI assistant
A CSV file is plain text with one record per line and values separated by commas. It is how spreadsheets, accounting tools and HR systems exchange data, which makes it the best first real project. The csv module in the standard library reads it correctly, including quoted values.
| region | product | units | price |
|---|---|---|---|
| Casablanca | pen | 10 | 1.5 |
| Rabat | book | 3 | 12 |
| Casablanca | book | 2 | 12 |
The file sales.csv holds the table above, with a header line. The goal: total sales per region.
| Code | Result |
|---|---|
| import csv | |
| totals = {} | |
| with open('sales.csv', newline='', encoding='utf-8') as f: | |
| for row in csv.DictReader(f): | each row is a dict |
| amount = int(row['units']) * float(row['price']) | convert text to numbers |
| totals[row['region']] = totals.get(row['region'], 0) + amount | add to the region |
| for region, total in sorted(totals.items()): | |
| print(f'{region}: {total:.2f}') | Casablanca: 39.00 and Rabat: 36.00 |
- Read — DictReader uses the header line as keys
- Convert — every value arrives as text, so use int() and float()
- Aggregate — a dictionary with get(key, 0) keeps totals
- Report — print, or write a new CSV with csv.DictWriter(f, fieldnames=[...]), writeheader() and writerow()
The full lesson continues in the interactive course on this page.
Sources and references
- The Python Tutorial
- Download Python (current releases)
- Status of Python versions
- venv: creation of virtual environments
- csv: CSV file reading and writing
- Installing packages with pip
- PEP 8: Style Guide for Python Code
- PCEP: Certified Entry-Level Python Programmer
Educational course based on the official Python 3 documentation. It is not affiliated with the Python Software Foundation or the Python Institute, and it does not certify you. Check the current exam outline on the Python Institute website before you book PCEP. Run AI-generated code only after you have read and tested it, and never paste confidential or personal data into an AI tool without your employer's approval.
All courses · AI & Data - Free courses, certificate from $7 | AMAADOR ACADEMY