1.2. Fundamentals#

1.2.1. Arithmetic#

Python supports basic arithmetic operations addition, subtraction, multiplication and division using the symbols +, -, * and /. Brackets are used to indicate the order in which the parts of an expression are computed. For example, in the following expression, the division is performed first and then the addition.

3 + 4 / 2
5.0

In order to compute \(\frac{3 + 4}{2}\), use brackets:

(3 + 4) / 2
3.5

In order to calculate powers, use the ** operator. For example, the following calculates \(8^3\):

8 ** 3
512

1.2.1.1. Arithmetic Operators#

The following arithmetic operators are available in Python. Modulo and Floor division are explained in Section 1.2.6.

Operator

Symbol

Addition

+

Subtraction

-

Multiplication

*

Division

/

Power

**

Modulo

%

Floor division

//

1.2.2. Number Types#

Every Python variable has a data type as well as a value. The type determines what operations can be performed on the variable and how it is stored in the computer’s memory. Python supports a number of primitive data types including numbers, strings, lists and files and in particular there are two number types: integers and floating point numbers. When we specify a number in code it is important to understand which type we are creating:

Number

Type

Description

5

int

A whole number

-5

int

A negative integer

0.5

float

A number with decimal part

5.0

float

Including a decimal point always results in type float

5e6

float

\(5\times10^6\)

2.34e-5

float

\(2.34\times10^{-5}\)

Exercise 1.1

Use Python to calculate the value of \(\frac{-5 + \sqrt{5^2 - 4}}{2}\).

Hint: \(\sqrt{x} = x^{0.5}\).

1.2.3. Variables#

A variable is a named storage location in the computer’s memory. We store a value in a variable so that we can use it later in our computations.

We use assignment to set the value of a variable:

speed = 35 # create a new variable named 'speed' and assign the value 35
double_speed = speed * 2 # create new variable named 'double_speed'

In order to inspect the value of a variable, we use the print function:

print(speed)
print(double_speed)
35
70

The print statement can print multiple values. Separate each value by a comma , and use double quotes " for literal text:

print("The value of speed:", speed)
print("The value of double_speed:", double_speed)
The value of speed: 35
The value of double_speed: 70

Exercise 1.2

Complete the following code so that it prints the two solutions to the quadratic equation \(x^2 + 5x + 4 = 0\):

a = 1
b = 5
c = 4

pos_solution = (-b + (b**2 - 4*a*c)**0.5) / (2*a)

print("Positive Solution:", pos_solution)

Note

VARIABLE NAMING RULES

  • A variable name can only contain alpha-numeric characters and underscores (A-Z, a-z, 0-9, and _)

  • A variable name cannot start with a number

  • Variable names are case-sensitive (age, Age and AGE are three different variables)

Warning

Beware of accidentally renaming Python keywords. The following is correct Python but a Very Bad Idea because it renames the print function, which will result in some very weird errors!

print = 5

print(print) # this won't work.

1.2.4. Updating Variables#

We can use assignment to change the value of a variable. In this case, the same variable appears on both sides of the equals sign:

print("Original speed:", speed)

speed = speed + 2 # Increase the value of speed by 2

print("New speed:", speed)
Original speed: 35
New speed: 37

This is a legal statement because Python first evaluates the expression on the right of the equals sign (speed + 2) and then places the result into the variable on the left.

Exercise 1.3

Complete the code below so that it divides v by 5 three times, printing its value each time.

v = 1000
print("v:", v)

# your code here

should output:

v: 1000
v: 200.0
v: 40.0
v: 8.0

1.2.5. Getting Help#

print is the first of many Python in-built functions that we will study.

You can find out more about Python functions by using the help() function. Let’s learn about the print function.

help(print)
Help on built-in function print in module builtins:

print(...)
    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
    
    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.

For example, from this we can see how to change the default seperator using sep:

print("1", "2", "3", sep="-")
1-2-3

1.2.6. Modulo Arithmetic#

Using the / operator results in a floating-point (decimal) value:

9 / 4
2.25

On the other hand, the // operator performs floor division, computing the quotient and discarding the fractional part:

9 // 4
2

To calculate the remainder after floor division, use the modulus operator %:

9 % 4
1

1.2.6.1. Example 1#

The % operator is useful to determine if a variable is divisible by a number. For example, if a number is even its remainder after dividing by 2 is zero; if it is odd its remainder after dividing by 2 is 1:

x = 5
print(x % 2)
x = 6
print(x % 2)
1
0

1.2.6.2. Example 2#

Suppose we have 1234 pennies in the piggy-bank. How much do we have in pounds and pence? First we divide by 100 to get the whole number of pounds:

num_pennies = 1234
pounds = num_pennies // 100
print("Pounds:", pounds)
Pounds: 12

Next we use the % operator to find the number of pence:

pence = num_pennies % 100
print("Pence:", pence)
Pence: 34

1.2.7. Repeating code using while#

A loop is a sequence of instructions which is executed repeatedly until a goal is reached. The while loop repeats a section of code while a specific condition is true.

The following loop repeatedly divides the variable v by 5 while the condition v > 10 is true.

v = 1000
while v > 10:
    print("v:", v)
    v = v / 5
v:
 1000
v: 200.0
v: 40.0

Exercise 1.4

Write a while loop which multiplies v by 5 while v is less than 1000.

v = 10

# your code here

Should produce:

v: 10
v: 50
v: 250

1.2.8. If statement#

The specific heat capacity of water depends on whether it is in a solid, liquid or gaseous state.

State

Specific heat capacity (kJ/kgK)

Solid

2.108

Liquid

4.187

Gas

1.996

Let’s write code which, given the temperature of a water sample, sets the value of the variable shc to the appropriate value (of course, we need to know the melting and boiling points of water!)

temp = 90 # temperature of water sample

if temp > 100: # gas
    shc = 1.996
elif temp > 0: # liquid
    shc = 4.187
else:          # solid
    shc = 2.108
    
print("Specific heat capacity:", shc, "kJ/kgK")
Specific heat capacity: 4.187 kJ/kgK

The if statement evaluates the expression temp > 100 and if it is true, executes the indented code directly underneath, then skips to the next statement after the if-else block. If it is not true, execution moves to the elif statement. If the expression temp > 0 is true, the indented code beneath it is executed and execution skips to the next statement after the if-else block. Finally, if neither expression is true, the indent code block below the else statement is executed.

Note

If statement

  • Exactly one of the indented code blocks will be executed.

  • Use the tab key to indent code by exactly four spaces.

  • The if, elif and else statements must be followed by a colon (:).

  • Note the unusual keyword elif (rather than elseif).

  • The elif and else statements are optional.

Warning

Assignment vs Equality

= is the assignment operator. It assigns the value on the right to the variable on the left:

x = 6 + 7 # sets x to the value 13

== is the equality operator. It evaluates to True if the expression on the left is equal to the expression on the right.

x == 13 # returns `True`

The condition in an if statement should always use ==. This is a common mistake:

if x = 13: # this is a mistake. Be careful!
    print("yes")

Exercise 1.5

Complete the code below so that it prints

x is even

if is x is divisible by 2 and prints

x is odd

if it is not divisible by 2.

x = 53783

# your code here

Should produce:

x is odd.

Check that your code works by changing the value of x and running the code again.