The lecture recaps programming concepts covered so far like variables, data types, selection statements, and functions. It then presents a "Test Generator" case study to demonstrate designing, coding, and enhancing a program through multiple versions. The case study involves generating random math tests with addition or subtraction problems for students. Pseudocode is developed for each version to plan the program logic before coding.
2. This Lecture
• Recap of programming concepts
– Summary of what we’ve covered so far
– Fundamental concepts of programming
• “Test Generator” case study
– Working through the process of designing, coding and enhancing a program
based on a problem description
2
3. Textbook
• Starting Out with Python, 4th Edition (Global)
– Tony Gaddis
• Reading the chapter(s) is required
– Read the indicated chapter(s) before class
• This week covers the following textbook chapter(s):
– Revise anything you’ve missed from Chapters 1 – 5 & 7
3
5. Recap of Programming Concepts
• We are not going to introduce any new concepts this week
– We have covered many important concepts in the first 4 modules,
and it’s worth taking a break to consolidate them
• This week we will take it easy and recap past modules
– If you have fallen behind or are struggling with something from the first 4 modules,
take this as an opportunity to catch up
• Always remember: No matter how good or how bad you are at programming,
the best way to improve is to program more – practise develops understanding
– Learning to program is all about developing the “mindset” of a programmer; Learning
to dissect and solve problems with the tools that a programming language provides
• I cannot teach you this; It is a skill that you need to develop
5
6. Module 1: Introduction to Programming
• We started out by establishing that this unit aims to teach you programming,
not just “programming in Python”
– The examples from various languages throughout the slides have hopefully illustrated
that despite the syntax of languages being different, the concepts are largely the same
• Computers exist to be useful; to do things for us
– People need to write programs for them to achieve this, and those programs must be
written in a way that a computer can understand – following the rules of a language
– Over the years, these languages have evolved and grown to be more useful and
accessible – making it easier to write programs
6
7. Module 1: Introduction to Programming
• Programming is problem solving
– This involves breaking the problem down into series of steps which can be
implemented in a programming language
– Programming languages are tools used to solve problems
• Pseudocode and flowcharts are two ways of illustrating this process.
This helps in two ways:
– To come up with a design/solution without worrying about the syntax of code and
minor details of programming
– To communicate or illustrate a design/solution to others
Prompt the user for a value
Multiply the value by 2
Show the value on the screen
Pseudocode Result = value * 2
Get value
Display result
7
8. Module 1: Introduction to Programming
• The source code of a program is made up of statements
– A statement is an “instruction” that tells the program to do something, and must be
written using correct syntax
• Statements can do many things, but overall they can:
– Receive some kind of input from the user
– Perform some kind of processing upon data
– Present some kind of output to the user
• Most programs, and parts of programs, can be broken down in this manner
Input Output
Processing
8
9. Module 1: Introduction to Programming
• In Module 1 we illustrated this with a simple program:
• This introduced some fundamental programming concepts:
– Variables, to store and refer to values via a name
– Comments, for descriptive and informative text in a program
– Built-In Functions, such as input() to get input, float() to convert values to
floats and print() to display output
# convert pounds to kilograms
value = input('Enter a value in pounds: ')
result = float(value) * 0.454
print(value, 'pounds is', result, 'kilograms')
Python
9
10. Module 2: Data Types & Selection
• Data types are the “categories” of data that a programming language recognises
– Every value has a data type
– The data type of a value determines what can and cannot be done with the data, e.g.
Arithmetic works on integers and floats, but not strings
– The basic data types are:
• Languages follow different rules regarding whether values of different data types
can be mixed/converted automatically
– “Weakly typed” languages focus on convenience (implicit)
– “Strongly typed” languages focus on safety (explicit)
10
Type Description Examples
integer (int) Whole numbers 2, -500, 4294967296
float (float) Numbers with a fractional part 3.14159, -0.3, 25.0
string (str) A sequence of characters 'Hello, World!', '25', ' '
boolean (bool) A true or false value True, False
11. Module 2: Data Types & Selection
• Understanding data types and the rules your language follows when dealing
with them is very important, e.g.:
– In most languages, keyboard input from the user is received as a string,
since a string can hold anything that the user types
• You may need to convert it to an integer or float before using it numerically
– 100 (int), 100.0 (float) and '100' (string) are all different
• You may need to convert a value to a different data type to do certain things with it
• What is considered “equal” or “equivalent” may differ between languages
– Concatenating strings and numbers (integers or floats) is a common requirement,
and languages handle it differently or offer various ways to achieve it
• You may need to convert numbers to strings first, e.g. 'The total is ' + str(total)
• However, some languages do it for you, or take a different approach…
11
12. Module 2: Data Types & Selection
• Selection statements such as “if” allow for a choice between different blocks
of code depending on a condition
– This can be expanded with “else” and “elif” (else-if) to accommodate whatever
flow of logic is necessary in your program
• A condition is a boolean expression
– i.e. An expression that results in either True or False
– Usually involves comparison operators (==, !=, >, <, <=, >=), functions that return
True or False, or the language coercing a non-boolean value to True or False
– Can also contain logical operators (and, or, not) to combine the results of multiple
comparisons into a final True or False
and True False
True True False
False False False
or True False
True True True
False True False
12
13. Module 2: Data Types & Selection
condition
True
False
only run if true
condition
True
False
only run if true only run if false
condition
1
True
False
only run if
condition 1 true
condition
2
condition
3
False
False
True only run if
condition 3 true
True only run if
condition 2 true
only run if all
conditions false
“If-Then” “If-Then-Else” “If-Then-Else-If”
13
14. Module 3: Data Structures and Iteration
• A “data structure” allows multiple pieces of data to be stored in some form of
organised structure
– Like a data type, a data structure defines what the language can do with it, such as
adding/removing items, sorting them, etc.
• Storing multiple values in a variable allows you do things that would otherwise be impossible
or inconvenient, such as sorting, counting, min/max, determining if a value exists in it…
• An “array” is simply an ordered collection of values
– Depending on the language, the values can be different data types, or even other data
structures (e.g. arrays within arrays)
– Values in an array are referenced by an index that starts from 0, e.g. names[2]
– Python has array-like data structures named list and tuple
• Lists are the most commonly used. They are mutable (can be changed) and defined with [],
e.g. names = ['Sam', 'Mary', 'John']
14
15. Module 3: Data Structures and Iteration
• Loop/Iteration statements allow a program to repeatedly run a block of code
(known as the “body” of the loop)
– Loops are controlled by either a counter or a condition. i.e. They run a certain
number of times, or while a condition is met
– Loops are often used to do something for each item in a data structure, or to repeat
part of a program until something happens to indicate that it should stop
• Watch out for common errors when writing loops:
– “Off by one”, where an incorrect condition involving >, >=, < or <= causes a loop to run
one too few or one too many times
– Infinite loops, where a loop never ends because there is nothing in the loop body to
make the condition become false and no “break” statement to exit the loop
– Erroneously including or excluding statements from the loop body, resulting in
unexpected or incorrect behaviour
15
16. Module 3: Data Structures and Iteration
• A “while loop” checks its condition and runs the loop body if it is true, ending
when the condition is false
– A while loop is typically used when you don’t
know how many times the loop will run, e.g.
If it depends on user input
– Some languages also have a do-while loop
(checks the condition after running loop body)
• A “for loop” is typically counter-controlled; It runs a certain number of times,
or once for each item in a data structure
– Iterating through a data structure is a very common use of a “for” loop (i.e. “for each”)
– Many languages implement “C-style for loops”, which are a generic condition-
controlled loop usually used with a counter variable / in a counter-controlled way
condition
True
False
loop body
16
17. Module 3: Data Structures and Iteration
Counter-Controlled For Loop (“For-Each”)
for <variable> in <sequence>:
<loop body>
C-Style For Loop
for (<init>; <condition>; <increment>)
{
<loop body>
}
item left in
sequence?
True False
set variable to next item
loop body
condition
True False
loop body
initialisation
increment
17
18. Module 4: Functions and Modules
• Functions implement the concept of process abstraction
– Call function by name, pass it the necessary parameters and receive the result
without needing to know the details
– Should perform a well-defined task and be independent of the code that calls it
(via parameters and return statements)
• Languages contain built-in functions to do common things, and modules full of
functions to do specialised things
– You can also define your own functions to do things specific to your program
• If used appropriately, functions facilitate simpler code, more code reuse,
better testing, faster development and easier teamwork
19
def <function name>(<parameters>):
<function body>
19. Module 4: Functions and Modules
• A variable’s “scope” is the part of a program in which a variable exists
– A variable that is created inside a function is known as a “local variable” and its
scope is limited to that function – it only exists within the body of that function
• Any parameters that a function defines become local variables in the function, with their
values being passed into the function when it is called
– Variables created outside of a function (i.e. directly in the main part of a program) are
known as “global variables”
• While they can be accessed from any function, this is strongly discouraged as it prevents
functions from being independent and is confusing
• Any data that a function needs should be passed to it via parameters, and any
result it produces should be returned from it using a “return” statement
20
20. Module 4: Functions and Modules
• As well as built-in functions and statements, languages come with modules
– These are packages that provide specialised functionality (functions, variables and
classes) for a certain task, e.g. random numbers, statistics, mapping, graphics…
– By only importing them when needed, programs remain small and memory efficient
• As well as the modules that come with a language, people can make and release
their own to fill gaps / improve things
• Large and complex programs are likely to use many modules, both from the
standard library and external ones
21
Specialised or
General?
Needs to be
Imported?
Part of Standard
Library?
Built-In Functions General No Yes
Standard Library Modules Specialised Yes Yes
External Modules Specialised Yes No
21. Summary
• In summary, we have covered:
– The basic concepts of what a program consists of (source code files made up of
syntactically-correct statements)
– User interaction via input (keyboard) and output (to screen)
– Using variables to hold and reference data, and the concepts of data types and
data structures to categorise and organise the data in useful ways
– Using control structures such as selection and iteration statements to control “the
flow of execution”, allowing programs to take different paths through the code
– Using functions and modules to make code more modular and efficient and make
writing larger programs more convenient
22
22. What’s Next?
• What we’ve covered so far are the fundamental concepts
– The large majority of code is based on these concepts
• The topics and concepts that we cover in future weeks will build upon these
fundamentals, for example:
– Reading from and writing to files is building upon the input and output concepts that
we’ve covered
– Exception handling builds upon the concept of control structures, allowing you to
detect and respond to errors or exceptions in a program (“try” / “except”)…
– Covering additional data structures such as dictionaries builds upon the concept of
data structures
23
24. “Test Generator” Case Study
• To illustrate the process of designing, coding and enhancing a program,
we’re going to work through a case study
1. We will begin with a problem description
• A description of what our program needs to achieve
2. We’ll then write pseudocode to design our program
• This will help us to plan it out before worrying about code
3. Next, we’ll code the program based on our pseudocode
• Any errors will be fixed as we encounter them
4. Lastly, we’ll enhance the program, adding more features
• This will involve returning to the pseudocode design stage
25
25. “Test Generator” – Problem Description (Version 1)
• Our problem description is as follows:
– A primary school teacher wants a way to generate simple maths tests for her young
students. To prevent copying, she wants each test to have randomised questions.
• The tests will be printed and completed by students in class
– Tests must be 10 questions long and the questions will consist of simple addition or
subtraction of numbers between 0 and 9, e.g. “5 + 7 = ____”
• Students have not covered negative numbers yet, so a subtraction test should not include
questions that result in negative answers, e.g. “3 - 5”
– Version 1 of the program needs to prompt the user to enter “+” or “-” to specify which
type of test they want, and then generate an addition or subtraction test as appropriate
• Examples of the program’s desired output are on the next slide
26
28. “Test Generator” – Problem Description (Version 2)
• Now that we have the basic test generating program up and running, let’s
enhance it to be more useful:
– Version 2 of the program must do everything Version 1 does, and…
– The program must make sure that it does not generate the same question multiple
times in the same test
• The same numbers in a different order is acceptable for addition questions,
e.g. “2 + 4” and “4 + 2”
29
30. “Test Generator” – Problem Description (Version 3)
• Let’s enhance the program a little bit more!:
– Version 3 of the program must do everything Version 2 does, and…
– The program must prompt the user to specify how many tests to generate,
and generate that many tests
• The tests are displayed on the screen one after the other
31
32. “Test Generator” – Extra Enhancements
• These enhancements further extend the test generator program, but we won’t
implement them in class
– Try implementing them yourself in the workshop or study time
• Enhancement 1 – Challenge Question:
– Before generating tests, the program prompts the user to specify (“y” or “n”) whether
to make the final question of the test a challenge question
• If they choose “y”, the final question should use the numbers 10 to 20 instead of 0 to 9, and
print “Challenge question – do your best!” before the final question
• As there are now two parts of the program that generate a question, with just the minimum
/maximum values that differ, consider creating a function to make this more efficient
33
33. “Test Generator” – Extra Enhancements
• Enhancement 2 – Input Validation:
– The program should validate all input, and re-prompt the user if their input is invalid
• The “number of tests” prompt should only accept integers of 1 or more
– Use the “input_int()” function from Workshop 4
• The “addition or subtraction” prompt should only accept “+” or “-”
• The “challenge question” prompt should only accept “y” or “n”
– For these prompts, create a function named “input_choice()” that accepts a prompt and
tuple or list of valid responses
– Use a loop to repeatedly prompt the user for input until they enter a valid response
op = input_choice('Addition or subtraction? [enter "+" or "-"]: ', ('+','-'))
Parameter 1:
Prompt to display
Parameter 2:
Tuple of valid responses
34
34. “Test Generator” – Extra Enhancements
• Enhancement 3 – Output to File:
– Instead of showing the tests on the screen, the program should write the output to a
file named “output.txt”
• The program should create “output.txt” if it doesn’t exist, and overwrite the file with the new
output it if it does exist (this is what happens when you open a file in “write” mode)
• After writing the tests into the file, program should display “Tests saved in output.txt file.”
• Notes:
– We haven’t covered writing to files yet, but it’s really quite simple – have a look at Module 6 or
Chapter 6 of the textbook
– The “print()” function adds a line break to the end of what it prints, but “file.write()”
does not. You’ll need to add an extra “n” to the end of the lines you write to the file
– “print()” allows for multiple parameters and automatically concatenates them and adds
spaces… “file.write()” does not – you need to convert and concatenate strings yourself
35
35. Conclusion
• We’ve covered the fundamental concepts of programming
– Take this week to recap and catch up as needed
– Programming is about developing a programmer’s “mindset”
– Subsequent weeks will build upon the fundamental concepts
• Our case study worked through the process of designing, coding and enhancing
a program – this is the same approach you should be taking to your assignments!
– We began with a problem description
– We wrote pseudocode to design our program
– We coded the program based on our pseudocode
– We tested the program and fixed any errors we made
– We enhanced the program, adding more features
36