Skip to content

Commit fa80852

Browse files
committed
operator pages
1 parent ea8261f commit fa80852

9 files changed

Lines changed: 981 additions & 98 deletions

File tree

‎_freeze/materials/00_introducing_python/execute-results/html.json‎

Lines changed: 2 additions & 2 deletions
Large diffs are not rendered by default.

‎_freeze/materials/01_python_basics/execute-results/html.json‎

Lines changed: 2 additions & 2 deletions
Large diffs are not rendered by default.

‎_freeze/materials/02_python_data_types/execute-results/html.json‎

Lines changed: 1 addition & 1 deletion
Large diffs are not rendered by default.

‎_freeze/materials/03_python_operators/execute-results/html.json‎

Lines changed: 12 additions & 0 deletions
Large diffs are not rendered by default.

‎_freeze/materials/04_Python_Data_types/execute-results/html.json‎

Lines changed: 12 additions & 0 deletions
Large diffs are not rendered by default.

‎materials/03_python_operators.qmd‎

Lines changed: 301 additions & 13 deletions
Large diffs are not rendered by default.
Lines changed: 161 additions & 71 deletions
Original file line numberDiff line numberDiff line change
@@ -1,145 +1,235 @@
11
---
2-
title: Python Syntax
2+
title: "Python Syntax"
33
---
44

55
::: {.callout-tip}
6-
#### Learning Objectives
6+
## Learning Objectives
7+
- Understand what syntax means in programming
8+
- Learn how to store and display text using variables and the `print()` function
9+
- Follow standard Python variable naming guidelines
10+
- Learn how Python uses indentation and whitespace
11+
- Write clear comments to explain your code
12+
:::
713

8-
- Learn the basic python syntax
9-
- Learn how to create and name variables
14+
## What is the Syntax of a Programming Language?
1015

11-
:::
16+
The syntax of a programming language is the set of rules that defines how programs must be written. Just like human languages have grammar and punctuation rules so we can understand one another, programming languages have syntax rules so the computer can understand our instructions.
1217

13-
## What is the syntax of a Programming language
18+
If you break a syntax rule in Python, the computer will not try to guess what you meant—it will simply raise a `SyntaxError` and stop running.
1419

15-
The syntax of a programming language is...
20+
## Assigning Variables
1621

22+
A variable is a named reference used to store a piece of information in a program so you can access and use it later.
1723

18-
## Assigning variables
24+
In Python, creating (or initialising) a variable is straightforward:
1925

20-
A variable is a named reference used to store and access a value in a program.
26+
- You choose a name for your variable.
27+
- You use the equals sign (`=`) to assign a value to it.
28+
- Python automatically works out what kind of data you are storing (such as text wrapped in quotation marks, known as a string).
2129

22-
::: {.callout-exercise}
23-
#### Python variables
30+
```python
31+
researcher_name = "Kavi"
32+
project_title = "Genome Analysis"
2433

25-
What are the variables in the ```expense_calculator.py``` script?
34+
print(researcher_name)
35+
print(project_title)
36+
```
2637

27-
What are they used for?
38+
## Variable Naming Conventions — Making Your Life Easy!
2839

29-
:::
40+
One of the hardest parts of reading someone else's code is dealing with variable names that make no sense to anyone except the original author.
3041

31-
In Python initialising variables is easy:
42+
When naming variables, follow Python's guidelines (from the official style guide known as PEP 8) for consistency and readability:
3243

33-
- Variables are assigned using the = sign
44+
- **Use lowercase with underscores (snake_case):** Separate words with underscores (e.g. `sample_id`, `species_name`).
45+
- **Case-sensitive:** `sample`, `Sample`, and `SAMPLE` are three completely different variables to Python.
46+
- **Do not start with numbers:** Variable names cannot begin with a digit (e.g. `1st_sample` is invalid, but `sample_1` is fine).
47+
- **Stick to letters, numbers, and underscores:** Do not use special characters, spaces, quotation marks, or brackets in the variable name itself.
48+
- **Be descriptive:** Choose clear, meaningful names (`lab_location` is helpful; `x12` is not).
49+
- **Avoid overly long names:** `sample_type` is ideal, whereas `the_type_of_sample_we_collected_from_the_field_today` is unnecessarily long.
50+
- **Do not use Python keywords:** Avoid using built-in command names like `print` as variable names, as this will overwrite the built-in function.
3451

35-
- Case sensitive
52+
## Indentation
3653

37-
- No need to declare the type explicitly (dynamic typing)
54+
In Python, indentation (leading spaces at the start of a line) is used to define code blocks. We will see more of this later in this course when we look at conditional statements and loops.
3855

