Getting started#

Learning goals

After finishing this chapter, you are expected to

  • be able to install and use Anaconda as your Python distribution

  • understand the role of the Python interpreter in programming

  • find and use the command line interface on your computer

  • perform basic operations using the Python interpreter

  • define variables in Python

  • work with floating point numbers, integers, string and boolean variables

  • write a Python script using Visual Studio Code

  • execute a Python script

What is Python?#

Python is a programming language that allows you to write software programs. By programming in Python you can tell the computer how to do things. Just like Python, there are many other programming languages out there. You might have heard about some of them, like C, C++, Java. Alternatively, it might be that you have heard of (or used) Matlab. In general, programming languages have a lot of similarities. They all allow you to work with data such as information provided by the user or stored in a file, and do something based on that input. They (almost) all have ways to visualize results. Of course, there are also differences. Languages differ in the way that your code is executed on the computer, in the syntax that you should use when writing code, in naming conventions, etc. We use Python here because it is a widely used language that is user-friendly and allows you to get a grasp of fundamental concepts in programming.

Python

Python is an interpreted, object-oriented, high-level programming language with dynamic semantics.

Python is a high-level language, which means that it is easy for humans to read and write Python. The fact that it is an interpreted language means that code does not have to be compiled before running: the interpreter will simply go over the lines in your code and execute them. This also means that code might run a bit slower than in a compiled language like C++. It is also important to realize that Python is object-oriented and that everything in Python is an object. We will explain later what this means.

How do I start?#

Python is a programming language that doesn’t natively come with a programming environment. There are many ways to install and use Python on your own computer. In this first session we will use two essential components to get you up and running with Python.

  • We will use Anaconda as the Python distribution and package manager.

  • We will use Visual Studio Code (VS Code) as the programming environment.

We’ll introduce all these tools step-by-step so that you get a good understanding what everything is and that you’ll be comfortable using Python.

Warning

Whenever we provide instructions on how to install software, please closely follow the order indicated.

Installing Anaconda#

The first step is to download Anaconda, a widely used Python distribution. Anaconda contains a lot of very useful functionality including

  • The newest versions of Python and many useful packages

  • A powerful package manager

  • A clean way to organize environments

  • A terminal

Anaconda is free. To download it, go to the Anaconda website and select Download. This will download a file of around 500MB-1GB. Use the file to install Anaconda. Follow the instructions and just install it as a regular software package. You can follow the detailed instructions here. It’s important that you don’t add Anaconda to your PATH variable. Not adding Anaconda to the PATH is the default setting during installation, so you should be fine.

Anaconda installer

Anaconda installs some additional tools on your machine, including Anaconda Navigator. This is a tool that conveniently combines several important elements of your Python distribution: environments, packages. For now, we will not discuss environments, but we will do so extensively later in the course.

Before you continue

Before you continue, please make sure that you have successfully installed Anaconda.

Using the command line#

One useful skill to have when working with computers is to be able to effectively use the command line. The command line is a text interface to your computer. You can use it to - for example - navigate your computer, create and delete files, and inspect which processes are running. The command line also offers an alternative to the graphics user interface (GUI) that you are used to, and you will find that many software tools can be used either via the command line or via a GUI.

Terminal? Shell?

The words ‘terminal’, ‘command line’, ‘shell’, ‘CLI’, ‘console’, and ‘prompt’ are often used for the same thing: a text-based interface to your computer.

To start, open a terminal window. We will here use Anaconda Prompt as terminal. Anaconda Prompt was installed automatically on your computer when you installed Anaconda before. Opening Anaconda Prompt gives you a command line interface (CLI) like below.

terminal

There are many things that you can do with the command line, but one essential skill is to be able to navigate your filesystem. The file system on your computer is organized like a tree, with directories/folders and subdirectories. There is one root directory, which contains either files or folders. Each of those folders can also contain files and folders, etc. The figure below shows an example of such a file system.

