In-class#

Coding Practice#

Code 1.1: Creating a folder for this course#

It’s a good practice to create a dedicated folder on your computer for this course. We also recommend maintaining an organized file structure. You should:

  1. On your computer, create a folder for this course, named programming

  2. Open the folder you have just created

  3. Inside the programming folder, create a subfolder called week_01. Here, you should save the scripts (files) you will create during this week’s exercises

Code 1.2: Opening IDLE#

Note

This exercise requires Python to be installed on your computer.

If you haven’t installed it yet, you can skip the exercises involving IDLE (Code 1.2, 1.2 and 1.9). You can complete the other exercises using the online Python editor at Run Python, but without creating or saving scripts. In that case, proceed to Code 1.4: Variables and code execution.

Make sure to install Python before the next week’s session. If you have problems with the installation, stop by the Python Support at DTU. Once Python is installed, return to the skipped exercises.

To open IDLE, follow the instructions below:

  1. Open PowerShell. You do this by opening the menu bar, searching for PowerShell, and clicking on the search result “Windows Powershell”.

  2. Type idle in the Powershell window, then press Enter.

If the instructions do not work for you please consult Python Support.

  1. Open Terminal. You do this by opening the Spotlight Search ( + Space), searching for Terminal, and clicking on the search result “Terminal”.

  2. Type idle3 in the Terminal window, then press .

If the instructions do not work for you please consult this website Python Support.

You should now have IDLE Shell window open. Guidelines at Python support show screenshots of the IDLE Shell window for both Windows and MacOS, so you are welcome to look at Python Support IDLE Getting started part.

Code 1.3: Running Python files in IDLE#

When programming, you’ll need to write and save a script (a file containing some code) for future use. In IDLE, you can create a new Python file by clicking File in the top left corner and selecting New File. This will open a new blank window in IDLE. In the blank file you just created, type in the following.

print('Hello World')

You are very close to running your first piece of Python code. However, IDLE requires you to save the file before you can run it. Therefore:

  1. Again click File and select Save as...

  2. Navigate to the folder you created in the previous exercise.

  3. Save the file under the name my_first_script.py. The the extension has to be .py, indicating that it is a Python file. IDLE should automatically add the extension if you don’t type it yourself.

Now, you can run the file by clicking Run and selecting Run Module. Alternatively, you can run the file by pressing F5.

Look in the window that opened when you started IDLE (the IDLE Shell), there should now be a line with

Hello World

This is the result of the code you just ran.

To make sure that you indeed run the same code again later, you should now close the file my_first_script.py.

From the first window that opened when you opened IDLE (the IDLE shell) click File, select Open, then choose the my_first_script.py file you saved before. Verify that the code in the file is the same as what you wrote earlier, run it again, and check that the output is the same.

The steps in this exercise are also described by Python Support, so you can look at Python Support IDLE Creating and running scripts if you would like to see the screenshots of the process.

Code 1.4: Variables and code execution#

In the exercises this week, we just touch upon the basics of Python. We start by defining variables and learning about code execution. During the upcoming weeks, we will look back at all the basics introduced here. For now, just follow the instructions below.

For this exercises, create a new blank file in IDLE and save it under the name my_first_variable.py.

String variables. First, we look at how you can represent text (strings) in Python using variables.

Insert the following in the file you just created and run the file.

message = "programming is important"
print(message)

Does Python print out message or programming is important?

Meeting your first error. Delete the first line such that the code in my_first_variable.py is as below.

print(message)

Save, and run the file.

Python should now give you an error, specifically a NameError, since it has no idea what message is. This happens because each time you run a Python script, it starts fresh, and has no recollection about previous runs.

You will encounter various types of errors, and even experienced programmers write code that causes errors regularly. Error messages can be a big help, and indicate how you can fix the error. For now, we will leave it at this, but you will be familiarized with errors and debugging (fixing errors) in the coming weeks.

Try now to fix the error the removed line back in the code, but place it at the end of the file, as in the code below.

print(message)
message = "programming is important"

Save and run the file again.

Python is still giving you NameError because it reads the code from top to bottom, and when you asked it to print, it has not yet seen the line where message is defined.

Code 1.5: Syntax in Python#

When you write Python code there are certain rules you have to follow. Create a new file in IDLE, and save it as syntax.py.

Spaces. Try to copy and paste the following code into your new file and run it.

my variable = "hello world"

This should give a SyntaxError because we have a space in the variable name. Thus, we typically use underscore _ instead. Change the code to the following correct code, and see that it runs without errors.

my_variable = "hello world"

Upper and lowercase. Insert the following code in syntax.py and try to run it.

message = "I want to print this!"
print(Message)

Trying to run the code should give you a NameError like you encountered earlier. This is because Python is case-sensitive, meaning that message and Message are not the same. Correct the code so the message is printed and run it.