39-
```
40-
# Initialising my_height in cm
41-
my_height = 176
42-
my_name = "Kavi"
56+
Because Python relies on indentation to group instructions, putting an unexpected space at the start of any line will trigger an `IndentationError`. This happens frequently across multi-line code—even when using simple `print()` statements!
4357

44-
```
45-
<br>
58+
### Multi-Line Indentation Errors with print()
4659

47-
### Variable Naming Conventions in Python - Making your life easy!
60+
Consider these two examples where multiple `print()` statements are run in sequence:
4861

49-
*One of the worst things in particular when looking at other peoples code is variable names that make no sense to anybody but the writer*
62+
```python
63+
print("Step 1: Sample logged")
64+
print("Step 2: Buffer added")
65+
print("Step 3: Centrifuge complete")
66+
```
5067

51-
When naming variables, it's important to follow Python's guidelines for consistency and readability. Here are some key rules to remember:
68+
```python
69+
print("Step 1: Sample logged")
70+
print("Step 2: Buffer added")
71+
print("Step 3: Centrifuge complete")
72+
```
5273

53-
* **Case-sensitive:** weight and Weight are different variables.
74+
In the second example, an extra space at the beginning of Line 2 causes an `IndentationError` immediately.
5475

55-
* **Use lowercase:** Separate words with underscores, e.g., weight_kg.
76+
**Why does this happen?**
5677

57-
* **Don't start with numbers:** Variable names cannot begin with a digit.
78+
In Python, you cannot indent a line unless it follows a specific statement that creates a new code block (like an `if` statement or a loop, which we will cover later). Because Line 1 is not starting a new block, Python does not expect Line 2 to be indented and immediately halts execution.
5879

59-
* **Stick to letters:** Use only letters, underscores, and digits (when needed). No quotation marks or brackets
80+
## Printing Multiple Items and Splitting Lines
6081

61-
* **Be descriptive:** Choose clear, meaningful names (e.g., asdjks is not helpful).
82+
You can print multiple items at once by passing them into `print()`, separated by commas. Python will automatically put a space between each item:
6283

63-
* **Avoid overly long names:** For example 'this_is_my_height_in_cm' is too long.
84+
```python
85+
lead_scientist = "Dr Aris Thorne"
86+
facility = "Central Lab"
6487

65-
* **Don't use keywords:** Avoid using Python function names, class names, or data types as variable names.
88+
print("Project Lead:", lead_scientist, "at", facility)
89+
```
6690

67-
For more detailed guidelines, refer to PEP 8 or the Google Python Style Guide.
91+
Output:
6892

69-
<br>
93+
```
94+
Project Lead: Dr Aris Thorne at Central Lab
95+
```
7096

71-
### Indentation
97+
If your `print()` statement becomes long, Python allows you to split it across multiple lines inside the round brackets `()`. This implicit line continuation makes your code much neater and easier to read:
7298

73-
In python indentation is used to define code blocks. We will see more of this later in this course.
74-
- Unexpected indents will result in errors.
75-
- indents are 4 spaces according to PEP 8 standards, however commonly also two spaces on web interfaces. Be consistent.
76-
- Using spaces is preferable to using tabs
99+
```python
100+
print("Project update:", project_title, "is currently managed by", lead_scientist, "in", facility)
77101

102+
print(
103+
"Project update:",
104+
project_title,
105+
"is currently managed by",
106+
lead_scientist,
107+
"in",
108+
facility
109+
)
78110
```
79-
# Initialising my_height in cm
80-
my_height = 176
81-
my_name = "Kavi"
82-
83-
```
84-
The above would produce an error
85111

86-
## Commenting your code
112+
Notice how indenting the items on new lines inside the brackets keeps the code organised. Because these lines sit inside round brackets `()`, Python knows they are part of the same `print()` instruction and will not raise an indentation error!
87113

88-
Commenting your code, and using lines liberally, are key to making your code easily understandable for both yourself and others.
89-
These comments are ignored by python and do not result in any output - check for yourself in the console!
114+
## Commenting Your Code
90115

91-
- A **```#```** (Hash) is used for single line comments
116+
Comments are notes written directly in your script to explain what the code is doing. Python ignores comments completely—they produce no output and exist solely to help humans read the code.
92117

93-
- A **```"""```** (triple quotes) is used around multiline comments or strings
118+
```python
119+
# Store the active status of the ongoing trial
120+
experiment_stage = "Data Collection"
94121

95-
- A **```\```** (backslash) is used to explicitly break a line
122+
print(experiment_stage) # You can also place comments at the end of a code line
96123

97-
- Lines can be implicitly continued in some cases, for example when in brackets. We will see this later.
124+
"""
125+
This is a multi-line comment (using triple quotes).
126+
It allows you to write longer notes across several lines
127+
without needing a hash symbol on every single line.
128+
"""
129+
```
98130

