A41 of 56
0 XP
  1. Hook
  2. Predict
  3. Name it
  4. Check
  5. Explain

A4 · Lesson 1 · Values, variables and functions

Writing a calculation down once, so it runs forever

You've worked out a voltage divider by calculator a dozen times now. Each time, you type the same steps with new numbers, and each time you can slip a digit. Write the steps down once as code and they run perfectly for any numbers, a thousand times a second. The code below runs right here in your browser: no installing anything.

Predict

What does print(2 ** 10) show?

Name it

The pieces you need first

Numbers and arithmetic. Python does arithmetic the way you'd expect, with ** for powers. Scientific notation uses e: 4.7e3 is 4700 and 100e-9 is 100 nF in farads.

V = 12          # a variable holding a number; # starts a comment
R = 4.7e3       # 4.7 kΩ, written in ohms
I = V / R       # about 0.00255 A
P = V**2 / R    # about 0.0306 W

Python has no units: a variable holds a plain number. The convention in this course is to keep every quantity in base SI units (volts, amps, ohms, farads, seconds), so that formulas work without conversion factors. Write prefixes as powers of ten: k = 1e3, m = 1e-3, u = 1e-6, n = 1e-9.

Showing results. print(I) shows a raw number like 0.002553191489361702. An f-string formats it: print(f"I = {I*1e3:.3g} mA") shows I = 2.55 mA. The .3g means three significant figures.

Functions. A function packages a calculation so you can reuse it:

def divider(Vs, R1, R2):
    """Output voltage of a two-resistor divider."""
    return Vs * R2 / (R1 + R2)

print(divider(12, 10e3, 4.7e3))   # 3.836...

def names the function and its inputs; the indented lines are its body; return sends back the result. Indentation matters in Python: it's how the language knows which lines belong to the function.

The math module. import math brings in math.pi, math.sqrt, math.log10, math.exp, math.sin (angles in radians) and many more.

Each lab below has a starter you edit and a Check button that runs hidden tests on your code. The values named in each question (like R or C) are already set when your code runs.

Worked example

Write a function for an LED's series resistor, and use it for a red LED (2.0 V, 20 mA) on 5 V.

Show the solution
  1. Write the formula as a function. The resistor drops what the LED doesn't, at the LED's current.
def led_resistor(Vs, Vf, I):
    """Series resistor in ohms for an LED with forward voltage Vf at current I."""
    return (Vs - Vf) / I

R = led_resistor(5, 2.0, 0.020)
print(f"R = {R:.3g} Ω")      # R = 150 Ω
  1. Check the number. The resistor drops 5−2=3 V at 20 mA: R=3V0.020A=150Ω
  2. Reuse it. Written as a function, the same line handles a blue LED on 3.3 V or a string of LEDs on 12 V.

Answer the red LED on 5 V needs a 150 Ω resistor.

Worked example

Print a resistor's power with a sensible number of digits.

Show the solution
  1. Compute the power and print it two ways. P=V2/R for 12 V across 470 Ω.
V, R = 12, 470
P = V**2 / R
print(P)                       # 0.30638297872340425
print(f"P = {P*1e3:.3g} mW")   # P = 306 mW
  1. Read the raw print. The raw float shows 17 digits that mean nothing.
  2. Format it. Three significant figures in milliwatts is what you'd write in a report.

Answer print it with an f-string as P = 306 mW.

Check

Write a function power(V, R) that returns the power, in watts, that a resistor R dissipates with voltage V across it.

This lab's V = 10 V and R = 15 Ω are already defined, in volts and ohms.

Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.

Check

Write parallel(R1, R2) that returns the resistance of two resistors in parallel, R1R2/(R1+R2).

Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.

Check

Write divider(Vs, R1, R2) returning a divider's output voltage, then print it for this lab's values with three significant figures, like Vout = 3.84 V.

Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.

Check

What does 7 // 2 give in Python?

Check

A wire's resistance is R=ρL/A, with A=πd2/4 the area of its cross-section. Write wire_resistance(rho, L, d) with everything in SI units (meters). Then set R for copper (ρ=1.68×10−8 Ω·m) of length L = 2 m and diameter d = 0.5 mm.

Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.

Check

What does this print?

x = 5
y = x
x = x + 1
print(y)

Explain why

Why is it worth writing even a short formula like a voltage divider as a function?

Practice

Keep practicing

8 kinds of problem on this topic, dealt one at a time with new numbers every time, for as long as you like.