Linear Algebra and Programming Skills¶

Dr Jon Shiach, Department of Computing and Mathematics, Manchester Metropolitan University


If statements¶

Learning Outcomes¶

On successful completion of this page readers will be able to:

  • Write conditional statements in Python and combine these using logical connectors for AND, OR and NOT;
  • Use if statements to perform commands based on logical conditions.

A common task in programming is to perform an operation if a particular condition is met. If statements allow us to do this and are an integral part of computer programming.


Conditional statements¶

Conditional statements are statements which we can use to make decisions based on its result. They return a Boolean value of either True or False depending on what condition we have applied.

Operator   Name Python code
$=$ equal x == y
$\neq$ not equal x != y
$>$ greater than x > y
$<$ less than x < y
$\geq$ greater than or equal to   x >= y
$\leq$ less than or equal to x <= y

Python can also assume a numerical value of a boolean value where 1 is the same as True and 0 is the same as False.

Example 1¶

Use Python commands to determine the output of the following logical statements:

  (i)   $2 = 3$

2 == 3
In [1]:
2 == 3
Out[1]:
False

  (ii)   $2 \neq 3$

2 != 3
In [2]:
2 != 3
Out[2]:
True

  (iii)   $2 > 3$

2 > 3
In [3]:
2 > 3
Out[3]:
False

  (iv)   $2 < 3$

2 < 3
In [4]:
2 < 3
Out[4]:
True

  (v)   $2 \geq 2$

2 >= 2
In [5]:
2 >= 2
Out[5]:
True

  (vi)   $3 \leq 2.9999$

3 <= 2.9999
In [6]:
3 <= 2.9999
Out[6]:
False

Logical Connectors¶

The Python commands standard logical connectors for AND, OR and NOT are given in the table below.

Connector   Name   Python code
$\lor$ or x or y
$\land$ and x and y
$\lnot$ not not x

Example 2¶

Use Python commands to determine the result of the following logical statements

  (i)   $(2 < 3) \lor (3 = 4)$

2 < 3 or 3 == 4
In [7]:
2 < 3 or 3 == 4
Out[7]:
True

  (ii)   $(3 > 2) \land (22 = 4)$

3 > 2 and 22 == 4
In [8]:
3 > 2 and 22 == 4
Out[8]:
False

  (iii)   $\lnot \left(\dfrac{9}{3} = 3\right)$

not (9 / 3 == 3)
In [9]:
not (9 / 3 == 3)
Out[9]:
False

If statements¶

If statements are used in a program to execute commands when a certain logical condition is met. The syntax of an if statement takes the following form

if conditional statement:
    commands executed when true

Note that the commands following the if statement are indented.

Example 3¶

The commands below defines two variables a and b and prints a sentence if a < b. Enter them into the code cell below and execute it to see the result. Try changing the values of a and b to see what effect it has.

a, b = 2, 3

if a < b:
    print(f"{a} is less than {b}.")
In [10]:
a, b = 2, 3

if a < b:
    print(f"{a} is less than {b}.")
2 is less than 3.

Exercise 1 - If statements¶

  1. Use an if statement to write a program that halves an integer if it is even.

    Hint: the x % y command will come in useful here.
In [11]:
x = 4
if x % 2 == 0:
    x = x / 2
    
print(x)
2.0

If-Else statements¶

If you want to execute some commnds if the logical condition is met but others if it is not we can use an if-else statement

if conditional statement:
      commands executed when true
else:
      commands executed when false

Example 4¶

The commands below defines the variable hour and prints a sentence based on whether its value is greater or less than 12. Enter them into the code cell below and execute it to see the result. Try changing the value of hour to see what the effect is.

hour = 10

if hour < 12:
    print("Good morning, how are you today?")
else:
    print("Good afternoon, how are you today?")
In [12]:
hour = 10

if hour < 12:
    print("Good morning, how are you today?")
else:
    print("Good afternoon, how are you today?")
Good morning, how are you today?

Exercise 2 - If-Else statements¶

  1. Use an if-else statement to write a program to print a statement whether the a number is or is not divisible by 3.
In [13]:
x = 6

if x % 3 == 0:
    print(f"{x} is divisible by 3")
else:
    print(f"{x} is not divisible by 3")
6 is divisible by 3

If-ElseIf-Else statements¶

We can specify further conditions in the event that the first condition is not met using an if-elseif-else statement

if conditional statement:
    commands executed when true
elif another conditional statement:
    commands executed when true
else:
    commands executed when none of the conditional statements are true

Example 5¶

