SKEE1033 · CH 1–2
SKEE1033 SCIENTIFIC PROGRAMMING · UTM SPACE · CHAPTERS 1–2

From Algorithms to Python

Programs & algorithms · Flowcharts & pseudocode · Choosing a language · Variables, types, operators · Numbers for engineers
In class · about 5 hoursCLO1Dr. Muhammad Ariff BaharudinCourse overview →

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.

First half · Chapter 1
Welcome, the course, set up Python20 min
01 Programs & program development20 min
02 Algorithms, flowcharts, pseudocode, the loop template55 min
03 Choosing a language15 min
Break15 min
Second half · Chapter 2
04 The Python platform, coding with AI, variables, types50 min
05 Operators & expressions35 min
Break15 min
06 Numbers for engineers: float, complex, math35 min
Lab: an engineer's calculator30 min
Exam toolkit, wrap-up & final check15 min

The course in one page

SKEE1033 teaches you to describe engineering problems as algorithms, and then to solve them with programs.

CLO1 · PLO1

Apply

Describe engineering problems with flowcharts and pseudocode, and solve them with programs.

Quiz · Test · Final exam

CLO2 · PLO2

Formulate

Use an advanced scientific language for data processing, analysis and visualisation.

Quiz · Assignment · Final exam

CLO3 · PLO9

Communicate

Read, write and compile technical documents about your work.

Assignment (group project)

Assessment

WhatWeightCovers
Quiz 1, Quiz 25% + 5%CLO1, CLO2
Test20%Chapters 1–5
Assignment20%Group project: one engineering problem solved in Python
Final exam50%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.

The chapters
  1. Overview of languages
  2. Programming platform
  3. Complex data types
  4. Control flow
  5. Functions
  6. Input & output
  7. Debugging & profiling
  8. Graphics
  9. Data interpolation
  10. Polynomials
  11. Data analytics
  12. 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.

Option A · for the course

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

Option B · lighter

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

Option C · right now

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

▶ or Shift+Enter runs a cellCells share variables, in the order you run them▶▶ Run all runs every cell from the top↻ Restart forgets all variables⬇ .ipynb downloads the notebook: open it in Google Colab (File → Upload notebook) or Jupyter

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.

ACTIVITY5 minutes · on your own

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".

01

Programs & program development

What a program is, and the three phases of building one

Chapter 1 · about 20 minutes

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

  1. Lift your hand.
  2. Move it to the right side of the book.
  3. Grasp the top-right corner of the page.
  4. Move your hand from right to left until the page is turned.
  5. 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.
A computer is not intelligent. It can't analyse a problem and come up with a solution. You analyse the problem, design the steps, and describe them. In return, the computer repeats them quickly and consistently, and never gets bored.

Program development: three phases

Writing code is only one part of the job, and it's not the first part.

Phase 1

Problem solving

  1. Analyse & specify: understand the problem and what the solution must do.
  2. General solution: write the algorithm, a logical sequence of steps.
  3. Verify: follow the steps by hand to check they really solve it.
Phase 2

Implementation

  1. Concrete solution: translate the algorithm into a programming language.
  2. Test: run it and check the results. If they're wrong, find the error in the program or the algorithm, then fix it.
Phase 3

Maintenance

  1. Use the program.
  2. Maintain it: change it when the requirements change, and fix the errors that show up later.
ACTIVITY2 minutes

Put the seven steps of program development in order.

Tap one tile, then tap another to swap them. Press Check when you're done.

02

Algorithms, flowcharts, pseudocode

Designing the steps before writing any code

Chapter 1 · about 55 minutes

What is an algorithm?

An algorithm is the general solution. A program is an algorithm written for a computer.

Formal definition

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

  1. Insert the key.
  2. Press the brake pedal.
  3. Make sure the gear is in Park (or Neutral).
  4. Turn the key to the start position.
  5. If the engine starts within 6 seconds, release the key to the ignition position.
  6. If it doesn't start, release the key, wait 10 seconds, and repeat steps 3–6, but no more than five times.
  7. 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.

ACTIVITY3 minutes

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.

Terminal (oval)Start and end
ParallelogramInput and output
RectangleProcessing step
DiamondDecision (yes / no)
CircleConnector (continues elsewhere)
ArrowFlow of control

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.
ACTIVITY2 minutes

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

IdeaWrite
Start / endbegin … end
Procedureprocedure Name … end
Input / outputinput : … output : …
Assignmentresult ← 0
Decisionif … else … end if
Loopwhile … end · for … to … next
Give backreturn 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.

WATCH5 minutes · step through it

IntegerDivision, one line at a time

ACTIVITY4 minutes · paper first

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
ACTIVITY3 minutes

What does it return for n = 2, d = 3?

Show the trace and the fix
checkd ≥ 0?resultd
start13
13 ≥ 0 ✓22
22 ≥ 0 ✓41
31 ≥ 0 ✓80
40 ≥ 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.

ACTIVITY4 minutes

Same template, new question: pick the right slot

PLUG & PLAY8 minutes

Fill the slots: get the pseudocode, the flowchart and the Python

Type <- or = for ←, and >=, <=, * as usual: they're converted for you.

Pseudocode
Flowchart
Python: press ▶ to test it
03

Choosing a language

Why scientific languages exist, and why we use Python

Chapter 1 · about 15 minutes

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.

Since 1957

Fortran

FORmula TRANslation, one of the oldest languages

Fast, good at arrays, and easy to run in parallel. It's still behind weather, climate and physics codes on supercomputers.

