Week 1: Introduction

Week 1: In-Class#

We assume that you have Python installed on your computer. If you haven’t installed it yet, skip the exercises involving IDLE and Python files, and use the online Python editor at Run Python for the rest. Make sure to install Python before the next week’s session. If you have problems with the installation, stop by the Python Support. Once Python is installed, return to the skipped exercises.

Coding Practice#

Code 1.1: Create a Folder for This Course#

You need to create a file for almost every exercise in this course. Therefore, it is important to organize your files from the start. You should:

  1. Decide where on your computer you want to create the folder for this course. A good place is your Documents folder.

  2. Create a folder and give it an appropriate name, for example programming.

  3. Inside this folder, create a subfolder for this week, for example week_01. Here, you should save the files you create during this week’s exercises.

Code 1.2: Open 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.

  1. Open PowerShell. You do this by typing powershell in the taskbar search, and clicking on the search result Windows Powershell.

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

  1. Open Terminal. You do this by opening the Spotlight Search ( + Space), typing terminal, and clicking on the search result Terminal.

  2. 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, press Enter or .

Code 1.3: Use 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.

Knowing this, compute \(\sqrt[3]{23.5}\). You should use the exponent rule \(\sqrt[k]{x} = x^{\frac{1}{k}}\), and the result should be approximately 2.86.

Code 1.4: Run Scripts 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:

  1. Click File again 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 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 with the text Hello World. This is the effect of the code you just ran.

Now, let’s 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 as before.

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, with Python, 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 arithmetic operators are - (subtraction), * (multiplication), / (division), and ** (exponentiation). You can control the order of operations using parentheses, just as in mathematics.

To see how this works, update computations.py to match 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. Python tells you that you used a name it has never seen before. It has no idea what number is. This happens because each time you run a Python script, it starts fresh with no memory of 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 - but you need to understand them. 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: Mathematics and Python#

Look at the following mathematical formulas and how students wrote them in Python. Which student will compute the correct values?

\[ P = \frac{a^2}{2r}\left(1 + \frac{x^2}{2}\right), \]
\[ y = \frac{3x^2-2}{3-x}, \]
\[ s = \frac{a+x}{r}. \]
P = a**2 / ((2 * r) * (1 + x**2 / 2))
y = 3 * x**2 - 2 / 3 - x
s = a + x / r
P = a**2 / (2 * r) * (1 + x**2) / 2
y = (3 * x**2 - 2 )/ 3 - x
s = (a + x)/ r
P = a**2 / (2 * r) * (1 + x**2 / 2)
y = 3 * x**2 - 2 / (3 - x)
s = (a + x) / r
P = a**2 * (1 + x**2 / 2) / (2 * r)
y = (3 * x**2 - 2) / (3 - x)
s = (1 / r) * (a + x) 

Code 1.8: Checking Expressions (Buddy-Exercise)#

A sum of numbers from 1 to \(n\) may be computed as

\[ s = \frac{n(n+1)}{2}. \]

Pair up with another student. Decide who is Student A and who is Student B, then follow the individual instructions for your role.

Write the Python script sum_to_n.py. The script should first define value \(n=5\). Then, it should compute a sum of numbers from 1 to \(n\) using the formula, and save the result in a variable s. Lastly, it should print the value of s.

Without using Python, use the formula above to calculate the sum of numbers from 1 to \(n\) for following values of \(n\): 5, 10, 27, 1, 2, 105.

Write down your results.

Once you are both ready, check whether Student A’s script gives the correct answer for \(n=5\). Then, modify the script to use \(n=10\) and run it to confirm that the output matches the hand calculation. Finally, keep changing and running the script to check it prints the correct answer for each number that Student B has calculated.

You have just practiced an important skill: testing that your code works correctly.

Code 1.9: Another Check (Buddy-Exercise)#

Consider the formula

\[ x = \frac{-b + \sqrt{b^2 - 4ac}}{2a} \]

which gives one of the roots of a quadratic equation. Pair up with another student. Swap roles and follow the instructions.

Write the Python script called roots.py. The script 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\)

As in the previous exercise, once you are ready, check whether the script by Student A gives the correct answer for the first set of values. Then try the second and third set of values and see if the script still works correctly.

Code 1.10: Built-in Functions#

In IDLE, create a new file, type in the code below, save the 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 expressions abs(x) and round(x) use 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, run it, and observe the output. Try also running the script with value of x set to -1/3 and -10/5.

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.11: 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 the text message or the text Programming is important!?

message = "Programming is important!"
print(message)

As you can see, in Python, you can also represent text (strings). Just for fun, run this code.

message = "Programming is important!"
print(3 * message)

Did it work?

We will return to strings in upcoming weeks.

Code 1.12: 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.13: 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 can insert blank lines to divide your code into sections, similar to how you would use paragraphs in an essay.

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 starts 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 the 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#

About problem solving. Programming is used to solve problems. While you only started programming today, you can already solve simple problems. In Problem Solving section, you are given a problem, and you should write code to solve it. For some problems, we show a solution which you can compare with yours. Remember that problem solving is a skill to be practiced. If you look at the solution before you have solved the problem yourself, you have missed out on the opportunity to practice.

Problem 1.14: Cube Measurements#

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 the side length of the cube.

Write a Python script cube_measurements.py which computes and prints the volume and area of the cube with side length of 1.4. You should start your script with the line where you define the variable for the side length, and use that variable when computing the volume and the area.

If you script is working correctly, for a side length of 1.4 it should print

2.7439999999999993
11.759999999999998

Problem 1.15: Imperial to Metric#

You have a niece 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 niece texts you that she is 5 feet and 1 inch tall.

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

\[\begin{split} \begin{aligned} 1 \text{ foot} &= 12 \text{ inches}\\ 1 \text{ inch} &= 2.54 \text{ centimeters} \end{aligned} \end{split}\]

Write a Python script imperial_to_metrics.py where you perform the computation and print the result. In the script, you should initialize variables for the feet part and the inch part of your niece’s height. After calculating the height of your niece in centimeters, round it to a whole number and print it.

For height of 5 feet and 1 inch, your code should print

155

Problem 1.16: Balloon Volume#

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 which is 0.0831 L bar K \(^{-1}\) mol \(^{-1}\), and \(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 balloon_volume.py where you calculate and print the volume of the balloon. You need to isolate \(V\) in the ideal gas law by hand. You should initialize all variables needed to calculate the volume. Then, calculate the volume using an appropriate version of the ideal gas law. Print the result.

For values given above, your code should print

19.87834074074074

Problem 1.17: 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

\[ P = 1-\left(1-{\frac {1}{T}}\right)^{n}. \]

You should write a script where you define two variables of your own choice: 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 100 years and the time period of 25 years. The probability that the 100-year event will occur in a period of 25 years is (displayed with 7 decimal places)

\[ P = 1-\left(1-{\frac {1}{100}}\right)^{25} = 0.2221786. \]

If you try your script with T = 100 and n=25 it should print

0.22217864060085335

Problem 1.18: Distance Traveled#

The distance traveled by an object falling from standstill is calculated using the formula

\[s = \frac{1}{2}g t^2\, , \]

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 and prints the distance traveled (in meters) from the duration of the fall (in seconds).

In the script, you should define a variable t for the duration of the fall (in seconds) and assign it a positive number 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

\[ s =\frac{1}{2}\,9.81 \cdot 5.5^2.\]

If you set t = 5.5 your script should print

148.37625