SlideShare a Scribd company logo
1 of 35
Download to read offline
Programming Fundamentals
Lecture 5: Recap and Case Study
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
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
Recap of Programming Concepts
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
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
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
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
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
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
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
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
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
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
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
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
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
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>
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
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
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
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
“Test Generator”
Case Study
“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
“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
“Test Generator” – Example Tests
Addition Test
Name: ___________
2 + 4 = ____
6 + 5 = ____
1 + 8 = ____
9 + 2 = ____
5 + 4 = ____
6 + 4 = ____
7 + 2 = ____
5 + 3 = ____
2 + 1 = ____
9 + 7 = ____
Subtraction Test
Name: __________
7 - 5 = ____
8 - 6 = ____
2 - 2 = ____
9 - 6 = ____
5 - 1 = ____
4 - 0 = ____
9 - 7 = ____
6 - 4 = ____
9 - 1 = ____
9 - 5 = ____
27
“Test Generator” – Version 1 Pseudocode
Pseudocode
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
“Test Generator” – Version 2 Pseudocode
30
Pseudocode
“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
“Test Generator” – Version 3 Pseudocode
32
Pseudocode
“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
“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
“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
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

More Related Content

Similar to ProgFund_Lecture_5_Recap_and_Case_Study-1.pdf

pythontraining-201jn026043638.pptx
pythontraining-201jn026043638.pptxpythontraining-201jn026043638.pptx
pythontraining-201jn026043638.pptxRohitKumar639388
 
Programming Language
Programming  LanguageProgramming  Language
Programming LanguageAdeel Hamid
 
DOC-20210303-WA0017..pptx,coding stuff in c
DOC-20210303-WA0017..pptx,coding stuff in cDOC-20210303-WA0017..pptx,coding stuff in c
DOC-20210303-WA0017..pptx,coding stuff in cfloraaluoch3
 
part 1 - intorduction data structure 2021 mte.ppt
part 1 -  intorduction data structure  2021 mte.pptpart 1 -  intorduction data structure  2021 mte.ppt
part 1 - intorduction data structure 2021 mte.pptabdoSelem1
 
Se 381 - lec 26 - 26 - 12 may30 - software design - detailed design - se de...
Se 381 - lec 26  - 26 - 12 may30 - software design -  detailed design - se de...Se 381 - lec 26  - 26 - 12 may30 - software design -  detailed design - se de...
Se 381 - lec 26 - 26 - 12 may30 - software design - detailed design - se de...babak danyal
 
Lesson 1 of c programming algorithms and flowcharts.pptx
Lesson 1 of c programming algorithms and flowcharts.pptxLesson 1 of c programming algorithms and flowcharts.pptx
Lesson 1 of c programming algorithms and flowcharts.pptxAlinaMishra7
 
0-IntroductionToDSA.ppt
0-IntroductionToDSA.ppt0-IntroductionToDSA.ppt
0-IntroductionToDSA.pptTrnHuy921814
 
Ch1 language design issue
Ch1 language design issueCh1 language design issue
Ch1 language design issueJigisha Pandya
 
Introduction to programming by MUFIX Commnity
Introduction to programming by MUFIX CommnityIntroduction to programming by MUFIX Commnity
Introduction to programming by MUFIX Commnitymazenet
 
Introduction to Software - Coder Forge - John Mulhall
Introduction to Software - Coder Forge - John MulhallIntroduction to Software - Coder Forge - John Mulhall
Introduction to Software - Coder Forge - John MulhallJohn Mulhall
 
COMPUTING AND PROGRAMMING FUNDAMENTAL.pptx
COMPUTING AND PROGRAMMING FUNDAMENTAL.pptxCOMPUTING AND PROGRAMMING FUNDAMENTAL.pptx
COMPUTING AND PROGRAMMING FUNDAMENTAL.pptxSherinRappai1
 
COMPUTING AND PROGRAMMING FUNDAMENTAL.pptx
COMPUTING AND PROGRAMMING FUNDAMENTAL.pptxCOMPUTING AND PROGRAMMING FUNDAMENTAL.pptx
COMPUTING AND PROGRAMMING FUNDAMENTAL.pptxSherinRappai
 
