Getting started#

Learning goals

After finishing this chapter, you are expected to

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

  • open and run a Jupyter Notebook

  • perform basic operations in Python

  • define variables in Python

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

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, many other programming languages exist. 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 three 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 will use Jupyter Notebooks as documents in which to write code and visualize results.

We’ll introduce all these tools step-by-step so that you get a good understanding what everything is and so 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, fill in a valid e-mail address, and download Anaconda using the link that you receive in your mailbox. 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. Please do add Anaconda to your path variable.

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.

Installing 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.

Using Notebooks#

In VS Code, we can edit all kinds of documents. Python is typically written in .py. Here, we will use a slightly different file that is easier to work/learn with. A Jupyter notebook is a file that can contain code and text. In fact, you’re looking at a notebook right now! A notebook consists of cells and each cell can be run by a Python kernel. This Python kernel is like a Python interpreter that is continuously running in the background and keeping track of your variables.

In order to use notebooks in VS Code, you first need to install the Jupyter extension, just like you did earlier for the Python extension. Go to the extensions window, search for ‘Jupyter’ and select the top option, as below.

install

A notebook file should always end in an .ipynb extension. If all is well, when you create a file (for example my_notebook.ipynb) and open it in VS Code, you should get the notebook editor view. This view is a bit different from the normal Python script editing view. The file already contains one cell that you can start editing. However, before you start editing, it’s good to select a Python kernel. For this, click on Select Kernel in the top right of the screen. This takes you to your list of Python Environments, where you should select your Anaconda Python interpreter. In the example below, the interpreter base was selected.

editor

Cells#

There are two main types of cells in notebooks

  1. Code cells. These are cells that can be run and interpreted by Python

  2. Markdown cells. These are cells that contain text in the Markdown style.

You can use as many cells as you want in a notebook, but each cell can only have one of these two types. Markdown cells can be used to write comments, explanations, other documentation in between your blocks of code, or you can use them to add headers to your blocks of code. Markdown is a markup language like HTML that provides options to write text bold, italic, use \(\LaTeX\), add headers, etc. We are not going to teach you all markdown commands here, but you can find an overview of the most commonly used Markdown statements here. Markdown can be very useful when building documents.

This manual

In fact, this entire manual is written in Markdown. You can download each chapter as an *.ipynb file and run it as a notebook.

In VS Code, 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 cells#

Once you have a notebook opened in VS Code, you can run its individual cells by pressing Shift + Enter. VS Code will ask you to select a kernel, a Python instance that will run your code. Choose the one that has ‘Anaconda’ or ‘conda’ in its name. The Jupyter kernel will then execute the contents of the cell, and if there is any output, that output will be shown directly below the cell.

Making exercises

For the exercises in this chapter, we provide a template notebook, a .ipynb file that you can directly open in VS Code and that you can use to fill in your answers. It contains all the exercises that you see in the rest of the chapter. You can download this notebook from Canvas, chapter1_notebook.ipynb.

Arithmetic operators#

We’re going to use Jupyter notebooks to set your first steps in programming. We will use Python as a calculator and perform some simple arithmetic operations.

Exercise 1.1

Compute the following arithmetic operations in your notebook.

1+4
8-6
6*7
8/4
5--6

Put one of these expressions in a cell, and run the cell after you put in the code. If all is well, you should see the output appear below the cell.

Opdracht 1.1

Voer de onderstaande berekeningen uit in Python. Tik bijvoorbeeld 1+4 en druk op Shift+Enter om het resultaat te krijgen.

1+4
8-6
6*7
8/4
5--6

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 Python 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

\(a\times b\)

a*b

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

a/b

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

a//b

\(a^b\)

a**b

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 should give you 26, but 4*(5+6) will give you 44.

Exercise 1.2

In this exercise, you will try out these arithmetic operators. For each of the expressions below, first compute the answer by hand. You may use a calculator. Then use Python to check the answers.

  1. \(\frac{2}{2\times 3}\)

  2. \(8 \times 63 - 9\)

  3. \(8 \times (63 - 9)\)

  4. \(\frac{3^2}{4}\)

  5. \(\frac{10}{25}-3+2\times 4\)

  6. \((3^2)^3\)