99131
## Exercises
100132

101-
102133
::: {.callout-exercise}
103-
#### Python variable evaluation
134+
### Exercise 1: Evaluating Variable Names
104135

105-
Decide whether the following are good or bad variable names. If they are bad, what might be a better name and why?
106-
107-
::: {.callout-answer}
136+
Look at the following list of proposed variable names. Decide whether each one is Valid & Good, Valid but Poor, or Invalid (Will Cause an Error). Explain your reasoning:
108137

138+
```python
139+
2026_target = "100 samples"
140+
temp_celsius = "21.5"
141+
the_exact_temperature_of_the_water_bath_in_room_4b = "37.0"
142+
q = "Invasive Species Study"
143+
patient name = "P_042"
144+
print = "Final Report"
145+
```
109146

147+
::: {.callout-answer}
148+
Answer:
149+
150+
- **Invalid:** Variable names cannot start with a digit.
151+
- **Valid & Good:** Clear, uses snake_case, and includes units (`_celsius`).
152+
- **Valid but Poor:** Too long and tedious to type or read. Something like `water_bath_temp` would be much better.
153+
- **Valid but Poor:** Cryptic and vague. A reviewer will not know what `q` refers to without reading the rest of the script.
154+
- **Invalid:** Contains a space. It should be `patient_name`.
155+
- **Invalid/Dangerous:** `print` is a built-in Python function. Assigning a value to it overwrites the function and prevents you from printing anything later!
110156
:::
111-
112157
:::
113158

114159
::: {.callout-exercise}
115-
#### Commenting code
160+
### Exercise 2: Formatting Multi-Line Print Statements
116161

162+
Re-write the following long print statement so that it spans cleanly across multiple lines inside the brackets, keeping the code neat and easy to scan:
117163

118-
::: {.callout-answer}
164+
```python
165+
organism = "Benson's Wild Violet"
166+
habitat = "Alpine Meadow"
167+
status = "Vulnerable"
119168

169+
print("Species Record:", organism, "found in habitat type:", habitat, "with threat classification:", status)
170+
```
120171

172+
::: {.callout-answer}
173+
Answer:
174+
175+
```python
176+
organism = "Benson's Wild Violet"
177+
habitat = "Alpine Meadow"
178+
status = "Vulnerable"
179+
180+
# A neatly formatted multi-line print statement:
181+
print(
182+
"Species Record:",
183+
organism,
184+
"found in habitat type:",
185+
habitat,
186+
"with threat classification:",
187+
status
188+
)
189+
```
121190
:::
122-
123191
:::
124192

125193
::: {.callout-exercise}
126-
#### Indentation
194+
### Exercise 3: Fixing Multi-Line Indentation and Syntax Errors
195+
196+
The following script contains two errors: an `IndentationError` on Line 2 and a syntax error on Line 4.
127197

198+
Fix the script so it executes cleanly, and add a single-line comment above each variable explaining what it stores:
199+
200+
```python
201+
lab_code = "LAB_NORTH_2"
202+
print("Initialising run for:", lab_code)
203+
buffer_solution = "Phosphate Saline"
204+
print("Status:", lab_code "Ready")
205+
```
128206

129207
::: {.callout-answer}
208+
Answer:
130209

210+
```python
211+
# Store the facility code where the run takes place
212+
lab_code = "LAB_NORTH_2"
131213

132-
:::
214+
# Fix 1: Removed leading spaces before print on Line 2 to resolve the IndentationError
215+
print("Initialising run for:", lab_code)
216+
217+
# Record the solution used for sample dilution
218+
buffer_solution = "Phosphate Saline"
133219

220+
# Fix 2: Added missing comma between lab_code and "Ready" inside print() on Line 4
221+
print("Status:", lab_code, "Ready")
222+
```
223+
:::
134224
:::
135225

136226
## Summary
137227

138228
::: {.callout-tip}
139-
#### Key Points
140-
141-
- Variables are words used to reference and access a value
142-
- Be clear an concise following guidelines when naming variables
143-
- Comment your code for clarity
144-
229+
## Key Takeaways
230+
- **Syntax:** The official rules of how code must be written for Python to understand it.
231+
- **Variables:** Stored values assigned using `=`. Use descriptive snake_case names.
232+
- **Indentation:** Extra spaces at the start of a line matter in Python. Unintended leading spaces across sequential statements trigger an `IndentationError`.
233+
- **Multiple items in print():** Separate variables and text strings with commas. Split long `print()` statements across multiple lines inside the brackets to keep code clean.
234+
- **Comments (`#`):** Notes ignored by Python that describe what your code is doing for human readers.
145235
:::

0 commit comments

Comments
 (0)