APP_All Five Unit PPT_NOTES.pptx
APP_All Five Unit PPT_NOTES.pptxAPP_All Five Unit PPT_NOTES.pptx
APP_All Five Unit PPT_NOTES.pptxHaniyaMumtaj1
 
1. OBJECT ORIENTED PROGRAMMING USING JAVA - OOps Concepts.ppt
1. OBJECT ORIENTED PROGRAMMING USING JAVA - OOps Concepts.ppt1. OBJECT ORIENTED PROGRAMMING USING JAVA - OOps Concepts.ppt
1. OBJECT ORIENTED PROGRAMMING USING JAVA - OOps Concepts.pptsagarjsicg
 
Object Oriented Programming Overview for the PeopleSoft Developer
Object Oriented Programming Overview for the PeopleSoft DeveloperObject Oriented Programming Overview for the PeopleSoft Developer
Object Oriented Programming Overview for the PeopleSoft DeveloperLee Greffin
 

Similar to ProgFund_Lecture_5_Recap_and_Case_Study-1.pdf (20)

Python training
Python trainingPython training
Python training
 
pythontraining-201jn026043638.pptx
pythontraining-201jn026043638.pptxpythontraining-201jn026043638.pptx
pythontraining-201jn026043638.pptx
 
Programming Language
Programming  LanguageProgramming  Language
Programming Language
 
Oop.pptx
Oop.pptxOop.pptx
Oop.pptx
 
DOC-20210303-WA0017..pptx,coding stuff in c
DOC-20210303-WA0017..pptx,coding stuff in cDOC-20210303-WA0017..pptx,coding stuff in c
DOC-20210303-WA0017..pptx,coding stuff in c
 
part 1 - intorduction data structure 2021 mte.ppt
part 1 -  intorduction data structure  2021 mte.pptpart 1 -  intorduction data structure  2021 mte.ppt
part 1 - intorduction data structure 2021 mte.ppt
 
c#.pptx
c#.pptxc#.pptx
c#.pptx
 
Se 381 - lec 26 - 26 - 12 may30 - software design - detailed design - se de...
Se 381 - lec 26  - 26 - 12 may30 - software design -  detailed design - se de...Se 381 - lec 26  - 26 - 12 may30 - software design -  detailed design - se de...
Se 381 - lec 26 - 26 - 12 may30 - software design - detailed design - se de...
 
Cs2305 programming paradigms lecturer notes
Cs2305   programming paradigms lecturer notesCs2305   programming paradigms lecturer notes
Cs2305 programming paradigms lecturer notes
 
Lesson 1 of c programming algorithms and flowcharts.pptx
Lesson 1 of c programming algorithms and flowcharts.pptxLesson 1 of c programming algorithms and flowcharts.pptx
Lesson 1 of c programming algorithms and flowcharts.pptx
 
0-IntroductionToDSA.ppt
0-IntroductionToDSA.ppt0-IntroductionToDSA.ppt
0-IntroductionToDSA.ppt
 
Ch1 language design issue
Ch1 language design issueCh1 language design issue
Ch1 language design issue
 
Introduction To Programming (2009 2010)
Introduction To Programming (2009 2010)Introduction To Programming (2009 2010)
Introduction To Programming (2009 2010)
 
Introduction to programming by MUFIX Commnity
Introduction to programming by MUFIX CommnityIntroduction to programming by MUFIX Commnity
Introduction to programming by MUFIX Commnity
 
Introduction to Software - Coder Forge - John Mulhall
Introduction to Software - Coder Forge - John MulhallIntroduction to Software - Coder Forge - John Mulhall
Introduction to Software - Coder Forge - John Mulhall
 
COMPUTING AND PROGRAMMING FUNDAMENTAL.pptx
COMPUTING AND PROGRAMMING FUNDAMENTAL.pptxCOMPUTING AND PROGRAMMING FUNDAMENTAL.pptx
COMPUTING AND PROGRAMMING FUNDAMENTAL.pptx
 