The following commands defines the variable hour and uses if-elseif-else statements to check whether it value is valid (for a 24 hour clock) and prints a sentence based on this value. Enter them into the code cell below and execute it to see the result. Try changing the value of hour to see what the effect is.

hour = 21

if hour < 0 or hour > 23:
    print("The value for the hour should be between 0 and 23.")
elif hour < 12:
    print("Good morning, how are you today?")
elif hour < 18:
    print("Good afternoon, are you having a good day?")
else:
    print("Good evening, did you have a good day?")
In [14]:
hour = 21

if hour < 0 or hour > 23:
    print("The value for the hour should be between 0 and 23.")
elif hour < 12:
    print("Good morning, how are you today?")
elif hour < 18:
    print("Good afternoon, are you having a good day?")
else:
    print("Good evening, did you have a good day?")
Good evening, did you have a good day?

Exercise 3 - If-ElseIf-Else statements¶

  1. Write a program that determines whether a number stored in the variable x is positive, negative or zero and prints the result.
In [15]:
x = -1

if x > 0:
    print(f"{x} is a positive number")
elif x == 0:
    print(f"{x} is zero")
else:
    print(f"{x} is a negative number")
-1 is a negative number
  1. Write a program that prints the degree classification based on a specified average mark using the following mark bands.
Average mark Degree classification
$\geq 70$ first class
$\geq 60$ upper 2nd class (2:1)
$\geq 50$ lower 2nd class (2:2)
$\geq 40$ third class
$<40$ fail
In [16]:
average_mark = 55

if average_mark >= 70:
    print("first class")
elif average_mark >= 60:
    print("upper second class")
elif average_mark >= 50:
    print("lower second class")
elif average_mark >= 40:
    print("third class")
else:
    print("fail")
lower second class
  1. Write a program that calculates the real roots of a quadratic polynomial given the values of $a$, $b$ and $c$ for $0=ax^2+bx+c$ using the quadratic formula

    $$x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}$$
    The program should determine whether there are two, one or no real roots. Test your program with the following quadratic equations

    (a)   $0 = 2x^2 - 10x +12$ which has roots at $x = 2$ and $x = 3$

    (b)   $0 = x^2 + 6x + 9$ which has a single root at $x = -3$

    (c)   $0 = 3x^2 + 2x + 1$ which has no real roots

In [17]:
import numpy as np

a, b, c = 3, 2, 1
discriminant = b ** 2 - 4 * a * c

if discriminant > 0:
    root1 = (-b - np.sqrt(discriminant)) / (2 * a)
    root2 = (-b + np.sqrt(discriminant)) / (2 * a)
    print(f"The quadratic equation 0 = {a}x^2 + {b}x + {c} has two real roots at "\
          f"x = {root1:0.4f} and x = {root2:0.4f}")
    
elif discriminant == 0:
    root = -b / (2 * a)
    print(f"The quadratic equation 0 = {a}x^2 + {b}x + {c} has one real root at x = {root:0.4f}")
    
else:
    print(f"The quadratic equation 0 = {a}x^2 + {b}x + {c} has no real roots")
The quadratic equation 0 = 3x^2 + 2x + 1 has no real roots
  1. Write a program that converts a time given in hours and minutes using the 24 hour format to 12 hour format. e.g., 15:05 would become 3:05pm.

    Hint: use print(f"{x:02d}") to output x using a leading zero if x is less than 10.
In [4]:
hours, minutes = 15, 5

if hours < 12:
    print(f"{hours:02d}:{minutes:02d} is {hours}:{minutes:02d}am")
else:
    print(f"{hours:02d}:{minutes:02d} is {hours - 12}:{minutes:02d}pm")
15:05 is 3:05pm
  1. Use the logical connectors and and or and the print command to produce the following truth table.

    Hint print(f"{x:d}") will print 1 if x = True and 0 if x = False.
 x | y |  x or y | x and y
--------------------------
 0 | 0 |    0    |    0
 0 | 1 |    1    |    0
 1 | 0 |    1    |    0
 1 | 1 |    1    |    1
In [19]:
print(" x | y | x or y | x and y")
print("--------------------------")
x, y = 0, 0
print(f" {x} | {y} |    {x or y}   |    {x and y}")
x, y = 0, 1
print(f" {x} | {y} |    {x or y}   |    {x and y}")
x, y = 1, 0
print(f" {x} | {y} |    {x or y}   |    {x and y}")
x, y = 1, 1
print(f" {x} | {y} |    {x or y}   |    {x and y}")
 x | y | x or y | x and y
--------------------------
 0 | 0 |    0   |    0
 0 | 1 |    1   |    0
 1 | 0 |    1   |    0
 1 | 1 |    1   |    1