|
1 | 1 | --- |
2 | | -title: Python Syntax |
| 2 | +title: "Python Syntax" |
3 | 3 | --- |
4 | 4 |
|
5 | 5 | ::: {.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 | +::: |
7 | 13 |
|
8 | | -- Learn the basic python syntax |
9 | | -- Learn how to create and name variables |
| 14 | +## What is the Syntax of a Programming Language? |
10 | 15 |
|
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. |
12 | 17 |
|
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. |
14 | 19 |
|
15 | | -The syntax of a programming language is... |
| 20 | +## Assigning Variables |
16 | 21 |
|
| 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. |
17 | 23 |
|
18 | | -## Assigning variables |
| 24 | +In Python, creating (or initialising) a variable is straightforward: |
19 | 25 |
|
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). |
21 | 29 |
|
22 | | -::: {.callout-exercise} |
23 | | -#### Python variables |
| 30 | +```python |
| 31 | +researcher_name = "Kavi" |
| 32 | +project_title = "Genome Analysis" |
24 | 33 |
|
25 | | -What are the variables in the ```expense_calculator.py``` script? |
| 34 | +print(researcher_name) |
| 35 | +print(project_title) |
| 36 | +``` |
26 | 37 |
|
27 | | -What are they used for? |
| 38 | +## Variable Naming Conventions — Making Your Life Easy! |
28 | 39 |
|
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. |
30 | 41 |
|
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: |
32 | 43 |
|
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. |
34 | 51 |
|
35 | | -- Case sensitive |
| 52 | +## Indentation |
36 | 53 |
|
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. |
38 | 55 |
|
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! |
43 | 57 |
|
44 | | -``` |
45 | | -<br> |
| 58 | +### Multi-Line Indentation Errors with print() |
46 | 59 |
|
47 | | -### Variable Naming Conventions in Python - Making your life easy! |
| 60 | +Consider these two examples where multiple `print()` statements are run in sequence: |
48 | 61 |
|
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 | +``` |
50 | 67 |
|
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 | +``` |
52 | 73 |
|
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. |
54 | 75 |
|
55 | | -* **Use lowercase:** Separate words with underscores, e.g., weight_kg. |
| 76 | +**Why does this happen?** |
56 | 77 |
|
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. |
58 | 79 |
|
59 | | -* **Stick to letters:** Use only letters, underscores, and digits (when needed). No quotation marks or brackets |
| 80 | +## Printing Multiple Items and Splitting Lines |
60 | 81 |
|
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: |
62 | 83 |
|
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" |
64 | 87 |
|
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 | +``` |
66 | 90 |
|
67 | | -For more detailed guidelines, refer to PEP 8 or the Google Python Style Guide. |
| 91 | +Output: |
68 | 92 |
|
69 | | -<br> |
| 93 | +``` |
| 94 | +Project Lead: Dr Aris Thorne at Central Lab |
| 95 | +``` |
70 | 96 |
|
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: |
72 | 98 |
|
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) |
77 | 101 |
|
| 102 | +print( |
| 103 | + "Project update:", |
| 104 | + project_title, |
| 105 | + "is currently managed by", |
| 106 | + lead_scientist, |
| 107 | + "in", |
| 108 | + facility |
| 109 | +) |
78 | 110 | ``` |
79 | | -# Initialising my_height in cm |
80 | | -my_height = 176 |
81 | | - my_name = "Kavi" |
82 | | - |
83 | | -``` |
84 | | -The above would produce an error |
85 | 111 |
|
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! |
87 | 113 |
|
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 |
90 | 115 |
|
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. |
92 | 117 |
|
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" |
94 | 121 |
|
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 |
96 | 123 |
|
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 | +``` |
98 | 130 |
|
99 | 131 | ## Exercises |
100 | 132 |
|
101 | | - |
102 | 133 | ::: {.callout-exercise} |
103 | | -#### Python variable evaluation |
| 134 | +### Exercise 1: Evaluating Variable Names |
104 | 135 |
|
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: |
108 | 137 |
|
| 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 | +``` |
109 | 146 |
|
| 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! |
110 | 156 | ::: |
111 | | - |
112 | 157 | ::: |
113 | 158 |
|
114 | 159 | ::: {.callout-exercise} |
115 | | -#### Commenting code |
| 160 | +### Exercise 2: Formatting Multi-Line Print Statements |
116 | 161 |
|
| 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: |
117 | 163 |
|
118 | | -::: {.callout-answer} |
| 164 | +```python |
| 165 | +organism = "Benson's Wild Violet" |
| 166 | +habitat = "Alpine Meadow" |
| 167 | +status = "Vulnerable" |
119 | 168 |
|
| 169 | +print("Species Record:", organism, "found in habitat type:", habitat, "with threat classification:", status) |
| 170 | +``` |
120 | 171 |
|
| 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 | +``` |
121 | 190 | ::: |
122 | | - |
123 | 191 | ::: |
124 | 192 |
|
125 | 193 | ::: {.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. |
127 | 197 |
|
| 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 | +``` |
128 | 206 |
|
129 | 207 | ::: {.callout-answer} |
| 208 | +Answer: |
130 | 209 |
|
| 210 | +```python |
| 211 | +# Store the facility code where the run takes place |
| 212 | +lab_code = "LAB_NORTH_2" |
131 | 213 |
|
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" |
133 | 219 |
|
| 220 | +# Fix 2: Added missing comma between lab_code and "Ready" inside print() on Line 4 |
| 221 | +print("Status:", lab_code, "Ready") |
| 222 | +``` |
| 223 | +::: |
134 | 224 | ::: |
135 | 225 |
|
136 | 226 | ## Summary |
137 | 227 |
|
138 | 228 | ::: {.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. |
145 | 235 | ::: |
0 commit comments