
Week 2: Closure#
Syllabus Week 2: Variables and Types#
- Concept of statement illustrated by the print statement and assignment statement 
- Assignments and assignment operator - =(formal definition)
- The concept of expressions 
- Variables and types (formal definition) 
- Valid variable names and naming conventions 
- The - type()function
- Concept of namespace (an informal definition) 
- Reassignments 
- Numeric data types: - int,- float
- String data type, - strwith single or double quote
- String operators - +(concatenation) and- *(repetition)
- The - len()function for strings
- Type casting with - int(),- float(),- str()
- Numeric operators: - %(modulus) and- //(floor division)
- Built-in-functions with multiple arguments: - max(),- min(), and- print()
- The - mathmodule
- Via example keyword - importand the import statement
- Functions from the - mathmodule:- math.sin(),- math.cos(),- math.sqrt(),- math.exp(),- math.log(),- math.ceil(),- math.floor().
- Constant - math.pi
- Boolean data type and - bool()
- Comparison operators: - ==,- !=,- <,- >,- <=,- >=
- Logical operators: - and,- or,- not
- Good practice, e.g. avoid - print = 6
- Understanding error messages 
Advanced#
Advanced 2.1: Floating Point Representation#
Run cells
print(0.1 + 0.2)
print(0.7 - 0.4)
print(0.1 + 0.2 - 0.3)
Is this surprising?
Decimal numbers cannot be exactly represented in a computer, and are therefore approximated. For example
   0.1 is represented as 0.1000000000000000055511151231257827021181583404541015625,
   0.2 is represented as 0.200000000000000011102230246251565404236316680908203125,
   0.3 is represented as 0.29999999999999998889776975374843459576368331909179688,
   0.4 is represented as 0.40000000000000002220446049250313080847263336181640625.
This is because computers use a binary system (zeros and ones), which is good for storing fractions of the type \(\frac{1}{2^n}\), like \(\frac{1}{2}, \frac{1}{4}, \frac{1}{8}, \frac{1}{16},...\), but not good for storing \(\frac{1}{3}\) or \(\frac{1}{10}\).
There are two situations, where you need to remember this. The first situation is when you print floating-point numbers, as they might be printed with a lot of digits, as you just saw.
The second situation is when you compare two floating-point numbers, as they might not be equal, even if you think they are. Run the code below for an example. Which comparison works as you would expect? In the example, the number 1e-10 is written using a scientific notation, which we explain in the next section. You can replace it with 0.00000000001.
a = 0.1 + 0.2
b = 3/10
print(a == b)
print(abs(a - b) < 1e-10)
Advanced 2.2: Scientific Notation#
Scientific notation allows for compact representation of very small or very large numbers. For instance, the scientific notation for the number \(6720000000\) is \(6.72 \times 10^9\)
In Python, scientific notation uses the letter e or E to indicate the part of the number that is multiplied by a power of 10. For example, 1e4 represents \(1 \times 10^4\) which is equal to 10000.0 and 3.1e-4 represents \(3.1 \times 10^{-4}\) which is equal to 0.00031.
To try scientific notation in Python, run the code below, and observe the printed outputs.
sn1 = 23e2 
sn2 = 1e-4 
sn3 = 3.14e2  
sn4 = 5.67e-4 
print(sn1)
print(sn2)
print(sn3)
print(sn4)
Can you use e4 to represent 10000.0?
Advanced 2.3: Practice Scientific Notation with Planck’s Equation#
According to Planck’s Equation, the energy \(E\) of a photon in joules can be calculated from its frequency \(f\) as
where \(h = 6.626 \times 10^{−34} \text{ J⋅Hz}^{-1}\) is Planck’s constant. The frequency \(f\) of a photon is related to its wavelength \(\lambda\) by the formula
where \(c = 3 \times 10^{8} \text{ms}^{-1}\) is the speed of light.
Suppose you have a light source emitting photons with a wavelength of \(\lambda = 440 \times 10^{-9} \text{ m}\) (or 440 nanometers). Using Planck’s equation, calculate the energy of these photons. Use scientific notation in your calculations.
Note: You might want to use lambda as a variable name for \(\lambda\). In Python, lambda is a reserved word, and you cannot use it as a variable name.
Advanced 2.4: When Were You Born?#
The code below computes the year when you were born from some information. Try it out an see if it works correctly. How does the code handle the difference between those that already had their birthday this year and those that have not?
age = input("How old are you? ")
year = input("What year is it? ")
had_birthday = input("Did you have your birthday this year? Enter 1 if yes, 0 if no: ")
birth_year = int(year) - int(age) - (1 - int(had_birthday))
print("You were born in", birth_year)
Advanced 2.5: Practice Boolean Variables#
Boolean variables sound simple (either True or False), but can be quite powerful. Here are two problems to help you practice, and the challenge is to solve the problems using only assignments (that is no if statements, which we introduce next week).
Imagine you have four numerical variables: l, w, X and Y. The variables l and w represent the length and the width of a bed, while X and Y represent the side lengths of a rectangular available space. Define a Boolean variable bed_fits which should be True if the bed fits in the available space, and False otherwise. You should make no assumptions about the orientation of the bed.
Hint
Start by assuming that X is the length of the available space and Y is the width. Now, write down the expression for the space is long enough and the space is wide enough. Then, combine these two expressions into the expression for whether the bed fits if it is palaced along the length of the space. Write now a similar expression for the case when the bed is placed along the width of the space. Finally, combine these two expressions into one expression for whether the bed fits in the available space.
Imagine you have a numerical variables age, full_price and discount_price. A person is eligible for a discount if they are older than 65 years, or if they are younger than 18 years. Define a variable price which should be either full_price or discount_price, depending on whether the person is eligible for a discount.
Hint
You can think of the price as a sum of two components: a basic price that is paid by everyone and an extra fee paid only by people not eligible for a discount. You can multiply the extra fee by a Boolean variable that is True if the person is not eligible for a discount, and False otherwise.
Advanced 2.7: Other Numeric Types#
Python assumes that you write numbers in decimal format. However, you can also use other numeric formats, such as hexadecimal (base 16), octal (base 8) and binary (base 2). You can use specific prefixes to indicate these formats. For example, try the following code.
test = 0b101010
print(test)
In a binary representation, as shown above, each digit after 0b represents a power of 2. The rightmost digit represents \(2^0=1\), the next digit represents \(2^1=2\), and so on. The digit values (0 or 1) determine whether the corresponding contribution is included in the final value. Confirm this on the example above.