Dr Alexander Fletcher

Autumn 2020/21

A program is a sequence of instructions for the computer to follow.

Let's think about telling someone how to cross the road.

- If there is a crossing nearby use it!
- Otherwise, look left and right until no traffic is coming.
- Then walk across the road, looking and listening until you get to the other side.

A computer program is similar but the language is more formalized.

The above illustrates basic features shared by many computer languages.

Variables | to store data and information, can be of various types |
`a = 7` |

Mathematical operations | add, multiply, etc. | `+` , `*` |

Input and output operations | communicate with the user and the World | `input` , `print` |

Loops | for repeating a set of steps | `while` , `for` |

Conditional statements | for checking if you want to do one thing or another | `if` , `else` |

Functions / procedures | to encapsulate a sequence of steps you perform often | `def` |

- Understand the problem or task.
- Design your solution. (In something like English.)
- Write your program. (In Python.)
- Test and debug your program.

Writing in Python does not come until step 3!

Often you will go back to previous steps.

Often you will program a little bit at a time.

(Break the task down.)

**Task.** For each number from 1 to 50,000 find its factors by trial division.

[*Trial division* means that to find if *x* is a factor of *n* you try to divide *n* by *x* and see if you have any remainder.]

- What is the task asking me to do?
- Do I understand what a factor is?
- Do I understand what trial division means?

- Write down the mathematical problem.
- Start to think how to address it algorithmically.
- How can I perform trial division?
- Will I need to repeat any actions?
- Do I need a loop?
- What do I need to print to screen?

1 2 3 4 5 6 7 8 9 | n = 1 while n <= 50000: print("The factors of", n, "are:") i = 1 while i <= n: if n % i == 0: print(i) i = i + 1 n = n + 1 |

Line 2 starts a *loop* that will repeat lines 3–9 from `n==1`

until `n==50001`

.

Line 5 starts a *loop* that will repeat lines 6–8 from `i==1`

until `i==n+1`

.

Line 7 prints `i`

to screen *if* `i`

is a factor of `n`

.

- Does the program run?
- Does the program print anything to screen?
- Does the program print 1 and
*n*as factors for each value of*n*? - Does the program give the correct answer for a smaller value than 50,000?
- Does the program take a long time to run?

(We will discuss refactoring and debugging in the next two lectures.)

`if`

command```
if (boolean_condition):
do this
followed by this
carry on here
```

For example

password = input("Enter password: ") if password == "parrot": print("Correct") print("Thank you")