0% found this document useful (0 votes)
65 views

Unit 2 Programming Notes

An algorithm is a step-by-step procedure for solving a problem, while programming is implementing an algorithm using instructions for a computer. Variables in algorithms store values and can control loops, branches, and totals. Programs specify variable data types like integers and strings. Selection uses if/else statements, while iteration repeats with loops. Validation checks input data. Subprograms reuse code through functions and procedures. Testing identifies logic, syntax, and runtime errors to evaluate programs.

Uploaded by

devika suresh
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
65 views

Unit 2 Programming Notes

An algorithm is a step-by-step procedure for solving a problem, while programming is implementing an algorithm using instructions for a computer. Variables in algorithms store values and can control loops, branches, and totals. Programs specify variable data types like integers and strings. Selection uses if/else statements, while iteration repeats with loops. Validation checks input data. Subprograms reuse code through functions and procedures. Testing identifies logic, syntax, and runtime errors to evaluate programs.

Uploaded by

devika suresh
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 23

Unit 2 programming notes:

Develop code
Difference between algorithms and programs

 Algorithm – is a step-by-step procedure for solving a problem (detailed design for a solution)
 Programming – is a set of instructions for a computer to follow to perform a task (implementation of
that design)

Data types

Like water in cup

=data =variable  needed to store the water

Algorithms use variables (named memory locations) to store values, variables have a variety of uses:

 controlling the number of times a loop is executed


 determining which branch of an IF statement is taken
 keeping running totals
 holding user input

When algorithms are converted into programs, the computer needs to be told what type of data is stored in each
variable.

(Python does not use character data type)

In pseudocode don’t need to specific data type of variables but you do in high-programming languages like python.

Variable initialization

1. initially, variable location is empty


2. When a variable is declared, the computer gives it a location in its memory to be used as it has to be given a
value
Pseudocode for putting initial value into a variable:

1. SET total TO 0
2. RECEIVE admissionCharge FROM (INTEGER) KEYBOARD

The variable’s value can then be changed by an assignment statement:

SET total TO total + admissionCharge

If variable is a loop counter and needs to hold a running total:

Always initialize starting value then,

Total=0

Total = total + admisisonCharge

Type coercion

Converting from one data type to another

In python, this is automatic, e.g.:

X=1

Y = 2.25

Z = x+y

Print (z)

