Running Python¶
There are three main ways to run Python code.
By running a Python file, e.g.
python myscript.pyThrough an interactive console (Python interpreter or iPython shell)
In an interactive notebook (e.g. Jupyter,
.ipynbfiles)
Basics¶
Comments are anything that comes after the “#” symbol
a = 1 # assign integer 1 to variable a
b = "hello" # assign string "hello" to variable bWe 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 * 1050# division
1 / 20.5# exponentiation
2**416# rounding
round(9 / 10)1Comparisons¶
We can compare objects using comparison operators, and we’ll get back a boolean (i.e. True/False) result:
2 < 3True"energy" == "power"False2 != "2"True2 == 2.0TrueBooleans¶
We also have so-called “boolean operators” or “logical operators” which also evaluate to either True or False:
True and TrueTrueTrue and FalseFalseTrue or TrueTrue(not True) or (not False)TrueConditionals¶
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 += 10
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)3Joining 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]1z[-1]7z[:4][1, 2, 3, 9]z[-4:][3, 9, 8, 7]Checking if item in list:
5 in zFalseDictionaries¶
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**53125Task 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.
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'