Be sure to do all exercises and run all completed code cells.
If anything goes wrong, restart the kernel (in the menubar, select Kernel\(\rightarrow\)Restart).
Strings and Variables¶
Strings¶
As we have seen in the introduction a string is a string of letters or numbers – enclosed in quotes – that is not interpreted mathematically.
Operations such as +
and *
work differently on strings to on numerical data types.
print("Hello" + "World!")
Here, we did not enter a space when adding (joining) the two strings.
There are various ways we can include a space, the last one including a space character " "
:
print("Hello " + "World!")
print("Hello" + " World!")
print("Hello" + " " + "World!")
The following two examples are equivalent:
print("Hello" + "Hello " + "Hello")
print("Hello " * 3)
However, strings cannot be multiplied together so this will not work:
print("Hello" * "World!")
Other things that do not work include: string + int and string * float (try them to see what happens).
Strings can be useful for displaying numerical in a more clear format.
If you want to use a numerical value in a text string it first needs
converting to string format using the built-in conversion function
str
:
print("The answer is " + str(6*7))
The conversion function takes a numerical argument (in brackets) and converts it into a string of characters. In the previous case the number 42 was converted into the plain text (ascii) characters 4 and 2.
String Methods and Functions¶
Strings have certain inbuilt functions called “methods” that can be used to change them.
Study the ones below to see what they do.
#Here we set a variable to store the string then use it instead of typing the whole thing
quote = "the QUICK BROWN Fox jumps over the LAZY Dog"
print( quote )
print( quote.upper() )
print( quote.lower() )
print( quote.title() )
print( quote.capitalize() )
Some functions take arguments, like the STR.replace(FIND, REPLACE)
function, which replaces every instance of the string variable stored in FIND with that in REPLACE.
print( quote.replace("the", "every") )
Also functions can be chained in sequence:
print( quote.replace("BROWN", "RED").title().replace("Lazy", "Sleeping") )
Variables¶
One of the things that makes a programming language like Python more powerful than a calculator is the fact that we can give a name to an intermediate result.
The assignment statement: =¶
We give a name to a value using an equals sign (=
) called the “assignment statement”.
The name appears on the left hand side of the equals sign and the value (or calculation) appears on the right hand side.
After a variable is assigned a value, the value will replace the name anywhere it is used in the script below it.
distance = 45.6 # assignment statement
time = 0.5 # another assignment statement
print(distance / time) # the two names will be replace by their values
Names are called variables.
Variables can be useful to make a complicated expression more clear.
The calculation:
((4*9.81*0.05)/(3*0.47) * (2650.0 - 1000.0)/1000.0)**0.5
can be made a lot clearer by giving names to some of the parameters and intermediate results and by adding comments.
# Terminal velocity of spherical object
g = 9.81 # acceleration due to gravity (m/s^2^)
d = 0.05 # object diameter (m)
C_d = 0.47 # drag coefficient (1)
rho = 1000.0 # fluid density (kg/m^3^)
rho_s = 2650.0 # object density (kg/m^3^)
geometry_factor = (4*g*d)/(3*C_d)
buoyancy_factor = (rho_s - rho)/rho
V_t = (geometry_factor * buoyancy_factor)**0.5
print(V_t)
This makes it also much easier to make changes or corrections.
Evaluate \(w\) where:¶
\(w = 3 a - 5 b + 2 c\)
#set w equal to the mathematical expression
# YOUR CODE HERE
print(w)
Expected Result: 40
Evaluate \(w\) where:¶
\(\displaystyle w = \frac{5 a - 2 b}{4 c + 2 a}\)
Result: 0.54
# YOUR CODE HERE
print(w)
Expected Result: 0.54
Evaluate \(w\) where:¶
\(\displaystyle w = \sqrt{2 a - b}\)
# YOUR CODE HERE
print(w)
Expected Result: 3.3166247903554
The word variable refers to the fact that we can change what value a name refers to.
The same name can be reused for different values.
a = 0.618
print(a)
a = 1.618
print(a)
IMPORTANT: Assignment is not equals!¶
Note that the use of the equals sign can be confusing at first.
The
equals sign denotes assignment and not an equation in the mathematical
sense.
A = B
takes the rigt hand side (B) and assigns it to the variable (A) on the left.
Notes:¶
The following example will generate an error message since this not legal Python code.
2*3 = a
If one variable is assigned to another, it takes its current value but they do not remain equal forever:
a = 1 # set a to 1
b = a # b takes the current value of a
a = 2 # change the value of a
print(a, b) # note that b does not change
The right hand side (RHS) is evaluated before assignment to the varible on the left (LHS), so the following examples are possible in Python:
a = 1
print(a)
# take the value of a and add 1 to it, assign this back to `a`
a = a + 1
print(a)
# multiply the current value of `a` by 2 and overwrite `a`
a = 2*a
print(a)
# replace the value of the variable `a` with its old value squared
a = a**2
print(a)
Note:
in each case the old value of a
is taken and used for the calculation, before replacing it using the assignment statement (=).
Example: Swapping two values¶
Suppose we have assigned the names varA
and varB
to two different
values.
To swap the values, we have to
use a temporary name to refer to one of the values.
varA = 7
varB = -99
print(varA, varB)
tmp = varA
varA = varB
varB = tmp
print(varA, varB)
Allowed Variable Names¶
A valid variable name consists of letters (A,a,B,b,…), digits (1,2,3,…) and underscores ( _ )
but ** cannot start with a digit**.Spaces are not allowed in variable names.
You should not use an underscore at the start of a variable name, since this has a special meaning in Python.
Python is case-sensitive, which means that upper and lower case letters are distinct.
a = 5
b2 = a + a
quite_a_long_variable_name = 0.1
A = 50.0
outerRadius = 5.7
print(a, b2, quite_a_long_variable_name, A, outerRadius)
Example: Quadratic Formula¶
The following program finds the solutions of the quadratic equation
\(a x^2 + b x + c\) using the quadratic formula:
$\(x = \frac{-b\pm\sqrt{b^2-4ac}}{2a},\)\( where \)b^2-4ac$ is known as the
discriminant.
We assume in this example that there are
two solutions.
# coefficients of the quadratic a*x**2 + b*x + c
a = 1.0
b = -5.0
c = 6.0 # quadratic formula for the equation a*x**2 + b*x + c = 0
disc = b**2 - 4*a*c # assumed to be positive
print(disc)
x1 = (-b + disc**0.5)/(2*a)
x2 = (-b - disc**0.5)/(2*a)
print(x1, x2)
Exercise run the quadratic formula program with different coefficients¶
Use an equations for which you know what the results should be:
e.g.: \(x^2 - 4 = 0\).
# YOUR CODE HERE
print(x1, x2)
Find out what happens when the discriminant is negative.
# YOUR CODE HERE
print(x1, x2)
Using Built-in Constants¶
Important constants like \(\pi\) and \(e\) can be accessed by loading the math
library using
import
.
The imaginary number \(i=\sqrt{-1}\) (called \(j\) by electrical engineers) is accessed using 1j
.
from math import pi, e
print(pi, e, e**(1j*pi) + 1)
Note that the last result is \(1.2\times10^{-16}i = 0.00000000000000012i\approx 0\), due to floating-point precision (see appendix of Section 1).
Strings as Variables¶
Strings can also be assigned to variable names, and it important to not confuse the two. For example:
word1 = "Hello World!"
print("word1")
print(word1)
Notice that in the first instance the string word1
that was enclosed
in quotes was
print ed and in the second the string value hello
assigned to the variable named word1
was
printed.
Formatting Numbers in Strings¶
Integer or floating point numbers can also also be combined with strings in other ways. They can be directly interspersed with text strings by separating them with commas without conversion:
print("The answer is", 40+2, "but not", "40"+"2")
Notice that spaces were automatically added in this case.
There are
other ways of formatting objects including numbers in text output (we will see more later).
One is the including special syntax such as %d
for integers and %f
for
floating point numbers (there are others).
The value to replace it with
follows the string, preceded by a percent symbol.
import math
pi = math.pi
print("Pi is %d as an integer" % pi)
print("Pi is %f, approximately" % pi)
print("Pi is %.3f to 3 decimal places" % pi)
In the third case
%.3f
is used to display the value to three decimal places. This can be very useful for displaying the results of calculations neatly. We will see another method for including numbers in strings later in the unit.
Another method is the format()
function (study how each of the arguments works and make notes on your observations):
mysentence = "This is how to put {} and {} in the sentence {}.".format("this", "that", "here")
print(mysentence)
mysentence2 = "This is how to place {2} then {0} and finish with {1}.".format("zero", "one", "two")
print(mysentence2)
this = "An integer: {:.0f}, two dp: {:.2f}, full precision: {}, ".format(pi, pi, pi)
print(this)
final = "Base of natural logs: {1:.3f}, pi = {0:.5f}".format(pi, e)
print(final)
Formatted “f-strings”¶
From Python 3.6 onwards a new method: “f-strings” were introduced to Python:
from math import pi, e
a=42
#the first argument is a plain variable name, .3f gives it to 3 decimal (floating point) places, and the third to 3 digits
formatted_string = f"The answer is {a}, the number pi is {pi:.3f} and the base of natural logarithms is {e:.3}."
print(formatted_string)
This makes formatting numbers in text much easier than before. Strings can also be formatted into strings, as the following multi-line string (using three quote marks on either side) shows:
Multiline Strings¶
Finally, strings can also be formatted as multi-line strings using three quote marks on either side:
a=42
palindrome = "do geese see god"
multiline = f"""Hello I am a multiline string,
as you can see my lines can be broken!
I can also include the contants of variables like {a}.
Not only that, other strings!:
This: {palindrome}
That: {palindrome.upper()}
Something else: {(palindrome+" ")*3}
"""
print(multiline)
Summary¶
# a comment is ignored
import math # importing a module
-999 # an integer
0.0999 # a floating point number
1.987e-6 # scientific/engineering notation
print(88) # printing a value
print(1, 4, 9) # printing multiple values
print(10**(2*3) - 1) # integer arithmetic
print(7/2) # integer arithmetic does what you would expect in real life
print(7.0/2.0) # floating point arithmetic
print(math.pi*100) # built-in constant
num1 = 44 # assignment statement
num2 = 2*33
print(num1 + num2)
Operations:
+
,-
,*
,/
,**
,%
Functions:
type
,int
,float
,round
Constants:
math.pi
,math.e
Pitfalls¶
The operation
*
denotes multiplication and cannot be omitted. It can be helpful to read out a formula.
E.g., \(5 (4 + 2)\) reads as five times four plus two.In other programming languages or in in previous Python versions (e.g. Python 2), the symbol
/
denotes integer division. In them, we have7/2 => 3
, but7.0/2 => 3.5
and7/2.0 => 3.5
. But this is not the case in Python 3.Variable names are case-sensitive.
Do not confuse assignment statements and mathematical equations.
Task 2 (2%)¶
Use the Daylight Factor sheet and the following instructions to complete the code below.
Enter the parameters \(\theta=57^\circ\) and \(\tau=0.64\) (calling them
theta
andtau
), given the values in the Example.Calculate the room reflectance \(\rho\) (“rho”) as an intermediate step using the formula:
\(\rho=\dfrac{A_c\times r_c + A_s \times r_s + A_g \times r_g + A_f \times r_f}{A}\)
using the values for the dimensions of the walls, glazing area and reflectance (\(r\)) given in the sheet.Using Equation 16.3: \(A_g = \dfrac{\overline{D}A(1-\rho^2)}{\theta\ \tau}\),
calculate a new glazing area needed to achieve a daylight factor of 5%.Your correct code should display the answer given below the example:
Re-run from fresh (restart kernel or e.g. using Spyder) to check your script before submitting
Some partially filled out code is below to get you started.¶
Copy and paste it into a new notebook
Save it as a Python
YOUR_FILENAME.py
file (no spaces in the filename)Check it runs independently using Spyder or Jupyterlabs
Submit the
.py
file to moodle.
# reflectivities are defined here:
r_c = 0.7
r_s = 0.4
r_g = 0.1
r_f = 0.2
# assign the values below
#theta=
#tau=
# YOUR CODE HERE
# Assign values to variables for dimensions (in m):
width = 4
length = 8
height = 3
# Calculate areas (first two done for you):
A_g = 6.9
A_s = 2*width*height + 2*length*height - A_g
#A_c = #calculate area of ceiling
#A_f = #calculate area of floor
#A = #calculate total area
# YOUR CODE HERE
# fill in the formula for the area weighted average reflectance below
#rho = ()/()
# YOUR CODE HERE
# Don't alter this next two lines! Old daylight factor is
D_old = A_g*(theta*tau)/(A*(1-rho**2))
print("Old Daylight Factor =", D_old)
# this sets the required Daylight factor to 5 (percent)
D = 5
#A_g = # formula for the new glazing area
# YOUR CODE HERE
#leave this next line alone - DO NOT EDIT!
print("Glazing Area for 5% DF =", round(A_g, 2), "m^2")
Expected Output (exactly formatted like this):
Old Daylight Factor = 2.221119979796034
Glazing Area for 5% DF = 15.53 m^2
The output should be the above and nothing else! (remove any code that prints anything else).
Use the checking cell below after running your code above to see if it will pass the autograder…¶
Run the cell below - this will only work using JupyterHub online
#this will only work running on ace.jupyterhub.bath.ac.uk
import sys
sys.path.append('.checks')
import check02
check02.test(rho, D_old, A_g)
Extra:¶
NB: Don’t submit this next bit!
Can you spot what is wrong with the above calculation?
Try commenting out the line
A_g = 6.9
and re-running the code-blockRun it again a few times in sequence.
Why do you think this is happening?
We will explore this further later on.
Extra Practice Example:¶
Projectile Motion¶
The height of a ball thrown upwards with a velocity \(v_0\) is given by $\(y = y_0 + v_0 t - \frac{1}{2} g t^2,\)\( where time \)t=0\( when the ball is released. The ball is released at height \)y_0\(. The initial velocity is \)v_0\(. Position, velocity and acceleration are all measured as positive upwards. Take \)y_0 = 1.5\(, \)v_0 = 12.8\( and \)g = 9.81$.
Use Python to calculate the height of the ball at \(t = 2\).
Use Python to calculate the time \(t\) for which \(y = 5\).
(Hint: rearrange and use the quadratic formula: \(x=\dfrac{-b\pm\sqrt{b^2-4ac}}{2a}\))
# YOUR CODE HERE
print(t_1, t_2)
Expected Result:
0.31034543701622325 2.29923662210712