Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

YouTube Video

Video not loading? Click here.

Running Python

There are three main ways to use Python.

  1. By running a Python file, e.g. python myscript.py

  2. Through an interactive console (Python interpreter or iPython shell)

  3. In an interactive notebook (e.g. Jupyter, .ipynb files)

In this course, we will mostly be interacting with Python via Jupyter notebooks. These are files that contain both code cells (which can be executed) and text cells (which can contain formatted text, images, links, etc.).

Basic Variables

A variable is a name that refers to a value stored in the computer’s memory. In Python, you can create a variable by assigning a value to it using the = operator. For example:

Anything that comes after the # symbol is a comment and is ignored by Python.

The following identifiers are used as reserved words and should not be used as variable names:

False      class      finally    is         return
None       continue   for        lambda     try
True       def        from       nonlocal   while
and        del        global     not        with
as         elif       if         or         yield
assert     else       import     pass
break      except     in         raise

Additionally, the following built-in utility functions are always available:

abs() dict() help() min() setattr() all() dir() hex() next() slice() any()
divmod() id() object() sorted() ascii() enumerate() input() oct() staticmethod()
bin() eval() int() open() str() bool() exec() isinstance() ord() sum() bytearray()
filter() issubclass() pow() super() bytes() float() iter() print() tuple()
callable() format() len() property() type() chr() frozenset() list() range()
vars() classmethod() getattr() locals() repr() zip() compile() globals() map()
reversed() __import__() complex() hasattr() max() round() delattr() hash()
memoryview() set()

Variables can be inspected by simply typing their name in a code cell and executing it, or by using the print() function:

1
hello

All variables are objects. Every object has a type (class) that defines the possible values it can take and the operations that can be performed on it.

To find out what type your variables are, you can use the type() function:

int
str

We can check for the type of an object:

True
False

The NoneType is its own type in Python. It only has one possible value, None - it represents an object with no value.

None
NoneType

Objects can have attributes and methods, which can be accessed via variable_name.method_name and called via variable_name.method_name().

It is important to note that methods only do something when they are called (i.e. written with parentheses).

This calls the method:

'Hello'

This does not (it just returns the method itself):

<function str.capitalize()>

String Operators

Basic operations to modify strings help in manipulating text data, for example:

['HOW', 'ARE', 'YOU', 'TODAY?']
'HOW-ARE-YOU-TODAY?'

Python has ways of creating strings by filling in the blanks and formatting them nicely.

This is helpful for when you want to print statements that include variables or statements.

'In Berlin, there is a CHP power plant Reuter West Power Plant. It has a nominal capacity of 564.12 MW.'

Math

Basic arithmetic and boolean logic is part of the core Python library.

-3
50
0.5
16
1

Comparison Operators

We can compare objects using comparison operators, and we’ll get back a Boolean (i.e. True/False) result:

OperatorDescription
x == y is x equal to y?
x != yis x not equal to y?
x > yis x greater than y?
x >= yis x greater than or equal to y?
x < yis x less than y?
x <= yis x less than or equal to y?
x is yis x the same object as y?
True
False
True
True

Boolean Operators

We also have so-called “boolean operators” or “logical operators” which also evaluate to either True or False:

OperatorDescription
x and yare x and y both True?
x or yis at least one of x and y True?
not xis x False?
False
True
True
True

Conditionals

Conditionals are the first step toward more complex programming and offer an opportunity to get familiar with Python syntax. At their core, conditionals allow a program to make decisions about what code to execute depending on certain conditions.

Positive Number

In Python, indentation is mandatory and blocks of code are closed by the indentation level.

Positive Number
Huge number!

There is also a way to write if-else statements inline, i.e., in a single line, for simplicity.

'short list'

Loops

Loops are another fundamental programming construct that allows a program to perform repetitive tasks. They govern the flow of execution by repeatedly processing a block of code, often until a certain condition is reached or for a predefined number of iterations.

There are two types of loops: the for loop, which iterates over a sequence of values, and the while loop, which continues execution as long as a specified condition remains true.

10
0
1
2
3
4

We can also use a for loop to iterate over a sequence of values, for instance, the elements of a list.

electricity 11
hydrogen 8
methane 7

We can use enumerate() to get both the index and the value while iterating over a list.

0 electricity 11
1 hydrogen 8
2 methane 7

What do the square brackets mean? A list! Lists are one of the core Python data structures.

Lists

list

Lists have a lot of useful methods for manipulating them, for instance, sorting them:

['electricity', 'hydrogen', 'methane']

There are many different ways to interact with lists. For instance:

