Getting Started
We first want to get familiar with the basic principles of the programming language Python. In particular, we want to learn which data types are provided by default and how to work with them. Furthermore, we want to get somewhat used to the syntax of this programming language.
Variables and Data Types¶
Using Python as a Calculator¶
Python can be used like a calculator. Intermediate results can be easily stored in variables using the assignment operator =:
3+58a = 3+5
b = a/2
b4.0Variables in Python do not need to be declared beforehand. The data type is automatically determined based on the assigned value.
The type function can be used to determine the data type of a variable:
print("a is a", type(a))
print("2 is a", type(2))
print("2. is a", type(2.))
print("b is a", type (b))a is a <class 'int'>
2 is a <class 'int'>
2. is a <class 'float'>
b is a <class 'float'>
Additional mathematical functions are included in the math module, which must first be imported into the Python script:
import math
print("The square root of 9 is", math.sqrt(9))
print("2 to the power of 3 is", 2**3)
print("The natural logarithm of 3 is", math.log(3))The square root of 9 is 3.0
2 to the power of 3 is 8
The natural logarithm of 3 is 1.0986122886681098
To find out which functions the math module provides, you can simply type in JupyterLab:
math.<TAB>This will display a list of all available functions and constants in the module.
In this example, we also saw how to import and use additional modules. Functions from the math module must be called with math.sin(...). Alternatively, all functions of a library can be imported using
from math import *and then all functions and variables can be used without specifying the module name.
Note: This can lead to naming conflicts with functions and variables from other libraries.
from math import *
print("The sine of pi/2 is", sin(pi/2))The sine of pi/2 is 1.0
Numeric Data Types¶
In the previous section, we already learned about the type function and observed two different data types in our calculations. The numeric data types are summarized in the following table:
| Data Type | Description | Examples |
|---|---|---|
int | Integer numbers | 2, 3*8 |
float | Floating-point numbers | 2., 3/2, math.pi |
bool | Boolean value | True, 1==0, 1<3 |
complex | Complex numbers | 2+4j, cmath.sqrt(-9) |
Boolean variables can only take the values true (True) or false (False). They are, among other things, the result of comparison operations:
a = 1 < 3
print("a is a variable of type", type(a), "and has the value", a)
b = 1 == 0
print("b is a variable of type", type(b), "and has the value", b)a is a variable of type <class 'bool'> and has the value True
b is a variable of type <class 'bool'> and has the value False
Complex numbers are a built-in data type in Python (complex).
The imaginary unit is written as j instead of i.
For complex numbers, corresponding arithmetic operations are defined in the cmath module, which can be imported using:
import cmathBy the way, a quick documentation of a library can be accessed by typing
cmath?in a code cell.
Here is a small example of complex numbers:
import cmath
a = cmath.sqrt(-9)
print("The square root of -9 is", a)
b = 1 + 2j
c = a / b
print("The quotient of a and b is", c, "and is again of type", type(c))
print("Re(c) =", c.real,
", Im(c) =", c.imag,
"and the complex conjugate is =", c.conjugate())The square root of -9 is 3j
The quotient of a and b is (1.2+0.6j) and is again of type <class 'complex'>
Re(c) = 1.2 , Im(c) = 0.6 and the complex conjugate is = (1.2-0.6j)
Strings¶
| Data Type | Description | Example |
|---|---|---|
string | An arbitrarily long sequence of characters | 'Hello world', "ABCDE" |
An object of type string is a sequence of characters, as we have already used in console outputs. Strings are enclosed in single quotes ' or double quotes ".
a = "I am a string." # Create a string
a += "\nA very long string." # Append another string
a += "\nNow already " + str(3) + " lines long" # Convert integer to string and append
print(a)I am a string.
A very long string.
Now already 3 lines long
The special character '\n' represents a line break. To convert objects of other types into a string, we use the function str(). The addition operator + concatenates two strings, and the += operator appends one string to another.
If we type a.<TAB>, we again get a list of useful functions that can be applied to strings. Alternatively, all methods defined for strings can be listed as follows:
dir(a)['__add__',
'__class__',
'__contains__',
'__delattr__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__getitem__',
'__getnewargs__',
'__getstate__',
'__gt__',
'__hash__',
'__init__',
'__init_subclass__',
'__iter__',
'__le__',
'__len__',
'__lt__',
'__mod__',
'__mul__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__rmod__',
'__rmul__',
'__setattr__',
'__sizeof__',
'__str__',
'__subclasshook__',
'capitalize',
'casefold',
'center',
'count',
'encode',
'endswith',
'expandtabs',
'find',
'format',
'format_map',
'index',
'isalnum',
'isalpha',
'isascii',
'isdecimal',
'isdigit',
'isidentifier',
'islower',
'isnumeric',
'isprintable',
'isspace',
'istitle',
'isupper',
'join',
'ljust',
'lower',
'lstrip',
'maketrans',
'partition',
'removeprefix',
'removesuffix',
'replace',
'rfind',
'rindex',
'rjust',
'rpartition',
'rsplit',
'rstrip',
'split',
'splitlines',
'startswith',
'strip',
'swapcase',
'title',
'translate',
'upper',
'zfill']This list contains the names of all methods that can be applied to the object a. A method is generally a function that can be applied to objects of a certain data type (in our example, string). The syntax to call a method is as follows:
<result> = <object>.<method>(<param1>, <param2>, ...)<object>is the name of a Python object (herea, of typestring).<method>is the name of a method from the list generated above.<result>is the object returned by the method.
However, there are also methods that do not return anything. In this case, the part <result> = is omitted.
Let’s test this with the replace method, which – as the name suggests – replaces certain characters (or substrings) with others. The central question is:
Which parameters must be passed to the method and what does it return?
Note: A good programmer is not someone who memorizes methods and parameters for all data types. Much more important is the ability to read code documentation.
Example: Google python string replace and open the first result: https://
Two parameters are required: **
oldvalue– the part of the string to be replaced
**newvalue– the new string to insert instead ofoldvalueAn optional parameter
countdetermines how many occurrences to replace. By default, all are replaced.The method returns a new string containing the changes.
Alternatively, the built-in documentation in JupyterLab can be used:
a.replace?This will output, for example:
Signature: a.replace(old, new, count=-1, /)
Docstring:
Return a copy with all occurrences of substring old replaced by new.
count
Maximum number of occurrences to replace.
-1 (the default value) means replace all occurrences.
If the optional argument count is given, only the first count occurrences are
replaced.
Type: builtin_function_or_methodApplying the replace method to strings looks like this, for example:
# Define string
a = "I am a string"
# Replace certain substrings
a = a.replace("I", "We")
a = a.replace("am", "are")
a = a.replace("string", "sentence")
# Console output
print(a)We are a sentence
If we look again at the list of all string methods above, we notice that some methods begin with two underscores. These are intentionally hidden methods and should generally not be used directly.
Some of these methods are used for operator overloading, e.g.:
__eq__→ implements the equality operator==__add__→ implements the addition operator+
We will discuss this in more detail in section Special methods.
In the following example, we apply some of the methods defined for strings:
# Concatenation operator += (internally calls __add__)
a = "I am a string,"
a += " which is already quite long"
print(a)
# Equality operator == (internally calls __eq__)
b = "abc"
v = (b == "abc")
print("The statement 'b equals abc' is", v)I am a string, which is already quite long
The statement 'b equals abc' is True
The method string.split() produces an object of type list, which we will examine in more detail in the following section.
Container Classes¶
Other important data types are lists and n-tuples:
| Data Type | Description | Examples |
|---|---|---|
list | List of any number of elements of any type | [1,2.2,'Hello'] |
tuple | Collection of a fixed number of elements | (1,"a") |
set | Set of unique elements | {1, 2, 3} |
dict | Key-value pairs | {'Name': 'Max', 'Age': 25} |
Lists¶
Let’s take a closer look at lists.
list is a data type that allows grouping multiple objects of any type into a single object. Additionally, numerous useful methods are provided to access the elements of the list or to modify the list.
dir(list)['__add__',
'__class__',
'__class_getitem__',
'__contains__',
'__delattr__',
'__delitem__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__getitem__',
'__getstate__',
'__gt__',
'__hash__',
'__iadd__',
'__imul__',
'__init__',
'__init_subclass__',
'__iter__',
'__le__',
'__len__',
'__lt__',
'__mul__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__reversed__',
'__rmul__',
'__setattr__',
'__setitem__',
'__sizeof__',
'__str__',
'__subclasshook__',
'append',
'clear',
'copy',
'count',
'extend',
'index',
'insert',
'pop',
'remove',
'reverse',
'sort']We can see that the data type list provides methods such as append, clear, copy, and so on.
Additionally, we notice that an addition operator (via __add__), a comparison operator (via __le__), and a multiplication operator (via __mul__) are also defined.
Let’s try out some of these methods:
L = [1,3,5] # Create a list [1,3,5]
L.append(2) # Append an element [1,3,5,2]
L = L + [4,6] # Append another list [1,3,5,2,4,6]
L.sort() # Sort the list [1,2,3,4,5,6]
L.pop() # Remove the last element [1,2,3,4,5]
L = 2 * L # Duplicate the list [1,2,3,4,5,1,2,3,4,5]
L # Output to console[1, 2, 3, 4, 5, 1, 2, 3, 4, 5]There are also several ways to create lists. A useful tool is the range class (see range? for a detailed description). Some examples:
L1 = list(range(10)) # Equivalent to L1 = [0,1,2,...,9]
print("L1 =", L1, ": contains", len(L1), "elements")L1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] : contains 10 elements
L2 = list(range(1,11,2)) # Odd numbers from 1 to 10
print("L2 =", L2, ": contains", len(L2), "elements")L2 = [1, 3, 5, 7, 9] : contains 5 elements
With a for loop, we can iterate over a list and access individual elements. The syntax of such a loop is as follows:
for [element] in [list]:
[do something]A simple example:
for a in L:
print("The list contains", a)The list contains 1
The list contains 2
The list contains 3
The list contains 4
The list contains 5
The list contains 1
The list contains 2
The list contains 3
The list contains 4
The list contains 5
To read or write a single element of a list, use the access operator []. Note that the first element has index 0, the second has index 1, and so on.
import random # Random number generator
colors = ['red', 'blue', 'green', 'black', 'yellow']
for i in range(3):
index = random.randint(0, len(colors)-1) # Generate random number between 0 and 4
color = colors[index] # Select the corresponding color
print("I spy with my little eye something that is", color)I spy with my little eye something that is red
I spy with my little eye something that is green
I spy with my little eye something that is black
Tuples¶
Finally, we look at the tuple class. This container is used for ordered lists of fixed size. Tuples are often used in functions that return 2 or more values. These values are then returned as an n-tuple. An example is the magnitude (r) and the argument (\varphi) of a complex number (z = a+i,b = r,e^{i,\varphi}):
import cmath
a = 1+3j
res = cmath.polar(a)
print("The return value", res, "of the function 'cmath.polar' is of type", type(res))The return value (3.1622776601683795, 1.2490457723982544) of the function 'cmath.polar' is of type <class 'tuple'>
print("Magnitude:", res[0])
print("Angle :", res[1])Magnitude: 3.1622776601683795
Angle : 1.2490457723982544
Accessing an element of the tuple is done using the [] operator.
Even more elegant is tuple unpacking:
(a_abs, a_arg) = cmath.polar(a)
print("Magnitude:", a_abs)
print("Argument :", a_arg)Magnitude: 3.1622776601683795
Argument : 1.2490457723982544
Classes and Functions¶
In the previous sections, we have already learned some important concepts of the Python programming language. We want to summarize them here.
Variables
Behind every variable is an object, also called an instance. Every instance belongs to a class, for example:
3.0belongs to the classfloat"Hello"belongs to the classstring[1,2,3]belongs to the classlist
We can find out which class an instance belongs to using the function type(...).
During this course, we will learn many more classes and even create our own. It is important to know at this point that classes bundle specific attributes and operations for instances of that class.
Example: The complex class stores the real and imaginary parts of a complex number. We can access them using:
a.real1.0a.imag3.0Methods
Methods are functions that are associated with instances of a class. They can be called using
<result> = <instance>.<method>(<param1>, <param2> [...])Methods that do not require input parameters are still called with empty parentheses ().
We can get the documentation for a method using
<instance>.<method>?To find out which methods a class offers, we create an instance a of this class and type a.<TAB> in the notebook, or use the function dir(a).
Example: The complex class provides the function conjugate() and can be called as follows:
b = a.conjugate()
print("The complex conjugate of", a, "is", b)The complex conjugate of (1+3j) is (1-3j)
Free Functions
Free functions are not tied to a class and can be called without specifying an instance.
An example is the function sum(...). Often, these functions can be applied to objects of different classes. For instance, the function sum(...) works for lists
sum([1,2,3])6as well as for tuples
sum((1,2,3))6For strings, however, the function sum is not applicable and produces an error:
sum("Teststring")---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[26], line 1
----> 1 sum("Teststring")
TypeError: unsupported operand type(s) for +: 'int' and 'str'