2+24
The cell below contains Python code that can be executed by the Python interpreter. One of the most basic things that we can do with Python is to use it as a calculator:
2+24
Great, but it gets more interesting when we use variables to store information. This is done with the = operator. In Python, variable names:
x = 3.0Once assigned, variables can be used in new operations throughout this notebook:
y = 2.0
x + y5.0
Python knows various types of data. Three common ones are:
number = 42
pi = 3.14159265358
text = "Programming for Medical Imaging"In the example above, three variables are assigned. Variable number is an integer number with a value of 42, while pi is a floating point number and text is of type string.
Using the type command, it is possible to check the data type of a variable:
text'Programming for Medical Imaging'
type(text)str
number42
type(number)int
pi3.14159265358
type(pi)float
In the above examples, most of the times output is printed directly below the cell, but not always the output is printed and not all operations are printed. The print command can be used to control what is printed when.
Note, that text (strings) always has to be surrounded by double or single quotes: " or '.
print("Hello world")Hello world
In the example below we first print the value of the variable number using the print command, and then call the variable:
print(number)
number42
42
Now we do it the other way around:
number
print(number)42
When not using the print function, only the output of the last operation in the input cell is printed. If the last operation is the assignment of a variable, nothing will be printed.
In general print is the only way to print output to the screen when you are not working in an interactive environment like Jupyter (as we are doing now).
Rule of thumb: use the normal output for quick checking the output of an operation while developing in your Jupyter notebook, use print for printing output that still needs to be there in the future while your scripts get more complicated.
Like any programming language, Python knows a wide variety of mathematical operations. A few examples:
summing = 2 + 2
multiply = 2 * 7
power = 2 ** 16
modulo = 13 % 5
print("Sum: ", summing)
print("Multiply: ", multiply)
print("Power: ", power)
print("Modulo: ", modulo)Sum: 4
Multiply: 14
Power: 65536
Modulo: 3
Once we have data stored in variables, we can use the variables to do calculations.
radius = 4.2 # Measured radius in mm
pi = 3.14159265358
area = pi * radius ** 2 # A = πr²
print("The area is:", area)The area is: 55.4176944091512
To carry out common tasks with data and variables in Python, the language provides us with several built-in functions. Examples of built-in functions that we already used above are print and type.
Calling a function: When we want to make use of a function (referred to as calling the function), we type the name of the function followed by parentheses. Between the parentheses we can pass arguments.
Arguments: Arguments are used by a function to perform a certain task; a function performs an operation on, or with its arguments. In the example below, type is the function name and pi is the argument:
type(pi)float
External course material
Other useful built-in functions are e.g.
abs(),max(),min(). Review the other built-in math functions here: https://www.w3schools.com/python/python_math.asp
max(1, 2, 3, 2, 1)3
The print function can have more than one argument. Instead of calling print(text) and print(number), we can call print(text, number), to print the value of both variables on a single line.
Quite often, however, we don’t want to just print a variable’s value, but provide a little more context. Formatted strings are very useful in such cases. These strings start with an f in front of the quotes, and have placeholders for variables between curly braces ({}). In these placeholders, format specifiers may be used to specify the way in which a value is printed:
# Print the area using a format string:
print(f"The area is {area} mm²")
print(f"The area is {area:.2f} mm²") # Specify to print it as a floating point value with two decimals.The area is 55.4176944091512 mm²
The area is 55.42 mm²
External course material
Review the first two sections in String Formatting (F-Strings and Placeholders and Modifiers) and do the exercises: https://www.w3schools.com/python/python_string_formatting.asp
Strings can contain ordinary, readable characters, but they can also contain control characters. These characters do not represent a visible letter or symbol. Instead, they control how text is interpreted or displayed.
In Python and many other languages, the backslash (\) is used as an escape character. When it is followed by certain characters, the combination has a special meaning or allows you to represent a character that would otherwise be difficult or impossible to include directly.
| Character | Meaning |
|---|---|
\n |
New line - starts a new line |
\r |
Carriage return - moves to the beginning of the current line |
\t |
Tab - inserts a tab |
\b |
Backspace - moves one position backward |
\' |
Single quote - inserts a single quote in a single-quoted string |
\" |
Double quote - inserts a double quote in a double-quoted string |
\\ |
Backslash - inserts a backslash |
Windows uses the backslash (\) as a path separator. Because the backslash is also Python’s escape character, you need to take some care when writing Windows paths in strings.
There are three common approaches:
path = "C:\\pmi\\images"r. In a raw string, most escape characters are not interpreted: path = r"C:\pmi\images"/) instead. These are the standard path separator on Linux and macOS, and Python also accepts them for Windows paths: path = "C:/pmi/images"print('C:\random\test') # A string with control characters; this doesn't work as intended!
print('C:\\random\\test\\') # A string with escaped backslashes
print(r'C:\random\test') # A 'raw' string
print('C:/random/test/') # Forward slashesC:
andom est
C:\random\test\
C:\random\test
C:/random/test/
There may be times when you want to specify a specific type, or convert one type into another. This can be done with casting. With data types that allow casting, it can be done like this:
s = "3.9"
x = float(s) # Casts the string s to a float.
print(f"x = {x} {type(x)}")
y = int(x) # Casts the float x to an int.
print(f"y = {y} {type(y)}")
s = str(y) # Casts the int y to a string.
print(f"s = {s} {type(s)}")x = 3.9 <class 'float'>
y = 3 <class 'int'>
s = 3 <class 'str'>
Be aware that casting data from one type to another might result in data loss, because data types may differ in precision or in the range of numbers that they can present. An obvious example is the conversion from float to int, where the decimals will be lost.
A less obvious example is the limited precision of floating point numbers. A float in Python is a standard 64-bit floating point number, where 52 bits are used for the fraction, 11 bits for the exponent, and 1 for the sign. This means that up to \(2^{53}\), the representable numbers are exactly integers, but any larger number is less precise, because the fraction can’t be higher:
x = 2**53 # The integer number 9007199254740992
y = x + 1 # The integer number 9007199254740993
z = x + 2 # The integer number 9007199254740994
print(y)
print(float(y)) # Note that a float cannot represent 2^53 + 1 = 9007199254740993:
print(float(z)) # Float 9007199254740994 is stored as 2^1 * 4503599627370497:9007199254740993
9007199254740992.0
9007199254740994.0
For the same reason, most decimal numbers cannot be represented exactly:
x = 0.3 # Trying to store the floating point number 0.3.
print(f'{x:.32f}') # The nearest representable number for 0.3 is 0.299999999999999988897769753748...
x - 3 * 0.1 # You would expect this to be exactly zero, but it is not:0.29999999999999998889776975374843
-5.551115123125783e-17