COMPUTING AND PROGRAMMING FUNDAMENTAL.pptx
COMPUTING AND PROGRAMMING FUNDAMENTAL.pptxCOMPUTING AND PROGRAMMING FUNDAMENTAL.pptx
COMPUTING AND PROGRAMMING FUNDAMENTAL.pptx
 
APP_All Five Unit PPT_NOTES.pptx
APP_All Five Unit PPT_NOTES.pptxAPP_All Five Unit PPT_NOTES.pptx
APP_All Five Unit PPT_NOTES.pptx
 
1. OBJECT ORIENTED PROGRAMMING USING JAVA - OOps Concepts.ppt
1. OBJECT ORIENTED PROGRAMMING USING JAVA - OOps Concepts.ppt1. OBJECT ORIENTED PROGRAMMING USING JAVA - OOps Concepts.ppt
1. OBJECT ORIENTED PROGRAMMING USING JAVA - OOps Concepts.ppt
 
Object Oriented Programming Overview for the PeopleSoft Developer
Object Oriented Programming Overview for the PeopleSoft DeveloperObject Oriented Programming Overview for the PeopleSoft Developer
Object Oriented Programming Overview for the PeopleSoft Developer
 

More from lailoesakhan

ProgPrinc_Lecture_3_Data_Structures_and_Iteration-2.pdf
ProgPrinc_Lecture_3_Data_Structures_and_Iteration-2.pdfProgPrinc_Lecture_3_Data_Structures_and_Iteration-2.pdf
ProgPrinc_Lecture_3_Data_Structures_and_Iteration-2.pdflailoesakhan
 
ProgFund_Lecture_2_Data_Types_and_Selection-1.pdf
ProgFund_Lecture_2_Data_Types_and_Selection-1.pdfProgFund_Lecture_2_Data_Types_and_Selection-1.pdf
ProgFund_Lecture_2_Data_Types_and_Selection-1.pdflailoesakhan
 
ProgFund_Lecture_3_Data_Structures_and_Iteration-1.pdf
ProgFund_Lecture_3_Data_Structures_and_Iteration-1.pdfProgFund_Lecture_3_Data_Structures_and_Iteration-1.pdf
ProgFund_Lecture_3_Data_Structures_and_Iteration-1.pdflailoesakhan
 
ProgFund_Lecture_6_Files_and_Exception_Handling-3.pdf
ProgFund_Lecture_6_Files_and_Exception_Handling-3.pdfProgFund_Lecture_6_Files_and_Exception_Handling-3.pdf
ProgFund_Lecture_6_Files_and_Exception_Handling-3.pdflailoesakhan
 
ProgFund_Lecture_4_Functions_and_Modules-1.pdf
ProgFund_Lecture_4_Functions_and_Modules-1.pdfProgFund_Lecture_4_Functions_and_Modules-1.pdf
ProgFund_Lecture_4_Functions_and_Modules-1.pdflailoesakhan
 
ProgFund_Lecture_7_Intro_C_Sequence.pdf
ProgFund_Lecture_7_Intro_C_Sequence.pdfProgFund_Lecture_7_Intro_C_Sequence.pdf
ProgFund_Lecture_7_Intro_C_Sequence.pdflailoesakhan
 
ProgFund_Lecture_1_Introduction_to_Programming.pdf
ProgFund_Lecture_1_Introduction_to_Programming.pdfProgFund_Lecture_1_Introduction_to_Programming.pdf
ProgFund_Lecture_1_Introduction_to_Programming.pdflailoesakhan
 
ProgFund_Lecture7_Programming_Algorithm.pdf
ProgFund_Lecture7_Programming_Algorithm.pdfProgFund_Lecture7_Programming_Algorithm.pdf
ProgFund_Lecture7_Programming_Algorithm.pdflailoesakhan
 

More from lailoesakhan (8)