One convention is only use lower-case letters for variable names. All code you will be shown today follows this convention.

Indentation. Copy-and-paste the following code into syntax.py and run it.

 message = "I want to print this!"
print(message)

If you copied the code correctly it should give an IndentationError. This is because the first line starts with a space. You will later learn that Python uses the number of spaces to group code together. For now, remember to start each line of code at the leftmost side of the window.

Luckily the number of spaces in the middle makes no difference at all. To verify this, copy the following code (which looks strange) into syntax.py and run it.

message              =     "I want to print this!"
print(        message)

Code 1.6: Numerical variables and operators#

Create a new blank file, and save it to your folder under the name numerical_variables.py.

Your first numerical variable. Copy the following into your script numerical_variables.py and run the script as described in the previous exercises.

a = 3
b = 7
c = a + b
print(c)
print(a)
print(b)

The first two lines define two numerical variables, the third line computes their sum, which the fourth line prints out. The last two lines print the variables a and b, in separate lines.

Try to change the values of a and b and see what happens when you run the script.

Essentially, we use Python as a calculator, but one where we can store everything in a file, and come back to it anytime we desire.

Numerical operators. You have just seen + in action, however this would be a poor calculator if we could only add numbers. Luckily, all the other mathematical operators you are used to also exist.

The common ones are subtraction (-), multiplication (*), and division (/). You can change the order of operations using parentheses, just as you know from mathematics. To see how this works, insert the following code in numerical_variables.py and run the code.

a = 10
b = 2
c = 4
d = 5
calculation_result = (a - d) * b / c
print(calculation_result)

Notice that Python prints out 2.5 Can you change the values of either a, b, c, or d such that Python prints out 10.0 instead?

The power operator. The last numerical operator we will introduce this week is the power operator. In Python, it is written as ** hence \(a^2\) is written as a**2.

Replace the code in numerical_variables.py with the following and run it.

a = 2
calculation_using_power = a ** 3
calculation_using_multiplication = a * a * a
print(calculation_using_power)
print(calculation_using_multiplication)

Are the two printed numbers the same, and is that what you would expect?

Code 1.7: Built-in functions#

Python offers a range of built-in functions, in this week we introduce two of them, namely the abs() and round() functions. Create a new file in IDLE, save it in the folder you created under the name built_in_functions.py

The absolute value. In Python, abs() returns the absolute value of the input. Insert the following code in built_in_functions.py and run it to see the abs() operator in action.

x = -10
absolute_value_of_x = abs(x)
print(absolute_value_of_x)

Rounding and floats. So far you have only been introduced to whole numbers, also called integers. Decimal numbers, also called floats, are also very common in programming. Replace the code in built_in_functions.py with the following code, run it to see two different floating point numbers.

float_one = 3.33
float_two = 10 / 3
print(float_one)
print(float_two)

Observe that float_two got printed with a lot of decimals.

Replace the code in built_in_functions.py with the following code, run it to see the round() operator in effect

my_number = 3.33
my_rounded_number = round(my_number)
print(my_rounded_number)

As you can see the number has been rounded down to the nearest whole number. Try rounding the number 3.88.

Code 1.8: Comments and readability#

From IDLE, create and save a new file called comments_and_readability.py. Insert the following code (which intentionally contains an empty line) in the file and run it.

my_number = 3.33
my_rounded_number = round(my_number)

print(my_rounded_number)

Blank lines in Python are ignored, so they won’t affect your code.

Inserting blank lines in your code can make it more readable. Readability is an important concept in programming. A code is readable if it is easy to understand for other people, or for yourself at a later date when you might have forgotten about what the code does.

This is where comments come in handy. Comments are ignored by Python, so you can use them describe (in natural language) what’s going on in the code. We use # to start a comment.

Replace the code in comments_and_readability.py with the following code, and run it.

# First we define our variable
my_number = 3.333    # This is the floating point number I want to round

# The following lines rounds the number and prints the resulting value
my_rounded_number = round(my_number)
print(my_rounded_number)

Notice here that we can both write a comment on a line by itself, and we can start a comment after some code on the same line. Everything to the right of # will be ignored by Python.

Add a # in front of the last line in your script, so it becomes #print(my_rounded_number) and run the script again.

Note how it does not print anything now. This is because Python interprets the entire last line as a comment, and does not run the code in it. Commenting lines of code is a useful way to disable code temporarily, without deleting it.

Comments are great for explaining code, but equally important is proper variable naming. Imagine that you have a variable denoting the concentration of nitrogen in the atmosphere. We show four examples of naming and commenting, ranging from the difficult to understand to the very descriptive. First the most difficult to understand

x = 0.78

The next one is helped by a comment, but in a longer script, it might be hard to remember what x is.