Explicit type coercion is (int (input(…))

Command sequence, selection and iteration

5/3= 1.66

5%3=2 (MOD, without reminder)

5//2=1 (DIV, quotient)

Exponential = **

Sequence

Orderly, if:

A=10, b=10, c=a+b, one after the other


Selection

To create a branch based on the outcome of a condition using: if, elif, else

If more than 2 outcomes, then use nested IF statement

Relational operators

Logical operators

Iteration/ loops

Repeat again and again

2 types of loops: definite and indefinite

Definite iteration (FOR)

= know how many times loop should be repeated.

e.g.: take 5 steps forward

pseudocode is REPEAT… END REPEAT and FOR… END FOR


Nested loops (used for FOR)

Loop in a loop

Before loop, initialize variable total to zero.

Indefinite iteration (WHILE)

Repeat until specific condition is reached, e.g.: steps until wall

Random numbers
Making programs easy to read
Code readability

Strings
String indexing

to 16 cuz goes from 0 to 15

first character is 0

length

len (variable)

String traversal

Using FOR loop, you can display letter by letter on separate lines.
Other ways to manipulate strings

Finding a character with a particular index

Chancing all characters to lower/upper case

Variable = variable.lower() or Variable = variable.upper()

Extracting characters from a string (slicing)


Checking a phrase in the string

Concatenation

+, 2 variables together

Comparing strings

Use ==

Data structures
Collection of items  arrays [same datatype] or records [for 2 or more diff datatype]

But in python  list either way


Arrays

► Data should be classified and organized into similar types to easily search and analyze. This is done by storing
together in data structures like records or arrays.
► There are many different data structures that can store multiple data items: strings, arrays and records.
► Pseudocode for array --? SET, e.g.: SET firstNames TO [‘Ashura’, ‘Bryn’, ‘Eloise’, ‘Mei’]
► Most are static arrays (fixed size and holds declared number of items which needs to be stated) e.g.: ,array
friends [5]
► to find length of myArray do len(myArray)

In python

► arrays not commonly used, instead use lists with comma to separate and inside square brackets.
► Lists are easier to use as they are dynamic – can add new elements as size not declared, e.g.: cars: [ ]

To add to the empty list  append  added to end of list:

cars = [ ]

cars.append (‘Audi’)

print (cars)

[‘Audi’]

Another advantage is items don’t need to be same data type:

cars = [ ]

cars.append(‘Audi’)

cars.append(3)

print(cars)

[‘Audi’, 3]

Can manipulate arrays in 3 ways:

max( )

x = max(5,2,11,10)

print(x)

you get 11

min( )

x = min(5,2,11,10)

print(x)
you get 2

slice( )

b = "Hello, World!"

print(b[2:5])

you get ‘llo’

multidimensional arrays

list inside a list, ‘array of arrays’

first row then column

e.g.:

marks = [[80,59,34,89], [31,11,47,64], [29,56,13,91]]

E.g: examResults [1][2] (not [1,2] ) is 47

results = [[‘Smith’, 69], [‘Jackson’, 90], [‘Dubois’, 30]]

for index in range(0, len(results)):

if results[index][1] >= 50:

print(results[index][0] + str(results[index][1]))

In Python each element is written as results[0][1] and not results[0, 1].

Records

Each element in a record is known as a field and is referenced using a field name.

All the values in a column have the same data type – learnerNum and ‘age’ are integers; firstName, lastName and ‘form’
are strings.
Input/ output
User input

A program can be made much more ‘user friendly’ by displaying helpful messages informing users of what they are
expected to enter and confirming successful input.

Validation

Invalid data can cause the program to behave unexpectedly or stop or output would be wrong --‘garbage in, garbage
out (GIGO) principle’

Validation can’t guarantee data entered is correct but can only make sure data is reasonable.

4 types of checks:

Range check

Checks if data is within given range

The Boolean variable is named validNum as a status flag – to initially set to False

WHILE loop runs until validNum is equal to True

IF statement deternmies if the value of validNum should be set to True

Presence check

Checks if we type everything to stop leaving input blank


Look-up check

If enters something not in list  error

Has to be in the predefined set of acceptable values.

Length check

Like passwords need a certain length


Testing validation rules

Normal data - This is data that is within the limits of what should be accepted by the program.

Boundary data - This is data that is at the outer limits of what should be accepted by the program. For example, if a
validation rule specifies that the range of acceptable values is >= 75 AND <= 100, then a value of 100 is at the upper limit
and a value of 75 at the lower.

Erroneous data – (not valid) This is data that should not be accepted by the program. For example, a value of 0 should
not be accepted by either of the validation rules given above.

Working with text files

To access a text file, you must first give it a file handle, e.g. myFile

The following program would create a text file called ‘names’ and add two items of data.
Writing to a file
Subprograms
Write it once, use it many times  can reuse code  def variable ( )

Functions
Local and global variables

Procedures

Unlike a function, a procedure does not return a value to the main program.
Arguments and parameters

Parameters – are the input value that you pass to the function

def is the function header

Argument  when received – then called parameter


Subprograms and menus

Functions and procedures are useful when using menus in a program. When a user selects a menu option, they can be
sent to a particular function or procedure.
The benefits of using subprograms

Repeated sections of code only need to be written once  shortens development time  means finished program will
occupy less memory space when it is run

Also easier to read, less complicated, can debug program

Built-in functions

These are already written by python to make it easier for high-level programmers like print, count the number of
characters in a string and generate random numbers.

Testing and evaluation


To reduce as many mistakes and errors, a program should be tested and evaluated.

Logic errors
Ideally should be fixed at design stage, it occurs when the thinking behind an algorithm is incorrect so the output isnt
what is expected or intended.

Computer has no sense to find error  program will run but the desired result won’t be achieved.

This is a logic error because it is an infinite loop as it will never reach 10.

Trace tables
Syntax errors

Misspelled

E,g: missing out closing brackets, missing out quotation marks, writing ‘prnit’ instead of ‘print’

Runtime errors

Most difficult to predict and spot as they occur during program execution

Like /0 wont work

Using an integrated development environment (IDE)

The program used to program – IDLE – not word as it si not suitable

One of the most useful features is the debugger as it can flag up syntax errors.
The test plan

Table  say what we expect  test to see if output same

The test plan:


If nothing went wrong then write ‘None’ for ‘action needed/comments’.

The test data categories:

It is important to use ‘bottom up’ testing e.g.: test each subprogram as you develop it and then test the whole program
once it is finished

This is the completed test plan for the grade calculator program:
Evaluating programs

You need to identify strengths and weaknesses to identify techniques that work and aspects that can be improved.

You might also like