ProgPrinc_Lecture_3_Data_Structures_and_Iteration-2.pdf
ProgPrinc_Lecture_3_Data_Structures_and_Iteration-2.pdfProgPrinc_Lecture_3_Data_Structures_and_Iteration-2.pdf
ProgPrinc_Lecture_3_Data_Structures_and_Iteration-2.pdf
 
ProgFund_Lecture_2_Data_Types_and_Selection-1.pdf
ProgFund_Lecture_2_Data_Types_and_Selection-1.pdfProgFund_Lecture_2_Data_Types_and_Selection-1.pdf
ProgFund_Lecture_2_Data_Types_and_Selection-1.pdf
 
ProgFund_Lecture_3_Data_Structures_and_Iteration-1.pdf
ProgFund_Lecture_3_Data_Structures_and_Iteration-1.pdfProgFund_Lecture_3_Data_Structures_and_Iteration-1.pdf
ProgFund_Lecture_3_Data_Structures_and_Iteration-1.pdf
 
ProgFund_Lecture_6_Files_and_Exception_Handling-3.pdf
ProgFund_Lecture_6_Files_and_Exception_Handling-3.pdfProgFund_Lecture_6_Files_and_Exception_Handling-3.pdf
ProgFund_Lecture_6_Files_and_Exception_Handling-3.pdf
 
ProgFund_Lecture_4_Functions_and_Modules-1.pdf
ProgFund_Lecture_4_Functions_and_Modules-1.pdfProgFund_Lecture_4_Functions_and_Modules-1.pdf
ProgFund_Lecture_4_Functions_and_Modules-1.pdf
 
ProgFund_Lecture_7_Intro_C_Sequence.pdf
ProgFund_Lecture_7_Intro_C_Sequence.pdfProgFund_Lecture_7_Intro_C_Sequence.pdf
ProgFund_Lecture_7_Intro_C_Sequence.pdf
 
ProgFund_Lecture_1_Introduction_to_Programming.pdf
ProgFund_Lecture_1_Introduction_to_Programming.pdfProgFund_Lecture_1_Introduction_to_Programming.pdf
ProgFund_Lecture_1_Introduction_to_Programming.pdf
 
ProgFund_Lecture7_Programming_Algorithm.pdf
ProgFund_Lecture7_Programming_Algorithm.pdfProgFund_Lecture7_Programming_Algorithm.pdf
ProgFund_Lecture7_Programming_Algorithm.pdf
 

Recently uploaded

Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdfKamal Acharya
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Bookingdharasingh5698
 
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...Call Girls in Nagpur High Profile
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordAsst.prof M.Gokilavani
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxupamatechverse
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingrakeshbaidya232001
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingrknatarajan
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations120cr0395
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxfenichawla
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxupamatechverse
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Christo Ananth
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSSIVASHANKAR N
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdfKamal Acharya
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdfankushspencer015
 

Recently uploaded (20)

Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdf
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
 
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptx
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writing
 
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
 
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINEDJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
 
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptx
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
 

ProgFund_Lecture_5_Recap_and_Case_Study-1.pdf

  • 1. Programming Fundamentals Lecture 5: Recap and Case Study
  • 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
  • 26. “Test Generator” – Example Tests Addition Test Name: ___________ 2 + 4 = ____ 6 + 5 = ____ 1 + 8 = ____ 9 + 2 = ____ 5 + 4 = ____ 6 + 4 = ____ 7 + 2 = ____ 5 + 3 = ____ 2 + 1 = ____ 9 + 7 = ____ Subtraction Test Name: __________ 7 - 5 = ____ 8 - 6 = ____ 2 - 2 = ____ 9 - 6 = ____ 5 - 1 = ____ 4 - 0 = ____ 9 - 7 = ____ 6 - 4 = ____ 9 - 1 = ____ 9 - 5 = ____ 27
  • 27. “Test Generator” – Version 1 Pseudocode Pseudocode 28
  • 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
  • 29. “Test Generator” – Version 2 Pseudocode 30 Pseudocode
  • 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
  • 31. “Test Generator” – Version 3 Pseudocode 32 Pseudocode
  • 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