Since 1984

MATLAB

MATrix LABoratory

Easy to learn and quick for prototypes, with many specialist toolboxes. Licences are expensive; Octave is a free look-alike.

Since 1985

C / C++

Compiled, general purpose

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.

Since 1991

Python

Interpreted, general purpose

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.

Why Python in SKEE1033

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.

ACTIVITY3 minutes

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

Chapter 1 in four lines
  • 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.

04

The Python platform

Spyder, coding with AI, scripts, variables and data types

Chapter 2 · about 50 minutes

Inside Spyder

Spyder is an IDE (integrated development environment): an editor, a console and a variable viewer in one window.

Left

Editor

Write and save scripts (.py files). F5 runs the whole file; F9 runs the selected lines.

Bottom right

IPython console

Type one command and see the answer at once. Use it to test small ideas. %whos lists your variables.

Top right

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.

1 · Describe

Prompt precisely

Give the inputs with units, the output you want, and the limits ("only the math module"). A vague prompt gets vague code.

2 · Read

Trace it

Read every line. If you can't explain a line, ask the AI to explain it, or don't use it.

3 · Test

Check one case by hand

Run it on numbers you can work out yourself. AI code often runs fine and is still wrong.

4 · Own it

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.

In the test and the final exam there is no AI and no computer: you write pseudocode, flowcharts and Python by hand. So treat AI like a tutor, not a crutch. What you need in the exam hall is the templates (collected on the Exam toolkit page at the end) and the judgement to fill them in.

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.

ACTIVITY5 minutes

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 Ω.

SymbolJobExample
#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 leftR = 220
==Comparison: are they equal? (Section 05)R == 220
( )Grouping, and calling a functionprint(I)
[ ]Lists and indexing (Chapter 3)v[0]
:Starts an indented block (Chapter 4)if I > 1:
indent4 spaces mark which lines belong to a block. In Python, indentation is part of the syntax.····print(I)
,Separates itemsprint("I =", I)
.Decimal point; also "something inside": a module's function or an object's attributemath.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.

ACTIVITY2 minutes

Valid Python variable name, or not?

Basic data types

Every value has a type, and type(x) tells you which.

TypeWhat it holdsExamples
intWhole numbers, of any size10 · -5 · 2**100
floatNumbers with a decimal point or an exponent3.14 · 1.2e3 · 7/2
complexReal + imaginary, written with j3+4j · complex(3, 4)
strText, in single, double or triple quotes'Hi' · "7" · """multi-line"""
boolLogical: exactly True or FalseTrue · 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.
ACTIVITY4 minutes

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.

05

Operators & expressions

Arithmetic, comparison, logic, and the order Python works in

Chapter 2 · about 35 minutes

Arithmetic operators

OpMeaningExample → result
+ −add, subtract7 - 2 → 5
*multiply7 * 2 → 14
/divide: always a float7 / 2 → 3.5 · 6 / 2 → 3.0
//floor division: round down7 // 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 %).

// and % together split a number into "how many whole times" and "what's left". IntegerDivision and FindRemainder from Part 02 are just n // d and n % d.

Comparison & logical operators

OpMeaning
== !=equal, not equal
< <= > >=less, less or equal, greater, greater or equal
andTrue only if both sides are True
orTrue if at least one side is True
notflips 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.

OrderOperators
1( ) brackets
2** power, worked right to left: 2**3**2 = 29 = 512
3unary minus: -3**2 = −(3²) = −9
4* / // % left to right
5+ − left to right
6== != < <= > >= (chained)
7not
8and
9or

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.

ACTIVITY6 minutes · work it out, don't run it

What does Python print?

Break · 15 minutes

So far in Chapter 2
  • 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.

06

Numbers for engineers

Floating point, complex numbers, mathematical functions

Chapter 2 · about 35 minutes

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.
Where you'll use this: AC circuit impedance, phasors, and the roots of polynomials (Chapter 10). For a series RLC circuit, Z = R + jωL − j/(ωC). We compute it in the lab.

Mathematical functions

Import the math module once at the top of your script, then call its functions with math. in front.

CallGives
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 / ceilround 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.

T1 · Algorithm (pseudocode)
procedure ⟨Name⟩
input : ⟨inputs⟩
output: ⟨answer⟩
begin
    ⟨answer ← 0 or 1⟩
    while ⟨condition⟩
        ⟨update answer⟩
        ⟨move on⟩
    end while
    return ⟨answer⟩
end
T2 · Flowchart
T3 · Trace table
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.

T4 · Good-algorithm question

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).

T5 · Flowchart symbols

Oval = start/end · parallelogram = input/output · rectangle = process · diamond = decision (Yes/No) · circle = connector · arrow = flow.

T6 · Calculation script
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.

T7 · AC / complex numbers
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).

T8 · Pseudocode → Python
PseudocodePython
x ← 0x = 0
while n ≥ dwhile n >= d:
(the body)indent 4 spaces
end whileun-indent
a × b, a ≠ ba * b, a != b
return xprint(x)
T9 · "What is x?" (evaluate an expression)
  1. Brackets first.
  2. ** (right to left), then unary −.
  3. * / // %, then + −, left to right.
  4. Split a comparison chain: a >= b != c → (a >= b) and (b != c).
  5. not, then and, then or.

Write one line per step: the steps carry the marks.

Today in one screen

01 · 02

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.

03

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.

04 · 05

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.

06

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

SELF-CHECK5 minutes · not graded

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.
Next time

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.