Week 1: In-Class#
Content of in-class live demo for Week 1. The in-class live demo covers different ways to run Python code: online, starting and interactive Python from the terminal, executing scripts from the terminal, using interactive Python in IDLE, and executing scripts from IDLE - the last being the method students should use. Demo also shows executing Python cells in Jupyter notebooks.
Coding Practice#
Code 1.1: Creating a Folder for This Course#
This week’s exercises cover code execution and defining variables. We will return to these fundamentals in the coming weeks. For now, just follow the instructions below.
You need to create a file for almost every exercise 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 create during this week’s exercises
Code 1.2: Opening IDLE#
Open IDLE. If you need help opening IDLE, visit the Python Support page for IDLE where you can watch a video on how to open and work in IDLE. The summary of the instructions is provided in the box 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.
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 ↩.
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. When you want to execute the command, you should press Enter or ↩.
Code 1.3: Using Interactive Python as a Calculator#
In the IDLE Shell window, enter (type followed by pressing Enter or ↩) the command written below, and observe the result.
12 + 18
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
What do you think **
does? If you are unsure, discuss with your neighbor, and try with other numbers until you are confident about your answer.
Code 1.4: Running Python Files from IDLE#
When programming, you often save a script (a file containing some code) for future use. In IDLE, you 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 window, type the following line.
print('Hello World')
You need to save the script 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 extension has to be.py
, indicating that it is a Python file and IDLE will 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 IDLE Shell (the window that opened when you started IDLE). You should see a line
Hello World
This is the effect of the code you just ran. To check that you can reopen and rerun the same file, close the file my_first_script.py
. From IDLE shell, click File
, select Open
, and choose my_first_script.py
. Confirm that the code 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: Script with Computation#
For this exercise, create a new blank file in IDLE, type in the commands from the block below, save the file under the name computations.py
, execute it, and observe what happens in the IDLE Shell window.
a = 3.5
b = 7.2
c = a + b
print(a)
print(b)
print(c)
As you see, Python works like a calculator, but with the advantage that you can save your computations in a file and revisit them whenever you want.
In the script above, you used the +
operator to add two numbers. Other common operators are -
for subtraction , *
for multiplication, and /
for division. You can change the order of operations using parentheses, just as you know from mathematics. You have also seen that Python uses **
as an operator for exponentiation (power) between two numbers.
To see how this works, update computations.py
so it matches the code below and run the script.
a = 10
b = 4
c = 2
d = 6
result1 = (a - d) * (b / c)
result2 = (a - d) ** b / c
result3 = (a - d) ** (b / c)
print(result1)
print(result2)
print(result3)
Code 1.6: Order of Execution#
Create a file in IDLE, type in the commands from the block below, save it as order.py
, and execute it.
number = 13.2
print(3 * number)
Now, delete the first line such that the code in order.py
is as below. Save and run the file again.
print(3 * number)
Python should now give you an error, specifically a NameError
, since it has no idea what number
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. Save and run the file again.
print(3 * number)
number = 13.2
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 number
is defined.
Code 1.7: Testing Python Expressions (Buddy-Exercise)#
Consider the formula
which gives one of the roots of a quadratic equation. Pair up with another student. Decide who is Student A and who is Student B, then follow the instructions for your role.
Write the Python script called roots.py
. The scrip should first define values \(a=1\), \(b=2\), and \(c=1\). Then, the script should compute \(x\) from \(a\), \(b\), and \(c\) using the formula. Lastly, the script should print the value of x
. Remember the exponent rule \(\sqrt[n]{d} = d^{\frac{1}{n}}\) which can be used to compute roots using **
.
Without using Python, calculate \(x\) by hand for the following values of \(a\), \(b\) and \(c\):
\(a=1\), \(b=2\), \(c=1\)
\(a=2\), \(b=0\), \(c=-2\)
\(a=2\), \(b=5\), \(c=2\)
Once both of you are ready, check whether Student A’s script gives the correct answer for the first set of values. Next, modify the script to use the second set of values and confirm the output matches the hand calculation. Finally, try the third set of values and see if the script still works correctly
You have just practiced an important skill: testing that your code works correctly.
Code 1.8: Built-in Functions#
In IDLE, create a new file, type in the code below, save tha file in your folder as built_in_functions.py
, run it and observe the output.
x = -10.8
y = abs(x)
z = round(x)
print(x)
print(y)
print(z)
The expression abs(x)
and round(x)
uses built-in functions abs
and round
to compute the absolute value and the rounded value of x
, respectively.
You will learn many more built-in functions as the course progresses, and in Week 5 you will learn how to create your own functions.
In built_in_functions.py
, try changing the value of x
to 3.28
and observe the output. Change the value of x
to -1/3
and -10/5
and observe the output.
As you can see, the output of round
is always an integer (whole number), while the output of division /
is a floating point number (a number with decimals). You will learn more about different types of numbers in Python next week.
Code 1.9: Representing Text#
Create a new blank file in IDLE and save it under the name representing_text.py
. Type in the code below, and try running it. Does Python print out message
or programming is important
?
message = "Programming is important!"
print(message)
As you can see, in Python, you can also represent text (strings). Just for fun, running this code.
message = "Programming is important!"
print(3 * message)
Did it work?
We will return to strings in upcoming weeks.
Code 1.10: Syntax in Python#
When you write Python code there are certain rules you have to follow. These rules are called syntax. Create a new file in IDLE, and save it as syntax.py
.
Try to copy and paste the following code into your new file and run it.
my text = "hello world"
This should give a SyntaxError
because we have a space in the variable name, which is on the left side of =
. We typically use an underscore _
instead of a space in variable names. Correct the code by replacing space with underscore, and see that it runs without errors.
Now insert the following code in syntax.py
and 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 and run it.
Most programmers write variable names in lower-case, especially for numbers and text, but the code will also run with upper-case letters. Try it out.
Now 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 one line starts with a space, and another does not. The line starting with space is indented. You will later learn that Python uses the indentation 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, and is not how one writes code) into syntax.py
and run it.
message = "I want to print this!"
print( message)
Code 1.11: 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.
message = "I want to print this!"
print(message)
Blank lines in Python are ignored, so they won’t affect your code.
You cen insert blank lines to divide your code into sections, similar to how you would use paragraphs in an essay. Inserting blank lines may make code easier to read to other people, or for yourself at a later date when you might have forgotten about what the code does.
Sometimes you want Python to ignore not just blank lines, but also some text. Try running the code below.
# 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)
A character #
start a comment which is ignored by Python. You can use comments to describe (in natural language) what’s going on in the code.
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. What gets printed now?
As you see, 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
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: Cube Measurements#
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 Python script 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
.Calculate the volume and surface area of the cube.
Print the volume and the surface area at the end of the code.
Your code should print
2.7439999999999993
11.759999999999998
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)
Problem 1.13: Imperial 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 Python script where you perform the computation:
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.
Calculate and print the height of your friend in centimeters rounded to a whole number.
Your code should print
155
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))
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.
Write a Python script where you calculate the volume of the balloon. For this, you should:
Isolate \(V\) in the ideal gas law by hand.
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.
Your code should print
19.87834074074074
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)
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)
and the script should print
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
148.37625