Lecture 6 –
Individual research task. You should all have completed the research task set
last week.
Please make sure you hand it in today.
Previously Decision structures with flowcharts
Boolean logic
UML and brief introduction.
Today Iteration
Date and time structures
Modularisation
Pseudo code
Iteration - loops
“If you cannot understand the overall structure of a program while taking a shower (no external memory aids), you are not ready to code it”
Rich Pattis
Types of loop CONCEPT:
A repetition structure causes a statement or set of statements to execute repeatedly.
Types of loop - definite loop definite loop: A loop that executes a known number
of times.
Also know as a Count-Controlled Loop.
for definite loops. We often use language like "repeat _ times" or "for each of these things".
– Examples:
Repeat these statements 10 times.
Repeat these statements n times.
Repeat these statements for each odd number between 5 and 27.
Types of loop - indefinite loop Indefinite loop: A loop where it is not easily determined
in advance how many times it will execute.
Also known as a Condition-Controlled loop.
Indefinite loops often keep looping as long as a condition is true, or until a condition becomes false.
Examples:
Repeat these statements until the user types a valid integer.
Repeat these statements while the number is not prime.
Repeat these statements until a factor of is found.
Flip a coin until you get 10 flips in a row of the same result
While loop The diamond
symbol represents the condition that is tested. Notice what happens if the condition is true: one or more statements are executed and the program’s execution flows back to the point just above the diamond symbol
While loop Here is the general
format of the while loop in Python:
while condition:
statement
statement
etc.
While loop Now do Lab 06 program Commission.py
In line 4 we use an assignment statement to create a variable named keep_going. Notice that the variable is assigned the value 'y'. This initialization value is important.
Without this the loop would never run.
This while loop was a pre-check loop.
The for loop The for loop is a Count-Controlled Loop.
CONCEPT: A count-controlled loop iterates a specific number of times.
In Python you use the for statement to write a count-controlled loop.
Count-controlled loops are commonly used in programs.
The for loop In Python, the for statement is designed to work with a
sequence of data items. When the statement executes, it iterates once for each item in the sequence.
Here is the general format:
for variable in [value1, value2, etc.]:
statement
statement
etc.
We will be looking at lists later in the course.
List in Python, a type of array but
much better.
The for loop – try this # This program demonstrates a simple for loop
# that uses a list of numbers.
def main():
print('I will display the numbers 1 through 5.')
for num in [1, 2, 3, 4, 5]:
print(num)
# Call the main function.
main()
The for loop How it works:
The for loop, strings work too! Try this one – simple_loop using strings
# This program also demonstrates a simple for
# loop that uses a list of strings.
def main():
for name in ['Winken', 'Blinken', 'Nod']:
print(name)
# Call the main function.
main()
Dates and Times How to find out the current date and time in Python? What is the module or function I need to use to get current time or date in Python programming language?
You need to use the datetime module in Python. It provides classes (OOP) for manipulating dates and times in both simple and complex ways. While date and time arithmetic is supported, the focus of the implementation is on efficient attribute extraction for output formatting and manipulation.
Date and time are very common in programs.
Dates and Times Try this
import time
print (time.strftime("%H:%M:%S"))
## 12 hour format
## print (time.strftime("%I:%M:%S"))
The import statement is how you identify external libraries to use with your program.
Dates and Times Now try this
import time
now = time.strftime("%c")
## date and time representation
print "Current date & time " + time.strftime("%c")
## Only date representation
print "Current date " + time.strftime("%x")
## Only time representation
print "Current time " + time.strftime("%X")
## Display current date and time from now variable
print ("Current time %s" % now )
Dates and Times Now do Date_and_time.py in lab06.
This uses the date time module.
The syntax is -
now = datetime.datetime.now()
now.hour
now.mintue
now.year
now.day
now.month
Modularisation Modularity is generally desirable, especially in large, complicated programs.
Modular programming is a software design technique that emphasizes separating the functionality of a program into independent, interchangeable modules, such that each contains everything necessary to execute only one aspect of the desired functionality. http://en.wikipedia.org/wiki/Modular_programming
Modularisation in Python CONCEPT: A module is a file that contains Python code. Large programs are easier to debug and maintain when they are divided into modules.
When you break a program into modules, each module should contain functions that perform related tasks.
Modularisation in Python An example, suppose you are writing an accounting system. You would store all of the account receivable
functions in their own module, all of the account payable functions in their own module, and all of the payroll functions in their own module.
This approach, which is called modularization, makes the program easier to understand, test, and maintain.
Modularisation in Python Modules also make it easier to reuse the same code in more than one program.
If you have written a set of functions that are needed in several different programs, you can place those functions in a module.
Then, you can import the module in each program that needs to call one of the functions.
In Python each module is a separate file.
Modularisation in Python Some rules to bear in mind. A module’s file name should end in .py. If the module’s file name does not end in .py you will not be able to import it into other programs. A module’s name cannot be the same as a Python key word. An error would occur, for example, if you named a module for. To use these modules in a program, you import them with the import statement. Here is an example of how we would import a circlemodule: import circle When the Python interpreter reads this statement it will look for the file circle.py in the same folder as the program that is trying to import it. If it finds the file it will load it into memory. If it does not find the file, an error occurs.
Modularisation in Python Do the lab06 exercise on Modules.
Pseudo code Pseudocode is an informal high-level description of the operating principle of a computer program or other algorithm.
It uses the structural conventions of a programming language, but is intended for human reading rather than machine reading. Pseudocode typically omits details that are not essential for human understanding of the algorithm, such as variable declarations, system-specific code and some subroutines. http://en.wikipedia.org/wiki/Pseudocode
Pseudo code The rules of Pseudocode are reasonably straightforward.
All statements showing "dependency" are to be indented.
These include while, do, for, if, switch.
Pseudo code Examples:
1. If student's grade is greater than or equal to 60 Print "passed"
else Print "failed"
2. Set total to zero
Set grade counter to one
While grade counter is less than or equal to ten
Input the next grade
Add the grade into the total
Set the class average to the total divided by ten
Print the class average.
Pseudo code – keywords to use For looping and selection, The keywords that are to be
used include
Do While...EndDo; Do Until...Enddo; Case...EndCase; If...Endif; Call ... with (parameters); Call; Return ....; Return; When;
Always use scope terminators for loops and iteration.
As verbs, use the words Generate, Compute, Process, etc. Words such as set, reset, increment, compute, calculate, add, sum, multiply, ... print, display, input, output, edit, test , etc. with careful indentation tend to foster desirable pseudocode.
Do not include data declarations in your pseudocode.
Summary what we have done today -
Iteration
Date and time structures
Modularisation
Pseudo code
Now complete the lab work It is on the WIKI
There is no research this week.
Next Time Reading and writing files.