From Algorithms to Python
Turn pages with ‹ Prev and Next ›, by swiping, or with the arrow keys. Tap the page number to see all pages. The code is in notebook cells like Jupyter or Google Colab: press ▶ to run one. Python runs inside your browser, so you don't need to install anything to follow today, and each example ends with a ✏️ Your turn practice question. Your activity answers are recorded under your name so your lecturer can give feedback; they are not graded.
Today
One long session, two chapters. We build up from "what is an algorithm?" to writing real engineering calculations in Python.
The course in one page
SKEE1033 teaches you to describe engineering problems as algorithms, and then to solve them with programs.
Apply
Describe engineering problems with flowcharts and pseudocode, and solve them with programs.
Quiz · Test · Final exam
Formulate
Use an advanced scientific language for data processing, analysis and visualisation.
Quiz · Assignment · Final exam
Communicate
Read, write and compile technical documents about your work.
Assignment (group project)
Assessment
| What | Weight | Covers |
|---|---|---|
| Quiz 1, Quiz 2 | 5% + 5% | CLO1, CLO2 |
| Test | 20% | Chapters 1–5 |
| Assignment | 20% | Group project: one engineering problem solved in Python |
| Final exam | 50% | Four questions: Ch. 1–4, 5–7, 8–10, 11–12 |
SPACE dates for the quizzes, test and project are announced in class and on e-learning.
- Overview of languages
- Programming platform
- Complex data types
- Control flow
- Functions
- Input & output
- Debugging & profiling
- Graphics
- Data interpolation
- Polynomials
- Data analytics
- Object-oriented programming
Today is Chapters 1 and 2. Main reference: Zabidi, Engineering Computation with Python (2026).
Set up Python
Pick one. For today, option C is enough on any laptop or phone.
Anaconda + Spyder
Anaconda Distribution installs Python, Spyder, NumPy, SciPy, Matplotlib and pandas in one go. It's about 1 GB, so download it on good Wi-Fi.
anaconda.com → Download → open Spyder
Spyder on its own
The Spyder standalone installer brings its own Python and the main scientific libraries. It's a smaller download.
spyder-ide.org → Download
The notebook cells on this page
They work like Jupyter or Google Colab, but Python runs inside your browser, so there's nothing to install. The first run downloads about 10 MB, and after that it's instant. Use ⬇ .ipynb to keep your work and open it in Colab or Jupyter later.
Check that it works: press ▶ on each cell
Print your name on one line and your programme on the next.
Use two print() calls, with the text inside quotes.
Warm-up: program a robot
A robot has just arrived in your kitchen. It can follow instructions exactly, but it has never seen a kitchen.
Write the steps for the robot to make one cup of Milo.
Number your steps. Your lecturer will "run" a few answers exactly as written, so watch out for missing steps and vague words like "some" or "enough".
Programs & program development
What a program is, and the three phases of building one
What is programming?
A lot of what we do is a sequence of steps. Writing that sequence down for a computer is programming.
Turning a page, as steps
- Lift your hand.
- Move it to the right side of the book.
- Grasp the top-right corner of the page.
- Move your hand from right to left until the page is turned.
- Let go of the page.
Walking, baking a cake and solving a maths problem all happen in a set order too.
The words we'll use
- Computer: a programmable electronic device that can store, retrieve and process data.
- Program: the list of steps a computer performs to solve a problem.
- Programming: describing, or writing, those steps.
Program development: three phases
Writing code is only one part of the job, and it's not the first part.
Problem solving
- Analyse & specify: understand the problem and what the solution must do.
- General solution: write the algorithm, a logical sequence of steps.
- Verify: follow the steps by hand to check they really solve it.
Implementation
- Concrete solution: translate the algorithm into a programming language.
- Test: run it and check the results. If they're wrong, find the error in the program or the algorithm, then fix it.
Maintenance
- Use the program.
- Maintain it: change it when the requirements change, and fix the errors that show up later.
Put the seven steps of program development in order.
Tap one tile, then tap another to swap them. Press Check when you're done.
Algorithms, flowcharts, pseudocode
Designing the steps before writing any code
What is an algorithm?
An algorithm is the general solution. A program is an algorithm written for a computer.
An ordered set of unambiguous, executable steps that defines a terminating process.
The word comes from al-Khwarizmi, the 9th-century Persian mathematician whose books also gave us "algebra".
A good algorithm…
- is precise and unambiguous: each step has exactly one meaning.
- has a finite number of steps: it always stops.
- produces the correct result.
- doesn't depend on a programming language: you can code it in Python, MATLAB or C.
Last semester's test asked for two of these with a short explanation of each (4 marks).
Example: starting a car
- Insert the key.
- Press the brake pedal.
- Make sure the gear is in Park (or Neutral).
- Turn the key to the start position.
- If the engine starts within 6 seconds, release the key to the ignition position.
- If it doesn't start, release the key, wait 10 seconds, and repeat steps 3–6, but no more than five times.
- If the car still doesn't start, call the garage.
Find the sequence, the decision (if) and the loop (repeat … no more than five times). The limit of five is what makes this algorithm terminate.
Which rule does each step break?
Four building blocks
Every algorithm, however large, is built from these four structures.
Sequence
Steps run one after another, in order.
Decision
Choose a path based on a condition: if … else.
Loop
Repeat steps while a condition is true.
Subprogram
A named group of steps you call by name (a function, in Chapter 5).
Flowcharts
A flowchart is a picture of the solution steps. A program flowchart can be turned into code; a system flowchart (an organisation chart, for example) can't.
A good flowchart
- has one start and one end;
- has flow lines that don't cross;
- contains no programming-language code;
- is neat and easy to follow.
Its drawbacks
- It takes time to draw properly.
- A large flowchart can be hard to translate into a program. That's why pseudocode is often preferred for big problems.
Which flowchart symbol would you draw for each step?
Pseudocode
Pseudocode is structured English: as precise as code, but not tied to any one language. Use it when you're still designing, or don't know the target language yet.
The notation we use
| Idea | Write |
|---|---|
| Start / end | begin … end |
| Procedure | procedure Name … end |
| Input / output | input : … output : … |
| Assignment | result ← 0 |
| Decision | if … else … end if |
| Loop | while … end · for … to … next |
| Give back | return result |
Example: IntegerDivision
Divide n by d using only subtraction: count how many times d fits into n.
procedure IntegerDivision
input : n, d
output: result
begin
result ← 0
while n ≥ d
n ← n − d
result ← result + 1
end while
return result
end
Trace it by hand
To verify an algorithm, you play the computer: run each line and write down every variable. This is a trace table, and test questions ask for one.
IntegerDivision, one line at a time
Trace each one on paper, then pick the answer.
Spot the bug
This version of CalculatePower should return nd. Trace it with n = 2 and d = 3.
procedure CalculatePower
input : n, d
output: result
begin
result ← 1
while d ≥ 0
result ← result × n
d ← d − 1
end while
return result
end
What does it return for n = 2, d = 3?
Show the trace and the fix
| check | d ≥ 0? | result | d |
|---|---|---|---|
| start | 1 | 3 | |
| 1 | 3 ≥ 0 ✓ | 2 | 2 |
| 2 | 2 ≥ 0 ✓ | 4 | 1 |
| 3 | 1 ≥ 0 ✓ | 8 | 0 |
| 4 | 0 ≥ 0 ✓ | 16 | −1 |
| 5 | −1 ≥ 0 ✗ | stop, return 16 | |
The loop runs d + 1 times, one too many, so it returns nd+1. The fix is while d > 0. This is an off-by-one error, one of the most common bugs there is. Tracing one small case by hand is how you catch it.
Practice: pseudocode to flowchart
Draw each flowchart on paper first. Then open the model answer and compare.
Every one of these has the same shape as IntegerDivision: start → input → set up → loop while a condition holds → output → end. SumEvenSquares was the flowchart question (6 marks) in last semester's SPACE test.
Preview: the same algorithm in Python
Pseudocode translates almost line by line. ← becomes =, and the indented lines under while are the loop body. You'll learn loops properly in Chapter 4; today, just see the match.
procedure IntegerDivision
input : n, d
output: result
begin
result ← 0
while n ≥ d
n ← n − d
result ← result + 1
end while
return result
end
Translate FindRemainder into Python for n = 7, d = 3. Store the answer in remainder and print it. You should get 1.
Copy the cell above and change it: start with remainder = n, loop while remainder >= d, and subtract d each time.
One template, many algorithms
Every algorithm in this chapter is the same loop with different parameters. Learn the template once; in the test, you only decide what goes in the slots.
procedure ⟨Name⟩
input : ⟨inputs⟩
output: ⟨answer⟩
begin
⟨answer ← start value⟩ # 0: sum, 1: product
while ⟨condition⟩
⟨update the answer⟩
⟨move towards the end⟩ # e.g. i ← i + 2
end while
return ⟨answer⟩
end
Four decisions: where do I start, when do I stop, what do I add or multiply each time, and how do I move on. Get those right and the rest is copying.
Same template, new question: pick the right slot
Fill the slots: get the pseudocode, the flowchart and the Python
Type <- or = for ←, and >=, <=, * as usual: they're converted for you.
Choosing a language
Why scientific languages exist, and why we use Python
Programming languages
A programming language is a simplified English plus maths symbols, with strict grammar rules. A scientific language is built for formulas, arrays and matrices.
Fortran
Fast, good at arrays, and easy to run in parallel. It's still behind weather, climate and physics codes on supercomputers.
MATLAB
Easy to learn and quick for prototypes, with many specialist toolboxes. Licences are expensive; Octave is a free look-alike.
C / C++
Very fast and close to the hardware, so it's used in firmware and embedded systems. It's harder to learn, and needs extra libraries for scientific work.
Python
Free, readable and easy to learn. With NumPy, SciPy, Matplotlib and pandas it's a full scientific toolkit, and it's widely used in industry, data science and AI.
Compiled or interpreted?
Compiled (C, Fortran): the whole program is translated to machine code first, so it runs fast, but every change needs a rebuild. Interpreted (Python, MATLAB): statements run one by one, so you can try ideas instantly in a console. It's slower in plain loops, but libraries like NumPy do the heavy work in compiled code.
The course used to be taught in MATLAB. The ideas are the same (variables, arrays, loops, plots), but Python is free on your own laptop and is what employers ask for. You'll meet NumPy in Chapter 3 and Matplotlib in Chapter 8.
Which language would you pick for each job?
There's often more than one defensible answer. Read the explanation after you pick.
Break · 15 minutes
- Problem solving → implementation → maintenance.
- An algorithm is unambiguous, finite, correct and language-independent.
- Flowchart symbols: oval, parallelogram, rectangle, diamond.
- Verify with a trace table, and watch for off-by-one errors.
During the break
If you're installing Spyder, start the download now. After the break we write Python, and you can use either Spyder or this page.
The Python platform
Spyder, coding with AI, scripts, variables and data types
Inside Spyder
Spyder is an IDE (integrated development environment): an editor, a console and a variable viewer in one window.
Editor
Write and save scripts (.py files). F5 runs the whole file; F9 runs the selected lines.
IPython console
Type one command and see the answer at once. Use it to test small ideas. %whos lists your variables.
Variable explorer
Shows every variable with its type, size and value, like MATLAB's workspace.
Console or script?
The console is for trying things out, and it forgets everything when you restart. A script is a file you can save, rerun, fix and hand in. Anything you want to keep goes in a script.
Other tools you'll see
Code editors such as VS Code, Notepad++ and Sublime Text; IDEs such as PyCharm, Spyder and Jupyter notebooks. They all run the same Python.
Coding with AI: plug and play, but you own it
"Vibe coding" means describing what you want in plain words and letting an AI assistant (ChatGPT, Gemini, Claude, Copilot, or the Gemini button in Colab) write the code. It's a real way engineers work now, and you should use it to learn faster.
Prompt precisely
Give the inputs with units, the output you want, and the limits ("only the math module"). A vague prompt gets vague code.
Trace it
Read every line. If you can't explain a line, ask the AI to explain it, or don't use it.
Check one case by hand
Run it on numbers you can work out yourself. AI code often runs fine and is still wrong.
Rewrite from your template
Fit the code back into the templates you learn today. That version is the one you can write in the exam.
Prompts have templates too. Copy this one, fill the slots, and paste it into any AI assistant.
Write a short Python script for a beginner. Task: ⟨what to calculate⟩ Inputs: ⟨names, values and units⟩ Output: print ⟨what⟩ to 3 decimal places, with units. Use only the ⟨math / cmath⟩ module. No functions or classes. Comment every line, then give me one test case I can check by hand.
Use the prompt to ask an AI for the resonant frequency f₀ = 1 / (2π√(LC)) of an LC circuit with L = 50 mH and C = 100 µF. Paste its code here, run it, and make sure the answer is stored in f0. Then check it: does it agree with your calculator?
No AI to hand? It's the calculation template: import math, the inputs with units, one formula, one print. Watch the units: 50 mH is 50e-3 and 100 µF is 100e-6.
Each piece of AI code runs, but it's wrong. What's the fix?
These are exactly the slips that cost marks when you write code by hand, too.
Your first script: comments and punctuation
Python reads punctuation strictly. Each symbol below has one job.
A 9 V battery drives a 1 kΩ resistor. Compute the current in milliamps, store it in I_mA, and print it with its unit.
V / R gives amperes; multiply by 1000 for mA. Remember 1 kΩ = 1000 Ω.
| Symbol | Job | Example |
|---|---|---|
| # | Comment until the end of the line | # volts |
| """ """ | Multi-line text, often a description at the top of a file | """Computes power.""" |
| = | Assignment: store the value on the right in the name on the left | R = 220 |
| == | Comparison: are they equal? (Section 05) | R == 220 |
| ( ) | Grouping, and calling a function | print(I) |
| [ ] | Lists and indexing (Chapter 3) | v[0] |
| : | Starts an indented block (Chapter 4) | if I > 1: |
| indent | 4 spaces mark which lines belong to a block. In Python, indentation is part of the syntax. | ····print(I) |
| , | Separates items | print("I =", I) |
| . | Decimal point; also "something inside": a module's function or an object's attribute | math.sqrt(2) |
Variables
A variable is a name attached to a value. You create one simply by assigning to it.
Store 470 in resistance and 0.02 in current, then compute voltage with Ohm's law and print it.
V = I × R. Use exactly these names: the checker looks for voltage.
Run it and read the last line of the error: NameError: name 'resistance' is not defined. Errors tell you the line and the reason, so get used to reading them.
Naming rules
- Use letters, digits and _ only, with no spaces or dashes.
- Don't start with a digit.
- Names are case-sensitive: R and r are different.
- Keywords aren't allowed: if for while class def True None and or not lambda …
- Avoid built-in names like sum max list print. Python allows them, but then the built-in stops working.
Style: snake_case for variables (load_current), and UPPER_CASE for values you mean to keep constant (SPEED_OF_LIGHT = 299792458). Python doesn't enforce constants; it's a convention.
Valid Python variable name, or not?
Basic data types
Every value has a type, and type(x) tells you which.
| Type | What it holds | Examples |
|---|---|---|
| int | Whole numbers, of any size | 10 · -5 · 2**100 |
| float | Numbers with a decimal point or an exponent | 3.14 · 1.2e3 · 7/2 |
| complex | Real + imaginary, written with j | 3+4j · complex(3, 4) |
| str | Text, in single, double or triple quotes | 'Hi' · "7" · """multi-line""" |
| bool | Logical: exactly True or False | True · 5 > 3 |
| NoneType | "No value here" | None |
Make a the int 7, b the float 7.0 and c the string "7". Then print a == b and a == c. Which one is True?
Quotes make text. A decimal point makes a float.
Don't worry about the for line yet: it repeats the indented line once for each value (Chapter 4).
Built-in functions turn one type into another, as long as the value makes sense.
A temperature sensor sends the text "23.7". Convert it to a number, add the 1.5 °C calibration offset, and round to the nearest whole degree. Store the result in t.
float() first, then +, then round(). int() would cut off the decimals instead of rounding.
Watch out for
- int() truncates; it doesn't round.
- bool("0") is True: any non-empty text is True.
- round(2.5) gives 2, because Python rounds halves to the nearest even number.
- "12" + 3 is a TypeError: convert first.
- There's no conversion to None: you just assign x = None.
What type is each value?
Check any you got wrong by typing print(type(…)) into a notebook cell.
Mutable or immutable?
Numbers, strings and tuples are immutable: they can't change. "Changing" one actually makes a new object. Lists, dictionaries and sets are mutable: you can edit them in place.
id() gives the object's identity, roughly its memory address. The int's id changes; the list's doesn't. You'll need this idea in Chapter 3 when we copy arrays.
Operators & expressions
Arithmetic, comparison, logic, and the order Python works in
Arithmetic operators
| Op | Meaning | Example → result |
|---|---|---|
| + − | add, subtract | 7 - 2 → 5 |
| * | multiply | 7 * 2 → 14 |
| / | divide: always a float | 7 / 2 → 3.5 · 6 / 2 → 3.0 |
| // | floor division: round down | 7 // 2 → 3 · -7 // 2 → -4 |
| % | remainder (modulo) | 17 % 5 → 2 |
| ** | power (not ^!) | 2 ** 10 → 1024 |
A test ran for 3725 seconds. Use // and % to split it into hours h, minutes m and seconds s, and print them.
One hour is 3600 s. Take the hours out first with //, then work on what's left (the %).
Comparison & logical operators
| Op | Meaning |
|---|---|
| == != | equal, not equal |
| < <= > >= | less, less or equal, greater, greater or equal |
| and | True only if both sides are True |
| or | True if at least one side is True |
| not | flips True ↔ False |
Chained comparisons
Python reads a < b < c as (a < b) and (b < c), so 0 <= V <= 5 checks a range in one go. It does the same with mixed operators: 12 >= 12 != 15 means (12 >= 12) and (12 != 15). The test likes this one.
A 5 V supply is safe if it's between 4.75 V and 5.25 V, inclusive. For V = 5.3, store that test in safe as one expression, and print it.
A chained comparison does it in one go: low <= V <= high.
Order of operations
When an expression mixes operators, Python works from the top of this table down. Brackets beat everything.
| Order | Operators |
|---|---|
| 1 | ( ) brackets |
| 2 | ** power, worked right to left: 2**3**2 = 29 = 512 |
| 3 | unary minus: -3**2 = −(3²) = −9 |
| 4 | * / // % left to right |
| 5 | + − left to right |
| 6 | == != < <= > >= (chained) |
| 7 | not |
| 8 | and |
| 9 | or |
Worked example
x = (6 * 2) >= 10 + 2 != 15 x = 12 >= 12 != 15 # brackets, then + x = (12 >= 12) and (12 != 15) # chained x = True and True x = True
Write every step like this in the test. The steps carry marks, not just the final answer.
What does Python print?
Break · 15 minutes
- Scripts, comments, and punctuation that each have one job.
- Variables are created by assignment and are case-sensitive.
- int, float, complex, str, bool, None; and int() truncates.
- / always gives a float; // rounds down; ** is power.
Next
The numbers engineers actually use: why 0.1 + 0.2 isn't 0.3, complex impedance, and the math module. Then you build a small calculator.
Numbers for engineers
Floating point, complex numbers, mathematical functions
Floating-point arithmetic
A float is stored in binary with about 15–16 significant digits. Most decimals, like 0.1, can't be stored exactly.
Is 0.1 * 3 equal to 0.3? Compare them the safe way, store the result in same, and print it.
== gives False here. Use math.isclose(), or check that the difference is smaller than 1e-9.
Rules of thumb
- Never test floats with ==. Use math.isclose or a tolerance.
- Expect tiny errors in the last digits, and round only when you print: f"{x:.3f}".
- int is exact and unlimited; float goes up to about 1.8 × 10308.
- 1.2e3 means 1.2 × 103, and 4.7e-6 means 4.7 µ: handy for component values.
Where do inf and nan come from?
- inf: a result too big for a float.
- nan: an undefined result, such as inf − inf, 0 × inf or inf / inf. Any arithmetic with nan gives nan.
- Dividing by zero: plain Python stops with a ZeroDivisionError. NumPy (Chapter 3) gives inf or nan with a warning instead.
Complex numbers
Python has complex numbers built in. Engineers write j for √−1, and so does Python.
Two impedances, Z1 = 4 + j3 Ω and Z2 = 2 − j1 Ω. Compute them in series, Zs = Z1 + Z2, and in parallel, Zp = Z1·Z2 / (Z1 + Z2). Print both, and the magnitude of Zp.
Python does complex arithmetic directly: just type the formula. abs() gives the magnitude.
Notes
- Write 4j, or 1j on its own. Plain j is just a variable name.
- (3 + 4j) / (1 − 2j) = −1 + 2j. Check it by hand: multiply the top and bottom by the conjugate (1 + 2j).
- The math module is for real numbers only; use cmath for complex ones.
- cmath.rect(r, θ) goes back from polar to rectangular form.
Mathematical functions
Import the math module once at the top of your script, then call its functions with math. in front.
| Call | Gives |
|---|---|
| math.sqrt(x) | √x |
| math.exp(x) | ex |
| math.log(x) | natural log, ln x |
| math.log10(x) | log base 10 (for decibels) |
| math.log(x, b) | log base b |
| math.sin(x) … | x in radians! |
| math.radians(d) | degrees → radians |
| math.degrees(r) | radians → degrees |
| math.hypot(a, b) | √(a² + b²) |
| math.floor / ceil | round down / up |
| math.pi · math.e | π, e |
| abs(x) · round(x, n) | built-ins: no import needed |
A 10 m ladder leans against a wall at 60° to the ground. Its top is at height h = 10 sin 60°. Compute h and print it to 3 decimal places.
math.sin() wants radians: convert 60° with math.radians(60) first. You should get 8.660 m.
The NumPy line takes a few seconds the first time while the library downloads.
Lab: an engineer's calculator
Four short tasks. Write each one in the cell (or in Spyder), then press Check my answer; that also sends your code to your lecturer. Print answers to 3 decimal places with f"{x:.3f}".
1 · A 12 V supply drives a 220 Ω resistor. Compute the current I = V/R and the power P = V·I, and print both to 3 decimal places with their units.
f"{I:.3f}" prints I with 3 decimals. Expect I = 0.055 A.
2 · A transmitter outputs 0.5 W. Power in dBm is 10·log₁₀(P / 1 mW). Print it to 3 decimal places.
1 mW is 1e-3 W. Use math.log10, not math.log (which is ln).
3 · R = 10 Ω, L = 50 mH, C = 100 µF at f = 50 Hz. With ω = 2πf, Z = R + jωL − j/(ωC). Print Z, its magnitude |Z| and its angle in degrees, to 3 decimal places.
Write j as 1j. abs(Z) is the magnitude; cmath.phase(Z) is the angle in radians.
4 · Find both roots of x² + 2x + 5 = 0 with x = (−b ± √(b² − 4ac)) / 2a. Store them in x1 (the + root) and x2, and print them. The discriminant is negative, so use cmath.sqrt.
Brackets matter: divide by (2*a), not 2*a. Expect −1 ± 2j.
Exam toolkit: the templates for Chapters 1–2
Memorise the shapes; in each question, only the ⟨slots⟩ change. Practise by writing each one out by hand.
procedure ⟨Name⟩
input : ⟨inputs⟩
output: ⟨answer⟩
begin
⟨answer ← 0 or 1⟩
while ⟨condition⟩
⟨update answer⟩
⟨move on⟩
end while
return ⟨answer⟩
end| pass | ⟨cond⟩? | ⟨var⟩ | ⟨var⟩ |
|---|---|---|---|
| start | … | … | |
| 1 | ✓ | … | … |
| 2 | ✓ | … | … |
| exit | ✗ | return … | |
One row per pass, one column per variable. Stop at the first ✗: that row gives the answer.
Name the characteristic, then one sentence on why it matters: unambiguous (each step has one meaning), finite (it always stops), correct (right result), language-independent (any language can code it).
Oval = start/end · parallelogram = input/output · rectangle = process · diamond = decision (Yes/No) · circle = connector · arrow = flow.
import math # cmath for complex ⟨x⟩ = ⟨value⟩ # inputs, units in comments ⟨y⟩ = ⟨formula⟩ # one line per formula print(f"⟨y⟩ = {⟨y⟩:.3f} ⟨unit⟩")
Powers are **; trig takes math.radians(deg); 50 mH → 50e-3.
import math, cmath w = 2 * math.pi * ⟨f⟩ Z = ⟨R⟩ + 1j*w*⟨L⟩ - 1j/(w*⟨C⟩) print(abs(Z)) # magnitude print(math.degrees(cmath.phase(Z))) # angle, degrees
Quadratic roots: r = cmath.sqrt(b**2 - 4*a*c), then (-b ± r) / (2*a).
| Pseudocode | Python |
|---|---|
| x ← 0 | x = 0 |
| while n ≥ d | while n >= d: |
| (the body) | indent 4 spaces |
| end while | un-indent |
| a × b, a ≠ b | a * b, a != b |
| return x | print(x) |
- Brackets first.
- ** (right to left), then unary −.
- * / // %, then + −, left to right.
- Split a comparison chain: a >= b != c → (a >= b) and (b != c).
- not, then and, then or.
Write one line per step: the steps carry the marks.
Today in one screen
Design before you code
Problem solving → implementation → maintenance. An algorithm is unambiguous, finite, correct and language-independent. Write it as a flowchart (oval, parallelogram, rectangle, diamond) or as pseudocode, and verify it with a trace table.
Languages
Fortran and C/C++ are compiled and fast; MATLAB and Python are interpreted and quick to work in. Python with NumPy and SciPy is free and widely used, so it's what we use.
Python basics
A variable is created by assignment and names are case-sensitive. The types are int, float, complex, str, bool and None. / gives a float, // rounds down, % is the remainder and ** is power. Precedence: brackets, then arithmetic, comparisons, not, and, or.
Numbers for engineers
Compare floats with a tolerance; inf and nan exist. Complex numbers use j, with abs and cmath.phase. The trig functions in math work in radians.
Final check
Eight questions on today
One last thing: what is still unclear after today?
Before next class: Chapter 3, Complex data types
Get ready
- Install Anaconda or Spyder on your laptop, and bring the laptop next time.
- Redo the four lab tasks in Spyder and save them as .py files, or and work through every ✏️ question in Colab.
- Draw the flowchart for SumEvenNumbers (sum of 2, 4, 6, … up to n) and trace it for n = 6. You should get 12.
Lists and NumPy arrays: creating them, indexing from 0, slicing with start:stop:step, matrices, multidimensional arrays, and strings. These carry marks in the test.