If your answers don’t match, try to figure out why not.

Opdracht 1.2

In deze opdracht probeer je zelf deze arithmetic operators uit. Reken onderstaande uitdrukkingen eerst met de hand uit. Je mag een rekenmachine gebruiken. Controleer vervolgens of je antwoord klopt door het in Python te berekenen.

  1. \(\frac{2}{2\times 3}\)

  2. \(8 \times 63 - 9\)

  3. \(8 \times (63 - 9)\)

  4. \(\frac{3^2}{4}\)

  5. \(\frac{10}{25}-3+2\times 4\)

  6. \((3^2)^3\)

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, for example, int(17 % 12) will give you 5.

Exercise 1.3

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

Opdracht 1.3

Probeer of je zonder Python kunt bepalen wat de oplossing is van onderstaande uitdrukkingen. Gebruik vervolgens Python om te controleren of je antwoord klopt.

  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

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, 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.

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

a=4

You may notice that if you put this in a cell, running the cell 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 for the value of a and Python should return 4. Instead, if we ask for the value of a, we will get the following answer:

a
4

As long as your notebook kernel 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__': 'Automatically created module for IPython interactive environment',
 '__package__': None,
 '__loader__': None,
 '__spec__': None,
 '__builtin__': <module 'builtins' (built-in)>,
 '__builtins__': <module 'builtins' (built-in)>,
 '_ih': ['', 'a=4', 'a', 'b = 3\nc = 7', '(a*b)-c', 'd = (a*b)-c', 'vars()'],
 '_oh': {2: 4, 4: 5},
 '_dh': ['/Users/jmwolterink/Library/CloudStorage/OneDrive-UniversityofTwente/Teaching/TM/M3/2024/intro-programming/notebooks/01_GettingStarted'],
 'In': ['', 'a=4', 'a', 'b = 3\nc = 7', '(a*b)-c', 'd = (a*b)-c', 'vars()'],
 'Out': {2: 4, 4: 5},
 'get_ipython': <bound method InteractiveShell.get_ipython of <ipykernel.zmqshell.ZMQInteractiveShell object at 0x7fbbb06243d0>>,
 'exit': <IPython.core.autocall.ZMQExitAutocall at 0x7fbbb0624f90>,
 'quit': <IPython.core.autocall.ZMQExitAutocall at 0x7fbbb0624f90>,
 '_': 5,
 '__': 4,
 '___': '',
 '_i': 'd = (a*b)-c',
 '_ii': '(a*b)-c',
 '_iii': 'b = 3\nc = 7',
 '_i1': 'a=4',
 'a': 4,
 '_i2': 'a',
 '_2': 4,
 '_i3': 'b = 3\nc = 7',
 'b': 3,
 'c': 7,
 '_i4': '(a*b)-c',
 '_4': 5,
 '_i5': 'd = (a*b)-c',
 'd': 5,
 '_i6': 'vars()'}

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.

Case sensitivity

Each variable has a name. The case of your variable name (whether you’re using a capital letter or not) 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_34768/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.4

Consider the code below. We want to swap the values in the variable a and b. However, the code does not work in the way that we 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

Opdracht 1.4

Bekijk de code hieronder. De programmeur wilde de waarden van a en b omwisselen, maar dat lukt niet volgens deze code.

  1. Leg uit waarom het programma niet werkt.

  2. Pas de code aan zodat de waarde van de variabelen wel goed wordt omgewisseld.

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

Exercise 1.5

Mathematical constants 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.

A small reminder: You can compute the volume of a sphere as \(v = \frac{4}{3} \pi r^3\), where \(r\) is the sphere’s radius.

Opdracht 1.5

Wiskundige constanten zoals \(\pi\) and Euler’s getal \(e\) zijn niet automatisch gedefiniëerd in Python. Definieer deze twee constanten en gebruik ze om het volume van een bol met radius \(e\) te berekenen. Sla het resultaat op in een nieuwe variable die je v noemt.

