In-Class#
Coding Practice#
Code 1.1: Creating a Folder for This Course#
In the exercises this week, we just touch upon the basics of Python. We start by learning about code execution and defining variables. During the upcoming weeks, we will look back at all the basics introduced here. For now, just follow the instructions below.
You will need to create a file for almost every exercise you do in this course. Therefore, it is important to have a dedicated folder on your computer for this course, and maintain an organized file structure inside it. You should:
Decide where on your computer you want to create the folder for this course. A good place is your Documents folder.
Create a folder and give it an appropriate name, for example
programming
.Open the folder you have just created and create a subfolder for this week, for example
week_01
. Here, you should save the scripts (files) you will create during this week’s exercises
Code 1.2: Opening IDLE#
To open IDLE, follow the instructions below:
Open PowerShell. You do this by typing
powershell
in the taskbar search, and clicking on the search result Windows Powershell.Type
idle
in the Powershell window, then press Enter.
If the instructions do not work for you, look at the Python Support page for IDLE where you can watch a video on how to open and work in IDLE.
Open Terminal. You do this by opening the Spotlight Search (⌘ + Space), typing
terminal
, and clicking on the search result Terminal.Type
idle3
in the Terminal window, then press ↩.
If the instructions do not work for you, look at the Python Support page for IDLE where you can watch a video on how to open and work in IDLE.
You should now have an IDLE Shell window open. The characters >>>
are called the prompt and indicate the place where you can type a Python command, and press Enter or ↩ to execute it.
Code 1.3: Using Interactive Python as a Calculator#
Enter the command
12 + 18
and observe the result. Confirm that you can use interactive Python to perform calculations by executing the following commands:
1785 - 1234
123 * 2.5
16 / 6
2.5 * (3.5 + 9 / 5)
What do you get when you execute the following commands?
5**2
2**3
Knowing this, compute \(\sqrt[3]{23.5}\). For this you can use the following exponent rule: \(\sqrt[k]{x} = x^{\frac{1}{k}}\).
Code 1.4: Running Python Files in IDLE#
When programming, you’ll often 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 Python script. However, IDLE requires you to save the file before you can run it. Therefore:
Again click
File
and selectSave as...
Navigate to the folder you created in the previous exercise.
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.5: Numerical Variables#
For this exercise, create a new blank file in IDLE and save it under the name numerical_variables.py
.
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.
Code 1.6: 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.
Basic operators 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)
Floating point numbers and rounding. So far you have only been introduced to whole numbers, also called integers. Decimal numbers, also called floating point numbers - or floats for short - 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: String Variables#
Now we look at how you can represent text (strings) in Python using variables. Create a new blank file in IDLE and save it under the name string_variables.py
.
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 by putting 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.9: 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 to 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.10: Comments and Readability#
Blank lines. 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.
message = "I want to print this!"
print(message)
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.
Comments. 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.11: Running a Downloaded Python Script in IDLE#
Instead of creating and running your own Python scripts, you will now download and modify an existing script.
Download the zip-file week01.zip.
Unzip the file using your preferred method, into the directory you made for this week.
In IDLE, open the file named
downloaded_python_script.py
, located in the folder you unzipped to. 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.12: Volume and Surface Area of a Cube#
The volume and surface area of a three-dimensional cube can be calculated as
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
Solution
We hope you chose a good name for the file, one possibility is cube_volume_and_surface_area.py
Below is a solution. The problem can be solved in several ways, and this is just one of them.
# First we define our variable side_length
side_length = 1.4 # h
surface_area = 6 * side_length ** 2 # 6 * h^2
volume = side_length ** 3 #h^3
print(volume)
print(surface_area)
This should print
2.7439999999999993
11.759999999999998
Problem 1.13: 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
Solution
We hope you chose a good name, a possibility is convert_imperial_height_to_metric.py
Below is a possible solution, the problem may be solved in several ways, and this is just one of the possibilities.
# First we need to define our variables, and we split 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
height_cm = (height_inches + height_feet * 12) * inch_to_cm
# Then we print the result
print(round(height_cm))
This should print
154.94
Problem 1.14: Ideal Gas Law#
You want to estimate the volume of a balloon of gas using the ideal gas law
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.
Solution
We hope you chose a good name, a possibility is ideal_gas_law_volume_calculator.py
Below is a possible solution, the problem may be solved in several ways, and this is just one of the possibilities.
# First we define the variables that we know in the ideal gas law
pressure = 0.810 # pressure in bar
gas_constant = 0.0831 # ideal gas constant
num_moles = 0.692 # number of moles
temperature = 280 # temperature in Kelvin
# Then we isolate for volume: P * V = n * R * T => V = n * R * T / P
volume = num_moles*gas_constant*temperature/pressure
# Finally we print the result
print(volume)
This should print
19.87834074074074
Problem 1.15: Event Probability #
When describing extreme events, such as major earthquakes, landslides, and floods, we utilize the concept of a return period \(T\), given in years. For example, a flood with a return period of 100 years, referred to as a 100-year flood, is a flood that has a probability of \(\frac{1}{100}\) of occurring in any given year. The probability that an event with a return period \(T\) will occur within a time period of \(n\) years can be expressed as
You should write a script where you define two variables: the return period (in years), T
and the time period (also in years) n
. The script should calculate the probability of an event with a return period occurring during the given time period and print it.
As an example, consider a return period of T = 100
years and the time period of n = 25
years. The probability that the 100-year event will occur in a period of 25 years is (displayed with 7 decimal places)
which is what the script should print, as shown in the code cell below.
0.22217864060085335
Problem 1.16: Distance Traveled #
The distance traveled by an object falling from standstill is calculated using the formula
where \(s\) is the distance traveled (in meters), \(t\) is the duration of the fall (in seconds), and \(g\) is the gravitational acceleration on Earth, equal to \(9.81\mathrm{m}/\mathrm{s}^2\).
You should write a script that calculates the distance traveled (in meters). Start by defining a variable for the duration of the fall (in seconds), t
and then use this variable along with the formula to compute the distance and print it.
Write a script that defines a variable t
for the duration of the fall (in seconds) and assign it a positive float of your choice. The script should then calculate the distance traveled (in meters) and print the result similar to the example below.
Consider an object falling for \(5.5\) seconds. The distance traveled is
so if you set t = 5.5
your script should print the following:
148.37625