x = 0.78    # Concentration of nitrogen

The following is even easier to understand, since the name tells us as much as the comment above, and later in the code we can see what the variable is used for.

nitrogen_concentration = 0.78

Finally, we get to most complete one, the naming makes it understandable and the comment adds to the understanding.

nitrogen_concentration = 0.78   # Concentration of nitrogen in the atmosphere

Code 1.9: Running a downloaded Python script in IDLE#

Instead of creating and running your own Python scripts, you will now download and modify a preexisting script.

  • Download the zip-file week_01_exercise_scripts.zip.

  • Unzip the file using your preferred method, into the directory you made for this week.

  • Go inside the extracted folder named week_01_exercise_scripts.

  • In IDLE, open the file named week_one_download_exercise.py. The file contains some print statements, that look weird.

  • However, try running the code and see if it doesn’t make sense when executed.

  • Run the file.

  • What did Python show?

Problem solving#

Programming is used to solve problems. While you only started programming today, you can already solve simple problems. In this section, you will be given a problem, and you will have to write code to solve it.

Problem 1.1: Calculating compound interest#

The formula for compound interest is given by

\[ A = P \left(1+r\right)^{t} \]

where \(A\) is the amount in some currency, \(r\) is the interest rate, \(P\) is the initial/principal value and \(t\) is the time in years.

Assume you deposit 200 in the bank at an interest rate of 0.04. Write some code that calculates the compound interest after 3 years:

  • Create a new IDLE file, and save it in your folder under an appropriate name.

  • You can copy and paste the code below to initialize the variables.

  • Write the code to calculate the compound interest.

  • Print the output in the end of the script

principal_value = 200   #P = 200
interest_rate = 0.04    #r = 0.04
time = 3    #t=3

Note that in mathematics we usually write variables using a single letter, however in programming we may (and often do) use longer variable names. On the other hand, in programming we may only use latin letters, numbers and underscores in variable names.

Problem 1.2: Volume and surface area of a cube#

The volume and surface area of a three-dimensional cube can be calculated as

\[ V = h^{3} \quad \text{and} \quad A = 6 h^{2} \]

where \(V\) is the volume of the cube, \(A\) is the surface area of the cube, and \(h\) is side length of the cube. Assume the cube has side length \(h = 1.4\).

Write a small piece of Python code where you calculate the volume and surface area of a cube:

  • Create a new IDLE file, and save it in your folder under an appropriate name.

  • Define the variable side_length you can see how it is done below.

  • Calculate the volume and surface area of the cube.

  • Remember to print the volume and the surface area at the end of the code.

side_length = 1.4   # h

This should print

2.7439999999999993
11.759999999999998

Problem 1.3: Converting imperial units to metric#

You have a friend visiting you from the United States. You would like to take her to Tivoli, but you know there is a height limit of 132 centimeters on some of the rides. Your friend texts you that she is 5 feet and 1 inches tall.

To determine whether she can use the rides or not, you want to calculate the height of your friend in centimeters. Here are conversion rates from feet to inches and from inches to centimeters:

\(1 \text{ foot} = 12 \text{ inches}\)

\(1 \text{ inch} = 2.54 \text{ centimeters}\)

Write a small piece of Python code where you:

  • Create a new IDLE file, and save it in your folder under an appropriate name

  • Initialize variables for the feet part and the inch part of your friend’s height, a possibility is as seen below.

  • Calculate and print the height of your friend in centimeters rounded to a whole number.

# Split the feet and inches into two variables, i.e 5 feet and 1 inch
height_feet = 5 # Your friend's height in feet
height_inches = 1 # Your friend's height in inches
inch_to_cm = 2.54

This should print

154.94

Problem 1.4: Ideal gas law#

You want to estimate the volume of a balloon of gas using the ideal gas law

\[ P V = n R T \]

where:

  • \(P\) is the pressure of the gas (in bars, bar)

  • \(V\) is the volume of the gas (in liters, L)

  • \(n\) is the amount of gas (in moles, mol)

  • \(R\) is the ideal gas constant (0.0831 L·bar·K \(^{-1}\) mol \(^{-1}\))

  • \(T\) is the temperature of the gas (in Kelvin, K)

The balloon contains \(0.692\) moles of gas at a temperature of \(280\) Kelvin and a pressure of \(0.810\) bar.

You should write a small piece of Python code where you calculate the volume of the balloon. For this, you should:

  • Isolate \(V\) in the ideal gas law

  • Create a new IDLE file, and save it in your folder under an appropriate name.

  • Initialize variables of the ideal gas law stated above. Remember to define appropriate names for each variable. .

  • Calculate the volume \(V\) using a formula you derived from the ideal gas law.

  • Print the result.

This should print

19.87834074074074