All courses › Programming with Python
Programming with Python (Python): free practice, theory and problems
A program is a recipe that the computer follows line by line. In Python you store values in variables, calculate with them and print the result. As an engineer you use this to automate calculations, read measurement data and test ideas quickly, instead of typing the same thing into a calculator a hundred times.
Contents
1. Python basics
What is it about?
A program is a recipe that the computer follows line by line. In Python you store values in variables, calculate with them and print the result. As an engineer you use this to automate calculations, read measurement data and test ideas quickly, instead of typing the same thing into a calculator a hundred times.
Everything in Python has a type. The type decides what you can do with a value: you can calculate with numbers, and you can slice and join text.
Concepts and formulas
- Variable: a name that refers to a value.
x = 5means "let x refer to 5" (assignment). It is not an equation. - Types:
int(integer,7),float(decimal number,7.0),str(text,"hello"),bool(TrueorFalse) andlist([1, 2, 3]). - Arithmetic operators:
+ - * /,//(floor division, rounds down),%(remainder) and**(power). - Precedence:
**is evaluated before* / // %, which in turn come before+ -. Operators on the same level are evaluated from left to right. Use parentheses when in doubt. /always gives afloat.//and%round towards minus infinity, so-7 // 2is-4.- Indexing: the first character has index 0, and
s[-1]is the last one. Slicing:s[a:b]includes indices a up to and including b − 1. - Conversion:
int("42"),float("2.5")andstr(3).int(6.9)drops the decimals and gives 6. - Output:
print(f"F = {F:.1f} N")inserts the value into the text with one decimal.
How to solve the problems
- Read the code line by line, and write down the value of every variable after each line.
- Find the type of each value (int, float or str) before you calculate.
- Evaluate expressions in the right order: parentheses, then
**, then* / // %from the left, and finally+ -. - Check whether the result is an integer or a float, and how it is printed.
Example
A sensor sends the text "L=1234mm". We want the length in meters:
s = "L=1234mm"
mm = int(s[2:-2])
m = mm / 1000
print(m, mm // 1000, mm % 1000)
s[2:-2]starts at index 2 (afterL=) and stops before the last two characters. This gives"1234".int("1234")turns the text into the integer 1234.mm / 1000gives the float 1.234.mm // 1000is 1 (whole meters), andmm % 1000is 234 (the remaining millimeters).
The output is 1.234 1 234.
Common mistakes
- Believing that
input()returns a number. It always returns a string, so you must writefloat(input()). - Forgetting that indices start at 0 and that the end index of a slice is not included.
- Using
=(assignment) when you mean==(comparison). - Comparing floats with
==.0.1 + 0.2 == 0.3isFalsebecause floats are stored in binary with rounding. - Adding text and numbers:
"5" + 3raisesTypeError. Convert first.
Concepts in this part
2. Loops and conditions
What is it about?
A program only becomes really useful when it can make decisions and repeat work. Conditions (if) let the program choose a path based on the data, for example switching off a pump when the pressure gets too high. Loops (for and while) repeat code, for example to go through a thousand measurements or to simulate a process minute by minute.
Concepts and formulas
if/elif/else: Python checks the conditions from the top down and runs only the first branch that is true.- Comparison:
==,!=,<,<=,>and>=. Logic:and,orandnot. Chains such as0 < x < 10are allowed. - Truth values:
0,0.0,"",[]andNonecount as false. Everything else counts as true. for x in my_list:goes through the elements one at a time.range(start, stop, step)gives integers from start up to, but not including, stop.range(a, b)gives b − a values.while condition:repeats as long as the condition is true. Something inside the loop must change the condition, or it runs forever.breakends the whole loop.continueskips the rest of the current iteration and moves to the next one.- Indentation (four spaces) decides what belongs to the loop or the
ifstatement. - Common patterns: accumulator (
total += x), counter (n += 1) and search (if ...: break).
How to solve the problems
- Make a table with one column per variable and one row per iteration.
- In a
whileloop, check the condition before every iteration. - Follow the indentation carefully: what happens inside the loop, and what happens after it?
- Stop when the condition becomes false or
breakruns, and read off the values. - Check the first and the last iteration extra carefully. That is where most mistakes happen.
Example
A tank holds 500 L and 20% of the contents is drained every minute. After how many minutes is there less than 100 L left?
V = 500.0
t = 0
while V >= 100:
V = 0.8 * V
t += 1
print(t)
Value table (V after each iteration): t = 1: 400, t = 2: 320, t = 3: 256, t = 4: 204.8, t = 5: 163.84, t = 6: 131.07, t = 7: 104.86 and t = 8: 83.89. Now V >= 100 is false, and the loop stops. The output is 8.
Check with mathematics: gives , i.e. 8 minutes.
Common mistakes
- Believing that
range(1, 5)includes 5. It gives 1, 2, 3 and 4. - Writing two
ifstatements when you meantifandelif. Then both branches can run. - Forgetting to update the variable in a
whileloop, so that the loop never stops. - Wrong indentation: a line that should have been inside the loop runs only once afterwards.
- Doing one iteration too many or too few (off-by-one).
Concepts in this part
3. Functions and data structures
What is it about?
As a program grows, you split it into functions: small, named pieces that take values in and give a result back. Then you can test each part on its own and reuse it, for example one function that computes stress and one that reads a file of measurements. Data structures decide how you store many values: a list of measurements, a dictionary of material data or a set of unique IDs.
Concepts and formulas
def f(a, b=2):defines a function with the parameters a and b. b has the default value 2.- Calls:
f(3),f(3, 5)or with a keyword:f(3, b=5). returnends the function and sends a value back. Withoutreturnthe result isNone.printonly shows something on the screen.- Variables created inside a function are local and disappear when the function finishes.
- List
[3, 1, 2]: ordered and mutable (append,pop,insert,sort). - Tuple
(3, 1, 2): ordered but immutable. - Dictionary
{"E": 210}: key and value. Used["E"],d.get(k, default)andd.items(). - Set
{1, 2, 3}: unordered and without duplicates.x in my_setis fast. - List comprehension:
[2 * x for x in xs if x > 0]builds a new list in one line. - Assignment does not copy: after
b = a, a and b refer to the same list. Usea.copy()to get a copy.
How to solve the problems
- Find the values the parameters get in the call (positional, keyword or default).
- Go through the function body line by line with those values.
- Look for
return: what is sent back, and what is only printed? - Keep track of whether a list or dictionary is modified or a new one is created.
Example
def mean_ok(xs, limit=100):
ok = [x for x in xs if x <= limit]
return sum(ok) / len(ok)
data = {"A": [98, 102, 97], "B": [101, 99, 150]}
res = {k: mean_ok(v, limit=120) for k, v in data.items()}
print(res["B"])
- For the key
"B",xs = [101, 99, 150]andlimit = 120(the keyword overrides the default value 100). - The list comprehension keeps the values that are at most 120:
[101, 99]. The value 150 is a faulty measurement and is filtered out. sum(ok) / len(ok)becomes 200 / 2 = 100.
The output is 100.0. It is a float because / is used. Similarly, res["A"] equals 99.
Common mistakes
- Using
printinstead ofreturn. Then the caller only getsNone. - Believing that
b = amakes a copy of a list. - Using a list as a default value (
def f(x, lst=[]):). The list is created only once and shared by all calls. UseNoneand create the list inside the function. - Looking up a missing key:
d["x"]raisesKeyError. Used.getor check withinfirst. - Modifying a list while looping over it.
return. Lists and dictionaries are mutable, and every name that refers to the same object sees the change.Concepts in this part
4. Files, errors and modules
What is it about?
Real programs read data from files (measurements, log files, CSV from a spreadsheet), must cope with bad data and use ready-made tools from modules. This part shows the few things you need to do it safely.
Concepts and formulas
- Open a file with
with. The file is then closed automatically, even if an error occurs:
with open("data.txt") as f:
for line in f:
print(line.strip())
- Modes:
"r"reads (default),"w"writes and erases what was there,"a"appends to the end. - Clean up text:
line.strip()removes spaces and line breaks at the ends,line.split(",")splits into a list. - Text to numbers:
int("12")andfloat("3.5"). They raiseValueErrorif the text is not a valid number. - Catch errors with
try/exceptso the program does not crash:
try:
x = float(text)
except ValueError:
x = None
- Modules:
import mathgivesmath.sqrt(2).from math import sqrtgivessqrt(2)directly. - Format numbers:
f"{x:.2f}"showsxwith two decimals.
How to solve the problems
- Go through the code line by line and write down the value of each variable.
- Remember that everything you read from a file or from
input()is text until you convert it. - When a line can fail: see which
exceptcatches it and jump there.
Example
data = "12;7;x;5"
numbers = []
for s in data.split(";"):
try:
numbers.append(int(s))
except ValueError:
pass
print(sum(numbers))
split(";")gives["12", "7", "x", "5"].int("x")raisesValueError, which is caught, so"x"is skipped.numbersbecomes[12, 7, 5], and the program prints24.
Common mistakes
- Calculating with text:
"3" + "4"becomes"34", not 7. - Opening with
"w"when you wanted to append. Then the old content is gone. - Forgetting
strip(), so the line break is kept. - Catching every error with a bare
except:. Then you also hide errors you should have seen.
Concepts in this part
Example problems with solutions
Here are some of the problems in programming with Python. In the app, calculation problems get new numbers every time, so you can practise until it sticks – and take a graded practice exam before the real one.
Python basics: What does print(7 // 2) print?
Answer: 3
// is integer (floor) division and rounds down.
Loops and conditions: What does the code print?for i in range(2, 8, 2):
print(i, end=" ")
for i in range(2, 8, 2):
print(i, end=" ")Answer: 2 4 6
range(start, stop, step). The stop value is not included.
Functions and data structures: What does a function without a return statement return?
Answer: None
Python returns None implicitly.
Files, errors and modules: You want to add new measurements at the end of log.txt without erasing what is there. Which mode do you use in open("log.txt", ...)?
Answer: "a"
"a" (append) writes at the end. "w" empties the file first, "r" can only read, and "x" fails if the file already exists.
Matches these university courses
The content covers the syllabus found in engineering degrees, for example:
- MEK1300 (OsloMet)
- TDT4110 (NTNU)
- INF120 (NMBU)