FunctionDescription
list.append(x)Add an item to the end of the list.
list.extend(L)Extend the list by appending all the items in the given list.
list.insert(i, x)Insert an item at a given position.
list.remove(x)Remove the first item from the list whose value is x.
list.pop([i])Remove the item at the given position in the list, and return it.
list.index(x)Return the index in the list of the first item whose value is x.
list.count(x)Return the number of times x appears in the list.
list.sort()Sort the items of the list in place.
list.reverse()Reverse the elements of the list in place.

Here are some more examples of list methods.

Joining two lists:

[0, 1, 2, 3, 4, 10, 11, 12, 13, 14]

Accessing items from a list at specific positions:

first 0
last 14
first 3 [0, 1, 2]
last 3 [12, 13, 14]

Checking if an item is in a list:

True

Python is full of tricks for iterating and working with lists, for instance, list comprehensions:

[0, 1, 4, 9, 16]

Dictionaries

This is another basic, but extremely useful data structure. It maps keys to values, like a real dictionary maps words to their definitions. There are two main ways to create a dictionary: using curly braces {} or the dict() function.

{'name': 'Reuter West', 'capacity': 564, 'fuel': 'hard coal'}

Values can be accessed via their keys. Square brackets are used in Python for accessing values in many different contexts.

564

You can also test for the presence of items in a list:

False

Trying to access a key that does not exist will raise a KeyError. We can catch this error using a so-called try-except block. We try to access the key, and if it fails, we except the error and do something else instead.

KeyError encountered.

As a way to avoid this, you can use the get() method of dictionaries, which allows you to provide a default value if the key does not exist:

'OCGT'

New entries can be added to a dictionary by assigning a value to a new key:

{'name': 'Reuter West', 'capacity': 564, 'fuel': 'hard coal', 'technology': 'CHP'}

Finally, you can also iterate over the keys and values of a dictionary using a for loop:

name Reuter West
capacity 564
fuel hard coal
technology CHP

Functions

For longer and more complex tasks, it is important to organize your code into reuseable elements.

Cutting and pasting the same or similar lines of code is tedious and opens you up to errors.

Best practice is to follow the DRY principle: “don’t repeat yourself”.

In Python, you can use functions for this purpose.

Functions are a central part of advanced Python programming.

Functions take some inputs (“arguments”) and do something in response.

Usually functions return something, but they don’t have to.

A function without any arguments could look like this:

We can call it like other functions of different data types using round brackets. This returns the string “Hello”:

'Hello'

Whatever is returned by a function can be assigned to a variable or used directly:

'Hello'

A function with arguments could be used to greet a specific person. This could look like this:

So, if we want to greet “Bob”, we can call the function like this:

'Hi Gustav'

Functions can distinguish between different types of arguments, for instance, positional and keyword arguments. Positional arguments are assigned based on their order and compulsory, whereas keyword arguments are assigned based on their name (like a dictionary) and are optional (they can have default values). Here’s an example function that uses both types of arguments to greet a person in different languages:

'Guten Tag Gustav'

Pure and Impure Functions

Functions that do not modify their arguments or produce any other side-effects are called pure.

Functions that modify their arguments or cause other actions to occur are called impure.

The distinction is important because pure functions are more robust and predictable as they do not depend on previous / repeated code executions.

Below is an example for an impure function.

['Max', 'Martha']
['Max']

We can do something similar with a pure function, which works with copies of the arguments instead of modifying them directly.

['Max', 'Martha', 'Marie']
['Max', 'Martha']

In general, pure functions are safer and more reliable, since they do not lead to unexpected value changes.

Exercises

Here are some exercises to practice and reinforce what you have learned in this notebook. You can find the solutions in the solutions section of the course website.

Task 1: What is 5 to the power of 5 minus 5?

Task 2: Create variables for the efficiency of 45% and the input_energy of 1000 MWh. Compute and print the output_energy using these variables.

Task 3: Split the following string into a list by splitting on the space character:

Task 4: Create a list with the names of every planet in the solar system (in order).

  • Have Python tell you the name of the third planet.

  • Have Python tell you the total number of planets.

  • Have Python tell you whether “Pluto” is in the list of planets.

  • Iterate through your planets and print the planet name only if it has an “s” at the end.

Task 5: Create a dictionary that contains the main facts about the Reuter West power plant.

  • Have Python tell you the main fuel type used in the power plant.

  • Add the power plant’s approximate latitude and longitude to the dictionary.

Task 6: Write a function that converts units of energy from ‘ktoe’ to ‘GWh’

https://www.iea.org/data-and-statistics/data-tools/unit-converter

Task 7: Write a more general unit conversion function that converts between all units of energy listed under the link below. The function should take arguments: for the original value, the original unit and the target unit. Implement the function in a way that the default target unit is “Wh”. Verify that function by converting 200 ‘toe’ to ‘Wh’.

https://www.iea.org/data-and-statistics/data-tools/unit-converter