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.

Running Python

There are three main ways to run Python code.

  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)

Basics

Comments are anything that comes after the “#” symbol

a = 1  # assign integer 1 to variable a
b = "hello"  # assign string "hello" to variable b

We can print variables to see their values:

# how to we see our variables?
print(a)
print(b)
1
hello

All variables are objects. Every object has a type. To find out what type your variables are

print(type(a))
print(type(b))
<class 'int'>
<class 'str'>

Objects can have attributes and methods, which can be accessed via variable.method

# this returns the method itself
b.capitalize
<function str.capitalize()>
# this calls the method
b.capitalize()
'Hello'

Math

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

# addition / subtraction
1 + 1 - 5
-3
# multiplication
5 * 10
50
# division
1 / 2
0.5
# exponentiation
2**4
16
# rounding
round(9 / 10)
1

Comparisons

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

2 < 3
True
"energy" == "power"
False
2 != "2"
True
2 == 2.0
True

Booleans

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

True and True
True
True and False
False
True or True
True
(not True) or (not False)
True

Conditionals

Conditionals allow a program to make decisions. They dictate the flow of execution based on whether certain conditions are met.

x = 100
if x > 0:
    print("Positive Number")
elif x < 0:
    print("Negative Number")
else:
    print("Zero!")
Positive Number
if x > 0:
    print("Positive Number")
    if x >= 100:
        print("Huge number!")
Positive Number
Huge number!

Loops

Loops tell 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.

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.

count = 0
while count < 10:
    print(count)
    count += 1
0
1
2
3
4
5
6
7
8
9
for i in range(5):
    print(i)
0
1
2
3
4
for carrier in ["electricity", "hydrogen", "methane"]:
    print(carrier, len(carrier))
electricity 11
hydrogen 8
methane 7

Lists

list = ["electricity", "hydrogen", "methane"]

Finding out the length of a list:

len(list)
3

Joining two lists:

x = [1, 2, 3]
y = [9, 8, 7]
z = x + y
z
[1, 2, 3, 9, 8, 7]

Accessing items from a list:

z[0]
1
z[-1]
7
z[:4]
[1, 2, 3, 9]
z[-4:]
[3, 9, 8, 7]

Checking if item in list:

5 in z
False

Dictionaries

This is another useful data structure. It maps keys to values.

d = {
    "name": "Reuter West",
    "capacity": 564,
    "fuel": "hard coal",
}
# access a value
d["capacity"]
564
# test for the presence of a key
print("fuel" in d)
True
# add a new key
d["technology"] = "CHP"
d
{'name': 'Reuter West', 'capacity': 564, 'fuel': 'hard coal', 'technology': 'CHP'}
for k, v in d.items():
    print(k, v)
name Reuter West
capacity 564
fuel hard coal
technology CHP

Now we have the building blocks we need to do basic programming in Python.

Exercises

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

Notebook Cell
5**5
3125

Task 2: Create a list with the names of every planet in the solar system (in order). Have Python tell you how many planets there are in the list.

Notebook Cell
planets = [
    "Mercury",
    "Venus",
    "Earth",
    "Mars",
    "Jupyter",
    "Saturn",
    "Uranus",
    "Neptune",
]

Task 3: Create a dictionary that contains the main facts about the following power plant in Berlin. Use this dictionary to access the main fuel type.

https://powerplants.vattenfall.com/reuter-west/

Notebook Cell
rw = {
    "Country": "Germany",
    "Electricity Capacity": 564,
    "Heat Capacity": 878,
    "Technology": "Combined heat and power (CHP)",
    "Main Fuel": "Hard coal",
    "Vattenfall ownership share": "100%",
    "Status": "In Operation",
}
Notebook Cell
rw["Main Fuel"]
'Hard coal'