Een kleine reminder: Het volume van een bol bereken je als \(v = \frac{4}{3} \pi r^3\), waarbij \(r\) de radius van de bol is.

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 automatically infers 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)
int
b = 3.1
type(b)
float
c = 'Technical Medicine'
type(c)
str
d = True
type(d)
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_34768/1642992856.py in <module>
----> 1 4 + 'Hello world'

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

Exercise 1.6

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 Python using a + operator. What is the result you get? Can you explain what happened?

Opdracht 1.6

Definieer twee variabelen. De ene variabele heeft als waarde ‘Technische’ en de andere variable als waarde ‘Geneeskunde’. Wat is het type van deze variabelen? Tel de twee variabelen bij elkaar op met een +. Wat is het resultaat dat je krijgt? Kun je uitleggen wat hier gebeurt?

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

Exercise 1.7

For each of the following nonsense programs, first write down the expected output yourself. Then verify in Python. 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))

Opdracht 1.7

Bekijk de vier programma’s hieronder. De print functie heb je nog niet eerder gezien, maar die print de waarde van een expressie tussen haakjes naar de terminal. Bijvoorbeeld: print(4) zal 4 schrijven naar de terminal, en als er een variabele a is met waarde 5 dan zal print(a) in de terminal 5 schrijven.

Schrijf voor elk programma telkens eerst op wat je zelf denkt dat het programma zal schrijven, en controleer vervolgens in Python of je antwoord klopt. Ga na wat er mis kan zijn gegaan als je antwoord niet klopt.

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

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.

Comments#

In Python code blocks, we can include comments. 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 ita = 4 b = 8 c = a**b # Compute a to the power b print(c) later. We’ll go over some common practices for code documentation later. See for example the third line in the code below.

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

Exercise 1.8

Take a look at this Wikipedia page on the Fibonacci sequence. As you can see, this is a famous sequence of numbers, where each number depends on the two preceding numbers.

1 --> 1 --> 2 --> 3 --> 5 --> 8 --> 13 --> 21 --> 34 --> etc.

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 two digits in your code, like this:

a = 1
b = 1 

and you can use the print function that we saw before. Run your code and verify the output.

Opdracht 1.8

Bekijk deze Wikipedia-pagina over de Fibonaccireeks. Dit is een beroemde reeks getallen, waarbij elk getal de som is van de twee voorafgaande getallen.

1 --> 1 --> 2 --> 3 --> 5 --> 8 --> 13 --> 21 --> 34 --> etc.

Schrijf een script in Python om de eerste acht getallen van de Fibonaccireeks te printen. In dit script mag je hoogstens twee getallen gebruiken, de rest van de code moet werken met behulp van variabelen.

Start bijvoorbeeld zo:

a = 1
b = 1

Je kunt de print functie gebruiken om waarden van variabelen te printen.

Verifieer je uitkomst met de reeks op Wikipedia.

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: ")

If you’re running this, a textfield will appear in the top center that asks you to type your name. The answer is stored in a variable called name.

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.9

Write Python code for at least three 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.

Opdracht 1.9

Schrijf Python scripts for minstens drie van onderstaande taken. Gebruik de input() en print() functies.

  1. Een script dat de gebruiker vraagt om de radius van een bol, en vervolgens het volume van die bol berekent.

  2. Een script dat de gebruiker om twee getallen vraagt en vervolgens print of het eerste getal groter is dan het tweede.

  3. Een script dat de gebruiker vraagt om drie getallen \(a\), \(b\) en \(c\) en True print als \(a\mod b > c\).

  4. Een script dat de gebruiker vraagt om de hoogte, breedte en diepte van een doos en het volume en oppervlak van de doos berekent.

A warning about running Jupyter Notebooks#

Your Python session is persistent, which means that any variables that you create in a code cell, will be kept in memory. This means that you can create a variable in one cell, run that cell, and then reuse that variable in some other cell. Similarly, you can define a function in one cell and then reuse that function in another cell. Take a look at the example below.

reuse

This is also dangerous: you should keep of track of the order in which you execute cells, because a variable might have a different value than you expect, depending on the order in which you run cells. That means that if you run one cell first and then the other, you might get different behavior than the other way around.

Order

The order in which you run cells matters!