filesystem

The table below provides a couple of common commands that you can use to navigate your file system. For example, assuming that the terminal starts in the root directory Tom.

Command

Example

ls (short for ‘list’), dir on Windows

ls / dir

List contents (files and subdirectories) of current directory

ls .\Thesis / dir .\Thesis

List contents in subdirectory Thesis

cd (change directory)

cd ..

Go one level up in directory structure

cd .\Thesis\

Go to directory Thesis which is a subdirectory of the current directory

cd \Tom\Thesis\

Go directly to a directory by using it’s full path on the machine

Exercise 1.1

  1. Create a Microsoft Word file called AnswersTutorial1.docx and save it somewhere on your computer in a folder of your choosing. In this week’s tutorial, you will use this file to store all your answers.

  2. Start a terminal window.

  3. Use the commands above to navigate to the folder where you stored your Exercise1.docx file. Display the contents of that folder. Make a screenshot of the terminal and paste it to your AnswersTutorial1.docx file.

The Python interpreter#

Once you have installed Anaconda, you also have installed the Python interpreter. You can use this interpreter as a command line tool that allows you to program in interactive mode. To start the Python interpreter, type python in a terminal and hit Enter. The output should look something like this.

Python 3.11.7 | packaged by conda-forge | (main, Dec 23 2023, 14:27:59) [MSC v.1937 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

There is some useful information in this output. In particular, on the left you see the Python version that you’re currently using in combination with Anaconda. Like each software tools, there are multiple versions of Python. Versions 3.11 and 3.12 are the newest versions of Python (as of December 2023) and are most likely to be supported in the long run.

Arithmetic operators#

The >>> in your terminal indicates that you’re in interactive mode and Python is ‘listening’. Anything that you will type here will be parsed, it will be interpreted, and an answer will be returned to you. Let’s give it a try! You can use the interpreter as a calculator and perform some simple arithmetic operations.

Exercise 1.2

Replicate the output below using the Python interpreter.

>>> 1+4
5
>>> 8-6
2
>>> 6*7
42
>>> 8/4
2.0
>>> 5--6
11

Remember to press Enter after each line to send your request to the interpreter. Paste the contents of your terminal window into your Word document.

Two things in the previous outputs are interesting to note. First, Python automatically interprets the minus sign in front of 6 and gives the correct answer. This is similar to what you would write yourself in mathematical notation. In fact, you’ll see that many expressions are quite intuitive. Second, if we divide 8 by 4, we don’t get 2, but we get 2.0. This has to do with the ‘type’ of the number. Like most programming languages, Python differentiates between integer numbers (such as 1, 2, 3, 4, …, 100000, …) and floating point numbers (such as -45.7, 0.00001, 12.9772). By default, if we divide two numbers using /, Python returns a floating point number to preserve precision.

We can use the interpreter as a calculator. For many standard mathematical operators there is an equivalent in Python. The table below gives an overview of some mathematical operations and how to implement them in Python.

Mathematical notation

Python

\(a+b\)

a+b

\(a-b\)

a-b

\(ab\)

a*b

\(\frac{a}{b}\)

a/b

\(\lfloor\frac{a}{b}\rfloor\)

a//b

\(a^b\)

a**b

If you type an expression in the interpreter, it will return the answer to you. For example 5--6 will result in the output 11. If you want to reuse the output of a previous expression (in this case 11), you can use the _ symbol. For example, to compute \(4 * 5 + 6\), we can do

>>> 4*5
20
>>> _+6
26

Of course, you can also directly make more complex statements. The use of ( and ) can help you properly structure your inputs. The location of the parentheses affects the output of the interpreter, e.g.,

>>> 4*5+6
26
>>> 4*(5+6)
44

Exercise 1.3

Evaluate the following expressions by hand and use Python to check the answers.

  1. 2/2*3

  2. 8*63-9

  3. 8*(63-9)

  4. 7-5*49

  5. 6-2/5+7**2-1

  6. 10/25-3+2*4

  7. 3**2/4

  8. 3**2**3

  9. (3**2)**3

Paste the contents of your terminal window into your Word document.

Modulo operator#

One operator that you might not yet be familiar with is the modulo operator %. The modulo operator returns the remainder or signed remainder of a division, after one number is divided by another. One clear example is time: we can express the time of day using 24 hours, but also using 12 hours. To use only 12 hours, we use a % 12 to take the modulo of any hour after noon

>>> print(17 % 12)
5

Exercise 1.4

First, evaluate the following expressions by hand. Then use Python to check your answers. If your answers don’t match, try to figure out why not.

  1. 7 % 4

  2. 34 % 3

  3. (6**2) % 3

  4. (7%3) // 1

  5. -7 % -4

  6. 2**(5%3)

  7. (7//2)%2

Paste the contents of your terminal window into your Word document.

Variables#

By now, you can use Python as a basic calculator, but this is not yet real programming. You haven’t really stored values properly yet, only in the last output _, so it’s hard to perform more complex computations. One key element of programming is the use of named variables and the ability to store values in those variables.

Variables

A variable is a value that can change, depending on conditions or on information passed to the program.

Within the Python interpreter, you can define a variable and assign a value to it. To do so, try something like

>>> a = 4 
>>>

You may notice that now, the interpreter does not return an output value. This is so because it has stored the value 4 in variable a and simply storing a value in a variable does not result in an output. However, we can now simply ask the interpreter for the value of a and it returns 4.

>>> a
4

As long as the Python interpreter is running, it will remember what the value of variable a is. Likewise, we can assign values to other variables.

>>> b = 3
>>> c = 7

Then, instead of using values to perform computations, we can use variables instead. For example, we can perform some basic arithmetic with these variables as follows:

>>> (a*b)-c
5

Moreover, we can assign the output of such arithmetic to a new variable.

>>> d = (a*b)-c
>>>

Again, the Python interpreter does not return anything, as we’re just assigning a value to d. At any moment, you can list all current variables by typing vars().

>>> vars()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'a': 4, 'b': 3, 'c': 7, 'd': 5}

You can always replace the value of a variable, so you can reuse variable names as often as you want.

>>> d = c**b+a
>>> d
347

Of course, if you assign a new value to a variable, the old value is lost.

Exercise 1.5

Consider the code below. The programmer wanted to swap the values in the variable a and b. However, it does not work in the way the programmer expected.

  1. Explain why the program fails to swap the values.

  2. Fix the program so that the variables are swapped. Verify your program in Python.

a = 19
b = 7
a = b
b = a

Case sensitivity

Each variable has a name. The case of your variable name matters. For example, if you first assign a value to a variable that you call a and then want to reuse the variable of that variable but (accidentally) type A, Python will throw an error:

>>> a=5
>>> b=A*4
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'A' is not defined

This could lead to unexpected behavior, in particular when you actually have two variables defined, one with uppercase and one with lowercase formatting. To prevent such problems, it is good to name your variables according to some standards. We’ll introduce these later.

Assigning values to multiple variables#

For clarity, it is often better to use one line of code to assign a value to one variable, but sometimes you may want to assign values to two variables at the same time. In that case, you can simply separate the variables and values by a comma, as in

a, b, c = 1, 2, 3

It is of course important that the number of values matches the numbers of variables. If that is not the case, Python will throw an error.

a, b, c = 1, 2
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/var/folders/07/x0gf6dj176dfjvrn357t5p6h0000gn/T/ipykernel_34265/1121104675.py in <module>
----> 1 a, b, c = 1, 2

ValueError: not enough values to unpack (expected 3, got 2)

You can also assign the same value to multiple variables. For example, to create three variables that all have the value 2, you can simply write

a = b = c = 2

Exercise 1.6

Special numbers like \(\pi\) and Euler’s number \(e\) are not automatically defined in Python. Define these two numbers as variables and use them to compute the volume of a sphere with radius \(e\). Store the result in a new variable called v.

Paste the contents of your terminal window into your Word document.

Data types#

Each variable in Python has a type that defines which kind of data it represents. There are four important types in Python that you will also see in almost any programming language:

  1. Integers, or whole numbers, such as 1, 2, 1000, 4000. Integers can be signed or unsigned. Signed integers can take on negative or positive values, unsigned integers only positive values.

  2. Floating point numbers such as -1892.3, 0.000045, 1.3040, 9828.322.

  3. Strings, i.e., sequences of characters. For example, ‘Technical medicine’ is a string. The length of strings can vary, e.g., ‘a’ is also a string.

  4. Booleans, which are variables that can take on just two values: True or False.

Some programming languages require you to explicitly specify the type of each variable. Instead, Python tries to automatically infer the type of a variable for you and does a good job in most cases. However, it’s always good to be aware of the type of your variables.To find out what the type is of a variable, you can use type(), i.e.,

>>> a = 4
>>> type(a)
<class 'int'>
>>> b = 3.1
>>> type(b)
<class 'float'>
>>> c = 'Technical medicine'
>>> type(c)
<class 'str'>
>>> d = True
>>> type(d)
<class 'bool'>

Not all data types are compatible. While you can add integers and floating point numbers, and even booleans and numbers, adding floating point and strings will throw an error.

4 + 'Hello world'
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/var/folders/07/x0gf6dj176dfjvrn357t5p6h0000gn/T/ipykernel_34265/1642992856.py in <module>
----> 1 4 + 'Hello world'

TypeError: unsupported operand type(s) for +: 'int' and 'str'

Exercise 1.7

Define two variables. One should have the value ‘Technical ‘ and the other ‘Medicine’. What is the type of these variables? Try to add these two variables in the Python interpreter. Which result do you get? Can you explain what happened?

Type casting#

In many cases, you can convert one variable type into another type. For example, if we have a variable b=3.0 it has type float. We can cast this variable into a type int variable by typing b = int(b). Similarly, a string can in many - but not all - cases be cast into a float or int or vice versa.

>>> b='3.4'
>>> float(b)
3.4
>>> c=3.4
>>> int(c)    # Casting an int to a float is the same as a 'floor' operator
3
>>> str(c)
'3.4' 

Note that this does not always work. For example, a string which is not a number cannot be cast into an int or float.

>>> a = 'Hello'
>>> int(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'Hello'
>>> float(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: 'Hello'
>>> bool(a)
True

Comparison operators#

Some operations by default take inputs of one type and return outputs of another type. A good example of this are comparison operators, which check whether two inputs are the same or different. The comparison operators in Python are as follows.

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

The return type of these operators is boolean. For example, evaluating if one integer is smaller or larger than another integer will return a boolean: the statement is either True or False.

>>> a < 1
False
>>> a > b
False
>>> a <= b
True
>>> a >= b
False

Special variants of this are the not, or and and operators. These return either True or False depending on the input. As you might expect, by writing not before a statement, we get the opposite value.

>>> a = 4
>>> a < 1
False
>>> not a < 1
True

With or and and we can combine two statements. For example

>>> a = 4
>>> b = 3
>>> a > 2 and b > 1
True
>>> a > 2 or b > 4
True

And of course, and and or can also be combined with not.

>>> not a > 2 or b > 1
True

Here, parentheses () matter. For example, consider why following output is correct.

>>> not (a > 2 or b > 1)
False

Alternatively, you can use not as a function (more on functions later), where you give the expression as an argument. For example, these statements give the same result

>>> a = False
>>> not a 
True
>>> not(a)
True

Exercise 1.8

For each of the following nonsense programs, first write down the expected output yourself. Then verify in the Python interpreter. If your answers don’t match those of Python, consider what might have gone wrong.

The print function lets Python print the value between parentheses to the terminal.

a = True
b = False
print(not(a))
print(not(b))
a = False
b = False
x = not(a)
y = not(b)
print(a or b)
print(x or y)
print(a or x)
print(x or b)
a = False
b = False
x = not(a)
y = not(b)
print(a and b)
print(a and x)
print(y and b)
print(x and y)
a = 4
b = -1
c = not(a > b)
d = not(a < b) or a
print(c and d)
print(bool(a) or d)
print(d or int(b))

Assignment operators#

If we have a variable that we want to modify by adding or multiplying with some other number, we can explicitly write the addition, e.g., a = a + 5, but we can also use the shorthand version a += 5. This adds 5 to the value of a. Similarly, you can write a *= 5, etc. There is an assignment operator for each arithmetic operator that you saw before. The assignment operators are as follows.

Operator

Example

Same As

+=

x += 3

x = x + 3

-=

x -= 3

x = x - 3

*=

x *= 3

x = x * 3

/=

x /= 3

x = x / 3

%=

x %= 3

x = x % 3

//=

x //= 3

x = x // 3

**=

x **= 3

x = x ** 3

Exercise 1.9

Use assignment operators to change - in one statement - the value of variable a=4 into the following. You may only use each assignment operator once.

  1. 42

  2. 3.0

  3. 1024

  4. 1

  5. 2

  6. 4627

  7. -172

Paste the contents of your terminal window into your Word document.

Complex numbers#

A convenient feature of Python is that it comes with built-in support for complex numbers. You can easily define a complex number as

>>> z = 3 + 2j

You can get the real part of the number by typing z.real and the imaginary part by typing z.imag.

Literals

As you notice, Python uses the literal \(j\) instead of \(i\) in complex numbers. This is an engineering convention.

Exercise 1.10

  1. Use the Python interpreter to find the type of the variable z.

  2. Choose two complex numbers. For example \(-3 + 2j\) and \(5-7j\), but you can also choose other numbers. Add, subtract, multiply and divide these numbers in Python.

Paste the contents of your terminal window into your Word document.

Leaving the Python interpreter

To leave the Python interpreter and go back to your terminal window, type

>>> exit()

Scripts#

So far, you have used the Python interpreter to interact with Python. As you can imagine, once you want to write and run a piece of code that contains many steps or lines, it becomes inconvenient to use the interpreter: you would have to write each line of code each time you’re trying to run a program. Instead, you can write Python scripts that can be passed to the interpreter, which will run everything line-by-line. Python scripts are files that can be run and are supposed to do something each time you run them. A Python file ends in .py, and can be simply a set of statements. For example, the contents of a Python file can be as simple as

a = 4
b = 8
c = a**b         # Compute a to the power b
print(c)

You can see that these are just four lines of code. In the third line, we have also added a comment. This is a piece of human-readable text that is not part of the code. It will not be run by the Python interpreter. We use the character # to indicate that this is a comment. Documenting your code properly with comments is a very valuable way to make sure that you (or someone else) will still understand the code when you look at it later. We’ll go over some common practices for code documentation later.

Running a Python script is straightforward. First, you have to actually create the script. To do this, create a directory/folder on your computer where you intend to store the code of this course. This can be the same directory where you stored the Word file you created earlier. Open Notepad (Kladblok) or an equivalent text editor and paste the lines of code above. Then go to File -> Save as, under Save as type select All files and save the file as test.py in the directory you just created. Then, open a command line window and navigate to the directory where you have stored test.py. To run the script, type python test.py and press Enter.

Exercise 1.11

What is the output of this script? Add a screenshot to your Word file.

And that’s it: you’ve written and run your first Python script! Now we can really start programming. There is no limit to how long a script can be and - as you’ll see - you can do much more in a script than just processing lines in a fixed order.

Visual Studio Code#

For simple programming, Notepad will get you quite far as a script editor. However, most programmers use an ‘integrated development environment’ (IDE) that provides additional tools during programming to increase productivity and help you write clear and reusable code. There are many different IDEs on the market, some focusing on one programming language, others on a range of programming languages. Some are very expensive and intended for professional use, some are free. Some are complex, some are easier to use. In this course, we will use Visual Studio Code, commonly referred to as VS Code. VS Code is free, flexible, and widely considered to be a good entry point for new programmers. In the remainder of the course, we assume that you are using VS Code.

To install VS Code, take the following steps:

  1. Go to the Visual Studio Code website and download the correct version for your computer. If you’re on a Windows laptop, this is likely going to be the User Installer x64 version.

  2. Run the installer to install Visual Studio Code.

  3. Open Visual Studio Code and go to ‘Extensions’ (Ctrl + Shift + X on Windows).

  4. Install the Python extension. Warning There are multiple Python extensions available. You should download the most popular one by Microsoft, which has been downloaded over a 100m times.

If you have properly installed Anaconda as described in the previous chapter, you should now be able to use Python within the VS Code IDE. You can find more information on the combination of Anaconda and VS Code on the Anaconda website.

Note that we suggest to use VS Code, but that there are other (free) IDEs that you can also use, like Spyder and PyCharm. The latter is a professional, expensive IDE that provides free licenses to students. Go to the JetBrains website and register as a student. Make sure to use your University of Twente email account. Once you have received confirmation from JetBrains, download the latest version of PyCharm from the PyCharm website. Use the license provides to you by JetBrains. In the end, it doesn’t really matter which IDE you use, the Python code that you use is not affected by the IDE. The IDE is just there to help you write code.

Writing scripts in VS Code#

With VS Code open, go to the ‘Explorer’ (Ctrl + Shift + E on Windows). Go to File –> Open Folder and select the folder you just created and in which you stored test.py. If all is well, you should see the folder appear in ‘Explorer’, including the test.py file. You can double click on the test.py file and it will open in the VS Code editor. You will see that colors are used to highlight individual words and characters in the code. This is called syntax highlighting and is a useful tool to make your code readable and easily spot errors. You can change the colors and the general look-and-feel of VS Code by picking a different theme. For this, go to File –> Preferences –> Theme –> Color Theme. Note that this is just a visualization and will not change anything to your code or what your code does. The editor in which you now see your code is basically a text editor with some nice additional functionality to make your life as a programmer easier.

Running scripts in VS Code#

To run your script in VS Code, first select an interpreter. On Windows, on the bottom right, click on Select Interpreter. This lets you pick the Python interpreter that you have previously installed with Anaconda. Then, if you select Run –> Run Without Debugging (or CTRL + F5) from the menu, VS Code will start a terminal, call the Python interpreter with your script, and output the results in a terminal window.

Exercise 1.12

Write a Python script that prints the first eight numbers in the Fibonacci sequence. Use variables in your script. You are only allowed to use a maximum of two digits in your code. Run the script and verify the output.

Interactive scripts#

A Python script will run ‘as is’, i.e., its output is entirely defined by what we put in the script. We can also make the script more interactive by using the input() function in Python. This asks the user for an input and stores it in a variable.

>>> name = input("Please enter your name: ")
Please enter your name: Adam
>>> name
'Adam'

You can use the input() function in a script to let the script compute something else depending on the users input. Keep in mind that input() always returns a string. Hence, if you want to ask the user for an int or a float instead, you will have to cast your variables.

Exercise 1.13

Write Python scripts for at least two of the following tasks. Use the input() and print() functions.

  1. A script that asks the user for the radius of a sphere and prints the volume of the sphere.

  2. A script that asks the user for two numbers and prints whether the first number is larger than the second number.

  3. A script that asks the user for numbers \(a\), \(b\) and \(c\) and prints whether \(a\mod b > c\).

  4. A script that asks the user for the height, width and depth of a box and returns it’s volume and surface area.