3.2  Basics

This tutorial covers the basic building blocks of Python: variables, data types, operators and flow control structures.

Variables

A variable is simply a name you give to a storage location in memory, allowing you to hold and manipulate data. Use the single equals sign = to assign a value. When naming variables, use descriptive names in “snake_case”, e.g. vehicle_mass, applied_force, etc. Names cannot start with a number, contain dashes or spaces. For example 2var = 3.5, variable-1 = 10 and test variable = 20 will all produce error messages. Certain names are also reserved as keywords for other functions, and can therefore not be used. One such example that you might be tempted to use is lambda.

# Input data (this is a "comment")
age = 40                              # [years] - always specify units
length = 185.3                        # [cm] - always specify units
first_name = "Johan"                  # single quotes 'Johan' works as well
is_awesome = True                     # could be argued
var_one, var_two = 1.0, 2.5           # several variable assignments
var_three = var_four = 3.5            # several varables assigned same value

Note that variables names in Python are case sensitive, meaning that a does not refer to the same variable as A, and vehicle_Mass does not refer to the same variable as vehicle_mass etc.

Data types

These are some examples of fundamental data types, i.e. categories for values:

Type Name Description Examples
int Integer Whole numbers (positive, negative or zero). a = 10, b = -5
float Floating Numbers with a decimal point. c = 3.14, d = 99.9, 10e-20 (a “numerical” zero)
complex Complex Complex numbers. f = 1j, g = 10+2j
str String A sequence of characters (text), enclosed in quotes h = "Hello", i = 'Python'
bool Boolean Represents truth values, either True or False j = True, k = False
NoneType NoneType Represents the abscence of a value l = None

To find the data type of a specific variable, use the type() function. For example, type(first_name) will return ‘str’, indicating that the variable first_name is a String. A value’s data type dictates what you can do with it, for example you can perform math on an int (like 10 / 2), but you can’t on a str. The data type also determines how a value is stored in memory and its internal structure. You can force the data type of a variable using casting, for example variable_three = str("1") would lead to type(variable_three) returning str, indicating that the variable is now a String.

Operators

Python provides a wide range of operators (special symbols and keywords) that allow you to perform various operations, such as arithmetic calculations, comparison between values, combining boolean expressions with logical operators, and checking for inclusion using membership operators.

Arithmetic

Operator Name Comment Example
+ Addition Adds numbers x + y
- Subtraction Subtracts numbers x - y
* Multiplication Multiplies numbers x * y
/ Division Returns a float x / y
// Floor division Rounds down, returns an integer x // y
** Exponentiation Takes some getting used to… x ** y
% Modulus Returns the remainder of x / y x % y

Comparison

Operator Name Example
== Equal x == y
!= Not equal x != y
> Greater than x > y
< Less than x < y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y

Logical

Operator Description Example
and Returns True if both statements are true (2 < x < 5) and (x < 10)
or Returns True if one of the statements is true (x < 5) or (x < 4)
not Reverse the result, returns False if the result is true not((x < 5) and (x < 10))

Membership

Operator Description Example
in Returns True if x is present in y 3 in [1, 2, 3]
not in Returns True if x is not present in y 9 not in [1, 2, 3]

Flow control

Flow control structures determine the order in which your code executes. They allow your program to make decisions and repeat actions.

Conditional statements

Conditional statements execute different blocks of code based on whether a condition is True or False.

Keyword Purpose
if Executes code if the condition is True.
elif (Else if) Checks a new condition if the previous if/ elif conditions were False.
else Executes code if all preceding conditions were False

Note that Python uses indentation (usually four spaces) to define code blocks. A code block is a group of statements, that is initialized with a colon (:).

score = 85

if score >= 90: # check if score is greater than or equal to 90
    print("Grade 5")
elif score >= 75: # if not, then check if score is greater than or equal to 75
    print("Grade 4")
elif score >= 60: # if not, then check if score is greater than or equal to 60
    print("Grade 3")
else: # for all other cases, the grade will be U
    print("Grade U")
    print("See you on the re-exam!")
Grade 4

In the above example, there are four code blocks. The first three code blocks contain one statement, while the last code block contains two statements.

Loops

Loops are used to execute a block of code multiple times.

The while loop executes a block of code as long as its specified condition remains True.

counter = 0

while counter < 5:
    print(counter)
    counter = counter + 1 # can also be written more compactly as counter += 1
0
1
2
3
4

The for loop is used for iterating over a sequence (like a list, string or range of numbers). In the following example, the range() function is used to create three numbers, starting with zero.

for i in range(3): 
    print(i)
0
1
2

The range() function is commonly used to define for-loops. It can be used in three main ways: 1. range(stop): A single stop parameter is specified, where the returned numbers will start with a zero (just like in the example above). 2. range(start, stop): The start parameter can be set to something other than zero, followed by the stop parameter. 3. range(start, stop, step): The start and stop parameters are specified, followed by the step-parameter which can be both positive or negative.

for i in range(7, 10):
    print(i)
7
8
9

Note that the total amount of numbers returned from range(start, stop) is stop - start.

for i in range(10, 0, -2):
    print(i)
10
8
6
4
2

Multiple “nested” for-loops can be used to iterate over multiple variables.

for x in range(2): # x goes from 0 to 2
    for y in range(5): # y goes from 0 to 5
        print(x, y)
0 0
0 1
0 2
0 3
0 4
1 0
1 1
1 2
1 3
1 4

Note the order. The “inner loop” over y runs from start to finish for each separate x of the “outer loop”.