0% found this document useful (0 votes)
3 views108 pages

Pseudocode & Python - 14

The document provides an overview of programming concepts in Python, including operators, variables, constants, data types, and input/output statements. It explains the differences between pseudocode and Python syntax, along with examples for variable declaration, initialization, type coercion, and selection statements. Additionally, it includes practice questions to reinforce understanding of these concepts.

Uploaded by

Ayesha Riaz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as ODP, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views108 pages

Pseudocode & Python - 14

The document provides an overview of programming concepts in Python, including operators, variables, constants, data types, and input/output statements. It explains the differences between pseudocode and Python syntax, along with examples for variable declaration, initialization, type coercion, and selection statements. Additionally, it includes practice questions to reinforce understanding of these concepts.

Uploaded by

Ayesha Riaz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as ODP, PDF, TXT or read online on Scribd
You are on page 1/ 108

PSEUDOCODE

& PYTHON
Computer Science Edexcel (9-1)
TOPIC 5: DEVELOP CODE
OPERATORS

and AND in python


or OR in python
not NOT in python
!= Not equal to in
Python
== Is equal to?

% MOD in Python

// DIV in Python

** Exponent in Python
VARIABLES & CONSTANTS
Variable:
It is a memory location which is used to store data during the
execution of a program. It has a fixed data type and a
meaningful name. It’s value can be changed throughout the
code.

Constant:
It is a memory location which is used to store data during the
execution of a program. It has a fixed data type and a
meaningful name. Once created and allotted a value, It’s value
cannot be changed throughout the code.
DATA TYPES
Python

int

float

bool

(str with 1
character)

str
DECLARATION(CREATION) OF VARIABLES & CONSTANTS
VARIABLE
Pseudocode Python
Syntax DataType VariableName There is no need to Declare / Create
Explanatio Creates a variable of the mentioned data type and variables in Python with a set data
n name type.
Example INTEGER age
REAL weight In python, variables are
BOOLEAN correct automatically created once they are
CHARCHTER age
CONSTANT initialized
Pseudocode Python
Syntax CONST DataType ConstantName There is no concept of a CONSTANT in
Explanatio Python
Creates a constant of the mentioned data type
n
Example CONST INTEGER age If a fixed value has to be stored, its
CONST REAL PI stored in a variable and programmer has
CONST BOOLEAN correct to remember it on his own
CONST CHARCHTER age
INITIALIZATION(STARTING) OF VARIABLES & CONSTANTS

Pseudocode Python
Syntax SET Variable TO <value> Variable = <value>
Explanatio
Assigns a value to a variable. Assigns a value to a variable.
n
Example SET Counter TO 0 Counter = 0
SET MyString TO ‘Hello world’ MyString = ‘Hello World’

Pseudocode Python
Syntax SET Variable TO <expression> Variable = <expression>
Explanatio Computes the value of an expression Computes the value of an expression and
n and assigns to a variable. assigns to a variable.
Example SET Sum TO Score + 10 Sum = Score + 10
SET Size to LENGTH(Word) Size = LENGTH(Word)
TYPE COERCION
Type Coercion means to change the data type of a variable
Pseudocode Python
Syntax SET <NewVariable> TO <NewVariable> =
<NewDataType>(<variable>) <NewDataType>(<variable>)
Explanatio Changes the data type of <variable> to
Changes the data type of <variable> to
n <NewDataType> and saves in
<NewDataType> and saves in <NewVaraible>
<NewVaraible>
Example SET Age TO 17 Age = 17
SET Name TO ‘Ali’ Name = ‘Ali’
SET NumString TO ‘546’ NumString = ‘546’
SET GPA TO‘3.4’ GPA = 3.4

SET NewAge TO float(Age) NewAge = float(Age)


SET NewAge2 TO str(Age) NewAge2 = str(Age)
SET Num TO int(NumString) Num = int(NumString)
SET Num2 TO float(NumString) Num2 = float(NumString)
SET NewGPA TO int(GPA) NewGPA = int(GPA)
SET NewGPA2 TO str(GPA) NewGPA2 = str(GPA)
SET NewName TO int(Name) NewName = int(Name)
SET NewName2 TO float(Name) NewName2 =float(Name)

Result NewAge NewAge2 Num Num2 NewGPA NewGPA2 NewName NewName2


TYPE COERCION
PRACTICE QUESTIONS
Q1. Declare five variables with suitable datatypes and meaningful names to store your name, age,
gender (M or F), weight, and status of your mood whether its happy or not. Code the same in python.

Q2. Declare 3 variables to store the price, availability and name of the product and a constant to
store the discount. Initialize the price with 500, availability with YES and name of product Cola Next.
The discount offered is of 25.5 rupees. Code the same in python.
PRACTICE QUESTIONS
Q1. Declare five variables with suitable datatypes and meaningful names to store your name, age,
gender (M or F), weight, and status of your mood whether its happy or not. Code the same in python.

PSEUDOCODE

STRING Name
INTEGER Age PYTHON
REAL Weight
CHARACTER Gender Name = ‘Ubair Khan’
BOOLEAN Happy Age = 29
Weight = 63.5
SET Name TO ‘Ubair Khan’ Gender = ‘M’
SET Age TO 29 Happy = YES
SET Weight TO 63.5
SET Gender TO ‘M’
SET Happy TO YES

Q2. Declare 3 variables to store the price, availability and name of the product and a constant to
store the discount. Initialize the price with 500, availability with YES and name of product Cola Next.
The discount offered is of 25.5 rupees. Code the same in python.
PRACTICE QUESTIONS
Q2. Declare 3 variables to store the price, availability and name of the product and a constant to
store the discount. Initialize the price with 500, availability with YES and name of product Cola Next.
The discount offered is of 25.5 rupees. Code the same in python.

PSEUDOCODE

STRING Prodcut_Name PYTHON


INTEGER Price
BOOLEAN Availible Product_Name = ‘Cola
CONST REAL Discount Next’
Price = 500
SET Prodcut_Name TO ‘Cola Available = YES
Next’ Discount = 25.5
SET Price TO 500
SET Availability TO YES
SET Discount TO 25.5
INPUT
INPUT STATEMENTS:
/ OUTPUT STATEMENTS
Takes / Receives / Reads data of mentioned datatype from the user and saves in a
variable/identifier
Input can also be taken without mentioning datatype of the data being received (NOT
RECOMMENDED)
• In pseudocode, it is also important to specify the device from where input is being
received. Pseudocode Python
• In python, there is no need to specify the device.
Syntax Without mentioning datatype:
Without mentioning datatype:
RECEIVE <variable> FROM <device>
Variable = input()
With mentioning datatype:
With mentioning datatype:
RECEIVE <variable> FROM (datatype)
Variable = datatype(input())
<device>
Exampl RECEIVE Name FROM KEYBOARD Name = input()
e RECEIVE Name FROM (STRING) KEYBOARD Name = str(input())
RECEIVE AccountNum FROM CARD_READER AccountNum = input()
RECEIVE AccountNum FROM (INTEGER)
CARD_READER
AccountNum = int(input())
INPUT
OUTPUT STATEMENTS:
/ OUTPUT STATEMENTS
Gives / Sends data output to the screen.
Data can be a variable, a number, an expression etc.
• In pseudocode, it is also important to mention to where output is being sent.
• In python, there is no need to mention that
• In python, a single output statement can be used to give multiple data as outputs
Pseudocode Python
Syntax
print (<data>)
SEND <data> TO DISPLAY
print (<data1>,<data2>,<data3>)

Exampl print (Total_Marks)


SEND Total_Marks TO DISPLAY
e
print (‘Have a good day.’,6754)
SEND ‘Have a good day.’ TO DISPLAY
print (Total_Marks, ‘Have a goo
SEND 6754 TO DISPLAY
day.’,6754)
INPUT / OUTPUT STATEMENTS
INPUT + OUTPUT COMBINED STATEMENTS:
• In python, an input statement can ALSO contain an output
• This output is usually a prompt to tell the user what to enter as input
• Using this combined statements save coding time and space
• It is absolutely fine not to use this input+output combined statement but it’s a good
practice to do so
Example: Suppose you want to ask the user to enter his age and then take
his age as input,
print (‘Enter your age’ )
age = integer (input())

This can be written in a single line using combined statement

age = int ( input (‘Enter your age’) )


PRACTICE QUESTIONS
Q3. Take 2 numbers as input. Add them and store the result in a variable and output the result with
an appropriate message. Code the same in python.

Q4. Take 3 numbers as input. Two of these numbers must be of integer data type and one of real/float
data type. Calculate their average and store the result in a variable and output the result with an
appropriate message. Code the same in python.
PRACTICE QUESTIONS
Q3. Take 2 numbers as input. Add them and store the result in a variable and output the result with
an appropriate message. Code the same in python.

PSEUDOCODE PYTHON

RECEIVE Num1 FROM Keyboard Num1 = input()


RECEIVE Num2 FROM Keyboard Num2 = input()

SET Sum TO Num1 + Num2 Sum = Num1 + Num2

SEND ‘Result is’ TO DISPLAY print (‘Result is:’ , Sum)


SEND Sum TO DISPLAY
PRACTICE QUESTIONS
Q4. Take 3 numbers as input. Two of these numbers must be of integer data type and one of real/float
data type. Calculate their average and store the result in a variable and output the result with an
appropriate message. Code the same in python.
PSEUDOCODE PYTHON

RECEIVE Num1 FROM (INTEGER) Num1 = integer(input())


Keyboard Num2 = integer(input())
RECEIVE Num2 FROM (INTEGER) Num3 = float(input())
Keyboard
RECEIVE Num3 FROM (REAL) Keyboard Sum = Num1 + Num2 + Num3
Avg = Sum / 3
SET Sum TO Num1 + Num2 + Num3
SET Avg TO Sum/3 print (‘Average is:’ , Avg)

SEND ‘Average is’ TO DISPLAY


SEND Avg TO DISPLAY
SELECTION STATEMENTS
SELECTION STATEMENT – IF..THEN..ENDIF:
A selection statement executes the commands on the basis of a given
condition/expression
• If the condition is true, the mentioned commands are executed and if its not, nothing
happens.
Pseudocode Python
Syntax IF <expression> THEN
if <expression> :
<command>
<command>
END IF
Explanatio If <expression> is true then command is If <expression> is true then command is
n executed. executed.
Example
IF Answer = 10 THEN
if Answer = 10 :
SET Score TO Score + 1
score = score + 1
END IF
SELECTION STATEMENTS
SELECTION STATEMENT – IF..THEN..ENDIF:
A selection statement executes the commands on the basis of a given
condition/expression
• If the condition is true, the mentioned commands are executed and if its not, nothing
happens.
• It is also possible specify Pseudocode Python
commands which will be executed if the condition is false.
Syntax IF <expression> THEN
if <expression> :
<command1>
<command1>
ELSE
else:
<command2>
<command2>
END IF
Explanatio If <expression> is true then If <expression> is true then
n <command1> is executed, otherwise <command1> is executed, otherwise
<command2> is executed. <command2> is executed.
Example IF Marks > 70 THEN
if Marks > 70 :
SEND ‘Well done’ TO DISPLAY
print (‘Well Done’)
ELSE
else:
SEND ‘Try again’ TO DISPLAY
print (‘Try again’)
END IF
SELECTION
NESTED IF STATEMENT:
STATEMENTS
A nested IF statement is an IF statement which has multiple conditions/expressions. If first
specified expression is false, then it checks for the next mentioned condition and if that’s
false too, program proceeds towards the next condition and so on.
Pseudocode Python
Syntax IF <expression1> THEN
if <expression1> :
<command>
<command>
ELSE IF <expression2> THEN
elif <expression2> :
<command>
<command>
ELSE IF <expression3> THEN
elif <expression3> :
<command>
<command>
ELSE <command>
else: <command>
END IF
Example IF Bill >= 5000 THEN
if Bill > = 5000:
SET Discount TO 500
Discount = 500
ELSE IF Bill >= 3000 THEN
elif Bill>=3000:
SET Discount TO 300
Discount = 300
ELSE IF Bill >= 1000 THEN
elif Bill>=1000:
SET Discount TO 100
Discount = 100
ELSE SET Discount TO 0
else: Discount = 0
END IF
PRACTICE QUESTIONS
Q5. Write a pseudocode that takes the age of a child as an input and if its above 12, displays that the
child is allowed to enter the ride. Code the same using python.

Q6. Write a pseudocode which takes the marks of a students as input and tells if the student has
passed the exam or not. Code the same in python.

Q7. Write a pseudocode which takes the marks of the a student and displays the grade as per the
given grade policy. Code the same in python
Grade Policy:
90+ A*
80-89 A
60-79 B
50-59 C
Below 50 F

Q8. Write a pseudocode which takes three different numbers and displays the largest number with
suitable prompts. Code the same in python.
PRACTICE QUESTIONS
Q5. Write a pseudocode that takes the age of a child as an input and if its above 12, displays that the
child is allowed to enter the ride. Code the same using python.

PSEUDOCODE PYTHON

SEND “Enter Age: “ TO DISPLAY print (‘Enter age:’)


RECEIVE Age FROM (INTEGER) KEYBOARD Age = int(input())

IF Age > 12 THEN if Age>12:


SEND “Entry Allowed” TO DISPLAY print(‘Entry Allowed’)
END IF
PRACTICE QUESTIONS
Q6. Write a pseudocode which takes the marks of a students as input and tells if the student has
passed the exam or not. Code the same in python.

PSEUDOCODE PYTHON

SEND “Enter Marks: “ TO DISPLAY print (‘Enter marks:’)


RECEIVE Marks FROM (REAL) KEYBOARD Marks= real(input())

IF Marks >= 50 THEN if Marks>=50:


SEND “You’ve passed” TO DISPLAY print(‘You’ve passed’)
ELSE else:
SEND “You’ve failed” TO DISPLAY print(‘You’ve failed’)
END IF
PRACTICE QUESTIONS
Q7. Write a pseudocode which takes the marks of the a student and displays the grade as per the given grade
policy. Code the same in python. Grade Policy: 90+ A*, 80-89 A,60-79 B, 50-59 C, Below 50 F

PSEUDOCODE PYTHON

SEND “Enter Marks: “ TO DISPLAY print (‘Enter marks:’)


RECEIVE Marks FROM (REAL) KEYBOARD Marks= float(input())

IF Marks >= 90 THEN if Marks>=90:


SEND “A*” TO DISPLAY print(‘A*’)
ELSE IF Marks>=80 THEN elif Marks>=80:
SEND “A” TO DISPLAY print(‘A’)
ELSE IF Marks>=60 THEN elif Marks>=60:
SEND “B” TO DISPLAY print(‘B’)
ELSE IF Marks>=50 THEN elif Marks>=50:
SEND “C” TO DISPLAY print(‘A’)
ELSE else:
SEND “F” TO DISPLAY print(“F”)
END IF
END IF
END IF
END IF
PRACTICE QUESTIONS
Q8. Write a pseudocode which takes three different numbers and displays the largest number with
suitable prompts. Code the same in python.
PSEUDOCODE PYTHON

SEND “Enter three numbers“ TO DISPLAY print (‘Enter 3 different numbers:’)


RECEIVE Num1 FROM (INTEGER) KEYBOARD Num1= int(input())
RECEIVE Num2 FROM (INTEGER) KEYBOARD Num2= int(input())
RECEIVE Num3 FROM (INTEGER) KEYBOARD Num3= int(input())

IF Num1>Num2 AND Num1>Num3 THEN if Num1>Num2 AND Num1>Num3


SEND Num1 TO DISPLAY :
ELSE IF Num2>Num1 AND Num2>Num3 THEN print(Num1)
SEND Num2 TO DISPLAY elif Num2>Num1 AND
ELSE IF Num3>Num1 AND Num2>Num3 :
Num3>Num2 THEN print(Num2)
SEND Num3 TO DISPLAY elif Num3>Num1 AND
END IF Num3>Num2 :
END IF print(Num3)
END IF
LOOP STATEMENTS
LOOP /REPITION / ITERATION Statements:
A loop statement is used to repeat a set of statements/commands.
• There are two types of loop statements:
1. Definite Iterations / Count Controlled
2. Indefinite / Condition Controlled
Definite Loops / Count Controlled Loops Indefinite Loops / Condition Controlled Loops
When we exactly know for how many times When we don’t know how many times the
the commands have to be executed. commands have to be executed.

Pseudocode:
Pseudocode:
1. REPEAT..TIMES..END REPEAT
1. REPEAT…UNTIL
2. FOR..FROM..TO..DO..END FOR
2. WHILE..DO..ENDWHILE
3. FOR..FROM.. TO..STEP..DO..END FOR

Python:
1. for.. in range(X): Python:
2. for.. in range(X,Y): 1. while ():
3. for.. in range(X,Y,Z):
DEFINITE LOOPS / COUNT
CONTROLLED
PSEDUOCODES LOOP
<id> : A variable created by the loop and only exists in the loop
<X>, <Y>, <Z>: Numbers OR an integer type variable OR an expression which solves to result in a number
REPEAT..TIMES..END REPEAT FOR..FROM..TO..DO..ENDFOR FOR..FROM..TO..STEP..DO..ENDFOR
FOR <id> FROM <X> TO <Y> STEP
REPEAT <X> TIMES FOR <id> FROM <X> TO <Y> DO
<Z> DO
Syntax <commands> <commands>
<commands>
END REPEAT END FOR
END FOR
Repeats the <commands> for each value of Repeats the <commands> for the values of
<id> starting from X to Y. <id> from X to Y with <id> getting
• Starts with id=X increment of Z each time.
Repeats the • Executes the commands
Explana
tion <commands> for X • Increments the value of <id> by 1 • Starts with id=X
number of times. • Executes the commands again • Executes the commands
• Repeats the process till id=Y • Increments the value of <id> by Z
• If X=1, it simply repeats commands for Y • Executes the commands again
times • Repeats the process till <id> reaches Z-1
FOR index FROM 1 TO 3 DO FOR index FROM 1 TO 10 STEP 4 DO
REPEAT 4 TIMES
Exampl SEND ‘Loop Number: ‘ TO DISPLAY SEND ‘Loop Number: ‘ TO DISPLAY
e SEND ‘Wow A Loop!’
SEND index TO DISPLAY SEND index TO DISPLAY
END REPEAT
END FOR END FOR
Loop Number: Loop Number:
Wow A Loop! 1 1
Output
on
Wow A Loop! Loop Number: Loop Number:
Screen Wow A Loop! 2 5
Wow A Loop! Loop Number: Loop Number:
2 9
DEFINITE LOOPS / COUNT
CONTROLLED PYTHON LOOP
<id> : A variable created by the loop and only exists in the loop
<X>, <Y>, <Z>: Numbers OR an integer type variable

for.. in range(X): for.. in range(X,Y): for.. in range(X,Y,Z):


for <id> in
for <id> in range(<X>): for <id> in range(<X>,<Y>):
Syntax range(<X>,<Y>,<Z>):
<commands> <commands>
<commands>
Repeats the <commands> for X Repeats the <commands> for Repeats the <commands> for the
number of times; for each value of each value of <id> starting from values of <id> from X to Y-1 with
<id> starting from 0 to X-1. X to Y-1. <id> getting increment of Z each
• Starts with id=0
time.
• Executes the commands • Starts with id=X
Explana • Starts with id=X
tion • Increments the value of <id> by 1 • Executes the commands • Executes the commands
• Executes the commands again • Increments the value of <id> by 1 • Increments the value of <id> by Z
• Repeats the process till id=X-1 • Executes the commands again • Executes the commands again
• Repeats the process till id=Y-1 • Repeats the process till <id> reaches
Y-1

for index in range(5): for index in range(3,7): for index in range (1,13,3):
Exampl
e print (‘Loop Number: ‘, print (‘Loop Number: ‘, print (‘Loop Number: ‘,
index) index) index)
Loop Number: 0 Loop Number: 3 Loop Number: 1
Output Loop Number: 1 Loop Number: 4 Loop Number: 4
on Loop Number: 2 Loop Number: 5 Loop Number: 7
Screen
Loop Number: 3 Loop Number: 6 Loop Number: 10
DEFINITE LOOPS / COUNT
CONTROLLED
PSEUDOCDE LOOP
VS PYTHON

Pseudocode Python
REPEAT <X> TIMES
<commands>
for <id> in range(<X>):
END REPEAT <commands>
FOR <id> FROM 1 TO <Y> DO
<commands> for <id> in range(<X>):
END FOR <commands>
(<id> not used inside loop)
FOR <id> FROM <X> TO <Y> DO
<commands>
for <id> in range(<X>,<Y>):
END FOR <commands>
FOR <id> FROM <X> TO <Y> STEP <Z> DO
<commands>
for <id> in range(<X>,<Y>,<Z>):
END FOR <commands>
DEFINITE LOOPS / COUNT
CONTROLLED
PSEUDOCDE LOOP
VS PYTHON
EXAMPLES
Pseudocode Python
REPEAT 50 TIMES
SEND ‘Hello World’ TO DISPLAY
for index in range(50):
END REPEAT print (‘Hello World’)
FOR index FROM 1 TO 50 DO
SEND ‘Hello World’ TO DISPLAY
for index in range(50):
END FOR print(‘Hello World’)
FOR index FROM 2 TO 100 DO
SEND ‘Hello World’ TO DISPLAY for index in range(2,101):
SEND Index TO DISPLAY print(‘Hello World’, index)
END FOR
FOR index FROM 0 TO 100 STEP 25 DO
SEND ‘Hello World’ TO DISPLAY for index in range(0,100,25):
SEND Index TO DISPLAY print(‘Hello World’, index)
END FOR
DEFINITE LOOPS / COUNT
CONTROLLED
PSEUDOCDE LOOP
VS PYTHON
EXAMPLES
Pseudocode Python
REPEAT 50 TIMES
SEND ‘Hello World’ TO DISPLAY
for index in range(50):
END REPEAT print (‘Hello World’)
FOR index FROM 1 TO 50 DO
SEND ‘Hello World’ TO DISPLAY
for index in range(50):
END FOR print(‘Hello World’)
FOR index FROM 2 TO 100 DO
SEND ‘Hello World’ TO DISPLAY for index in range(2,101):
SEND Index TO DISPLAY print(‘Hello World’, index)
END FOR
FOR index FROM 0 TO 100 STEP 25 DO
SEND ‘Hello World’ TO DISPLAY for index in range(0,100,25):
SEND Index TO DISPLAY print(‘Hello World’, index)
END FOR
INDEFINITE LOOPS / CONDITION
CONTROLLED LOOP
PSEDUOCODES
REPEAT…UNTIL WHILE..DO..ENDWHILE
REPEAT WHILE <condition> DO
Syntax <commands> <commands>
UNTIL <condition> END WHILE
• Repeats the <commands> WHILE the
• Repeats the <commands> UNTIL the <condition> is true & stops when <condition>
<condition> becomes True becomes false
Explanatio • It’s a Post-Condition Controlled Loop i.e. • It’s a Pre-Condition Controlled Loop i.e. condition
n condition is checked AFTER commands are is checked BEFORE commands are executed
executed
• Thus, commands might not be executed at all if
• Thus, commands will be executed at least once condition is already false

SET Counter TO 0 SET Counter TO 0


REPEAT WHILE (Counter < 5)
Example SET Counter TO Counter + 1 SET Counter TO Counter + 1
SEND Counter TO DISPLAY SEND Counter TO DISPLAY
UNTIL (Counter = 5) END WHILE
1 1
2 2
Output on
Screen
3 3
4 4
5 5
INDEFINITE LOOPS / CONDITION
CONTROLLED
PYTHON LOOP
while ()
Syntax
while <condition>:
<commands>
• Repeats the <commands> WHILE the <condition> is true & stops when
<condition> becomes false

Explanation • It’s a Pre-Condition Controlled Loop i.e. condition is checked BEFORE commands
are executed

• Thus, commands might not be executed at all if condition is already false


counter = 0
while (Counter < 5) :
Example
counter = counter + 1
print (counter)
1
2
Output on
3
Screen
4
5
LOOP SKIPPER
CONTINUE COMMAND
It is possible to add a certain condition within the commands inside the loops
to skip the remaining commands for that specific iteration. This is done using
CONTINUE command
if <condition>:
Syntax
continue
check = 0
while (check<10):
check = check+1
Example
if (check == 3):
continue
print(check)
In each iteration/loop the variable check is incremented and then printed. But if
Explanation check = 3, the print statement is skipped and the program moves to next
iteration.
Output on
1 2 4 5 6 7 8 9 10
Screen
PRACTICE QUESTIONS
Q9. Write a pseudocode that takes the marks of 50 students as input and displays their average.
Code the same using python.

Q10. Write a pseudocode which takes 25 numbers and counts how many of them are positive and
how many are less than zero and displays the result. Your code MUST have appropriate prompts.
Code the same using python.
Q11. Write a pseudocode which takes a number as input and prints all its multiples less than 100.
Code the same using python.

Q12. Write a pseudocode which takes marks of students of a class as input and sums them. An entry
of -1 is done to indicate that the list has ended and the program then displays the total. Code the
same in python.
Q13. Write a pseudocode which takes the amounts of bills of a super store as input and continues to
add them till the total reaches Rs.100,000. It also counts how many bills were entered to reach that
total and out of those how many bills were of more than Rs.5,000. Code the same in python.
PRACTICE QUESTIONS
Q9. Write a pseudocode that takes the marks of 50 students as input and displays their average.
Code the same using python.

PSEUDOCODE PYTHON

SET Total TO 0 Total = 0


FOR index FROM 1 TO 50 DO For index in range (50):
RECEIVE Marks FROM Marks = int(input())
KEYBOARD Total = Total + Marks
SET Total TO Total + Marks Avg = Total / 50
END FOR Print (Avg)
SET Avg TO Total / 50
SEND Avg TO DISPLAY
PRACTICE QUESTIONS
Q10. Write a pseudocode which takes 25 numbers and counts how many of them are positive and
how many are less than zero and displays the result. Your code MUST have appropriate prompts.
Code the same using python.
PSEUDOCODE PYTHON

SET Negative TO 0 Negative =0


SET Positive TO 0
Positive = 0
FOR index FROM 1 TO 25 DO
SEND ‘Enter Number’ TO DISPLAY
for index in range(25):
RECEIVE Num FROM KEYBOARD Num=int(input(’Enter Number’))
IF (Num>0) THEN if (Num>0):
SET Positive TO Positive + 1 Positive=Positive+1
ENDIF if (Num<0):
IF (Num<0) THEN Negative = Negative + 1
SET Negative TO Negative + 1 print (‘Positive Numbers:’, Positive)
ENDIF
Print (‘Negative Numbers:’,Negative)
END FOR
SEND ‘Positive Numbers:’ TO DISPLAY
SEND Positive TO DISPLAY
SEND ‘Negative Numbers:’ TO DISPLAY
SEND Negative TO DISPLAY
PRACTICE QUESTIONS
Q11. Write a pseudocode which takes a number as input and prints all its multiples less than 100.
Code the same using python.

PSEUDOCODE PYTHON
SEND ‘Enter Number’ TO DISPLAY
RECEIVE Num FROM KEYBOARD Num = int(input(‘Enter Number:’))
FOR index FROM 0 TO 100 STEP Num DO for index in range (0,100,Num):
SEND index TO DISPLAY print (index)
END FOR
PRACTICE QUESTIONS
Q12. Write a pseudocode which takes marks of students of a class as input and sums them. An entry
of -1 is done to indicate that the list has ended and the program then displays the total. Code the
same in python.
PSEUDOCODE PYTHON
SET Marks TO 0
SET Sum TO 0 Marks = 0
WHILE (Marks <> -1) DO Sum = 0
SET Sum TO Sum + Marks while (marks <>-1):
SEND ‘Enter Marks’ TO DISPLAY Sum=Sum+Marks
RECEIVE Marks FROM KEYBOARD Marks=int(input(‘Enter Marks:’))
END WHILE print (‘Sum is:’, Sum)
SEND Sum TO DISPLAY
PRACTICE QUESTIONS
Q13. Write a pseudocode which takes the amounts of bills of a super store as input and continues to
add them till the total reaches Rs.100,000. It also counts how many bills were entered to reach that
total and out of those how many bills were of more than Rs.5,000. Code the same in python.

PSEUDOCODE PYTHON
SET Greater TO 0 Greater = 0
SET Count TO 0 Count = 0
SET Sum TO 0 Sum = 0
WHILE (Sum < 100000) DO while (Sum < 100000):
SEND ‘Enter Bill’ TO DISPLAY Bill=int(input(‘Enter Bill:’))
RECEIVE Bill FROM KEYBOARD Sum= Sum+ Bill
SET Sum TO Sum + Bill if (Bill > 5000):
SET Count TO Count + 1 Greater = Greater + 1
IF (Bill > 5000) THEN Count = Count + 1
SET Greater TO Greater + 1 print (Greater, Count)
END WHILE
SEND Count TO DISPLAY
SEND Greater TO DISPLAY
FUNCTION

Function: A function is a piece of code which is used to


perform a specific task. It is written only once and it can then
be used again and again by just using its name. Functions can
be built-in or user made.
RANDOM FUNCTION
Random Function: RANDOM is a built-in function which generates a random number
from within the given range.

Pseudocode Python
Syntax import random
SET <variable> TO RANDOM(n)
<variable> = random.randint(<X>,<Y>)
Explanatio Generates a random number from X to Y-
n Generates a random number from 0 to n 1 and stores in the variable.
and stores in the variable. import random must be written to use
the built-in random function
Example SET Guess_Number TO RANDOM(50) import random
Guess_Number = random.randint(0,51)
This will generate a random number
from 0-50 and save it in variable This will generate a random number from 0-50
Guess_Number and save it in variable Guess_Number
LENGTH FUNCTION
LENGTH Function: LENGTH is a built-in function which counts the number of
characters in a string OR the number of elements in an array and stores the result in a
variable.
Pseudocode Python
Syntax SET <variable> TO LENGTH(<string>) <variable> = len(<string>)
Explanatio Counts the number of characters in the Counts the number of characters in the
n string and stores in variable. string and stores in variable.
Example SET Size1 TO LENGTH(‘Cornerstone’) Size1 = len(‘Cornerstone Is My School’)
SET Name TO ‘Imran Khan’ Name = ‘Mustanzar Hussain #$%’
SET Size2 TO LENGTH(Name) Size2 = len(Name)
Result Size1 = Size1 =
Size 2 = Size 2 =
TOPIC 6: MAKING PROGRAMS EASY TO USE
MAKING PROGRAMS EASY TO READ
TOPIC 6: STRINGS
STRINGS
INDEXING IN STRINGS

‘Computer Science’

The first character of a


string will ALWAYS be at
Index ZERO
STRINGS
LOCATING/FINDING A CHARACTER IN STRING

Subject = ‘Computer Science’

Subject(3) =
Subject(8) =
Subject(12) =
Subject(15) =
Subject(16) =
Subject(4) =
Subject(0) =
STRINGS
STRING TRAVERSAL / SCROLLING THROUGH A STRING
Subject = ‘Computer Science’

STRING TRAVERSAL: A FOR LOOP IS USED TO TRAVERS/SCROLL THROUGH EACH


CHARACTER OF THE STRING.
Each character of a string can be accessed by traversal for printing, searching for a certain
character etc.

PSEUDOCODE EXAMPLE PYTHON EXAMPLE

SET Subject TO ‘Computer Science’ Subject = ‘Computer Science’


FOR index FROM 0 TO 15 for index in range (0,16):
SEND Subject(index) TO DISPLAY print Subject[index]
END FOR
STRINGS
FINDING A CHARACTER IN A STRING THROUGH STRING TRAVERSAL
Subject = ‘Computer Science’

PSEUDOCODE PYTHON

SET Subject TO ‘Computer Science’ Subject = ‘Computer Science’


SEND ‘Enter Character’ TO DISPLAY Find =str(input(‘Enter Character’))
RECEIVE Find FROM KEYBOARD
for index in range (0,16):
FOR index FROM 0 TO 15 if (Find == Subject[index]):
IF (Find = Subject(index)) THEN print (index)
SEND index TO DISPLAY
ENDIF
END FOR
STRINGS
STRING OPERATIONS
Subject = ‘Computer Science’

FINDING LENGTH
Length (number od characters) in a string can be found using LENGTH
Pseudocode function Python
Syntax LENGTH(<string>) len(<string>)
Explanatio Counts the number of characters in the Counts the number of characters in the
n string string
Example SET Size TO LENGTH(Subject) Size = len(Subject)
Result Size= Size=
STRINGS
STRING OPERATIONS
Subject = ‘Computer Science’

CHANING TO LOWER CASE


Characters of a string can be turned to lower case using LOWER CASE
Pseudocode function Python
Syntax LOWER(<string>) <string>.lower()
Explanatio Changes all the characters of the string Changes all the characters of the string
n to lower case to lower case
Example SET ChotiABC TO LOWER (Subject) ChotiABC = Subject.lower()
Result ChotiABC = ChotiABC =
STRINGS
STRING OPERATIONS
Subject = ‘Computer Science’

CHANING TO UPPER CASE


Characters of a string can be turned to lower case using UPPER CASE function
Pseudocode Python
Syntax UPPER(<string>) <string>.upper()
Explanatio Changes all the characters of the string Changes all the characters of the string
n to upper case to upper case
Example SET BariABC TO LOWER (Subject) BariABC = Subject.upper()
Result BariABC = BariABC =
STRINGS
STRING OPERATIONS
Subject = ‘Computer Science’

EXTRACTING A SUBSTRING
Some characters from a string can be extracted to form a new string using
SUBSTRING
Pseudocode Python
Syntax SUBSTRING(<string>, <X>,<Y>) <String>[<X>:<Y>]
Explanatio Extracts a substring from <string> Extracts a substring from <string>
n starting from character at index <X> starting from character at index <X> and
and ending at character at index <Y>-1 ending at character at index <Y>-1
Example Extracted = SUBSTRING(Subject,3,6) Extracted = Subject[3:8]
Result Extracted = Extracted =
STRINGS
STRING OPERATIONS
Subject = ‘Computer Science’

CONCATENATION OF STRINGS
Joining of two strings or a string with a character is called concatenation
Pseudocode Python
Syntax <String1> & <String2> <String1> + <String2>
Explanatio Adds <String2> after <String> and
n forms a new string Adds <String2> after <String> and
In pseudocode, A number can also be forms a new string
concatenated with a string using &
Example SET Remark TO ‘Is Nice’ Remark = ‘Is Nice’
SET New TO Subject & Remark New = Subject + Nice
SEND New TO DISPLAY print(New)
Result on
Screen
STRINGS
STRING OPERATIONS
Subject = ‘Computer Science’

CHECKING A PHRASE IN STRING


Presence of a certain phrase or series of characters can be checked using IN
Pseudocode function Python
Syntax <Phrase> IN <string> <Phrase> in <string>
Explanatio This will check if <Phrase> exists in
This will check if <Phrase> exists in
n <string> or not. If it does, the
<string> or not. If it does, the expression
expression generates TRUE otherwise
generates TRUE otherwise FALSE
FALSE
Example SET Found TO ‘Compute’ IN Subject Found = ‘puter’ in Subject
SEND FOUND TO DISPLAY Found2 = ‘ien’ in Subject
Found3 = ‘COM’ in Subject
Result on Found=
Screen Found2=
STRINGS
STRING OPERATIONS
Subject = ‘Computer Science’

FOR … EACH.. FROM.. END FOREACH


A Special FOR LOOP used with STRINGS
Pseudocode Python
Syntax FOR EACH <id> FROM <string> DO
for <id> in <string>:
<command>
END FOREACH command
Explanatio Executes <command> for each character of Executes <command> for each character of
n the <string> by assigning each character to the <string> by assigning each character to
<id> one by one. <id> one by one.
Example FOR EACH letter FROM Subject DO for letter in Subject:
SEND letter TO DISPLAY print(letter)
END FOREACH
Result
STRINGS
Q. Write a pseudocode which takes a string as input from user and performs the following tasks:
1. Finds and prints the length of the string
2. Converts it to upper case and prints
3. Converts it to lower case and prints
4. Extract first 5 characters into a new string and prints that
5. Checks if the phrase ‘have’ is in the string or not

Perform all the tasks one by one and separately.


TOPIC 8: DATA STRUCTURES
DATA STRUCTURES

A data structure is an organized collection of


related elements.

STRINGS ARRAYS RECORDS


It’s mainly a data It is a collection/list of
type, but also multiple data items, of
considered as a same data type & the
entire collection/list has
data structure as it
the same name. Each data
is a ‘collection of element in the array has a
characters’ unique index which
denotes its position in the
list/collection.
ARRAYS
It is a collection/list of multiple data items, of same data type & the entire collection/list has the same
name. Each data element in the array has a unique index which denotes its position in the
Pseudocode list/collection. Python
Arrays Lists
Name One Unified Name for Entire Array One Unified Name for Entire List
Data
Type
All data elements are of same data type All elements CAN be of different data type

Indexing First element is at Index 0 First element is at Index 0


It is essential to declare a list in python.
It is essential to declare and define the
Size Defining size is also not compulsory but
size of the array.
preferred.
• ARRAY <AarrayName>
<ListName> = [ ] OR
[<ArraySize>]
<ListName> = [None]*n OR
Declaration
• SET <ArrayName> TO [<value>,
& <ListName> = [<value>,…]
Initializatio …]
n
First statement declares an array <ArrayName> &
Initializes a one-dimensional list called
second statement Initializes that array with set of
values <ListName> with OR without set of values

• ListValues = [ ] (Defining Empty List)


• ListValues =[None] * 5 (Defining Size of
ARRAYS/LISTS
INDEXING IN STRINGS

Array/List: StudentNames
Index 0 1 2 3 4 5 6 7 8 9 10 11 12
Mehree
Data 'Basil Fayha Ayesha Asra Hamza Taha Areesha Noor Nadis
n
Momina Ameer Ibrahim

The first character of a


string will ALWAYS be at
Index ZERO
ARRAYS/LISTS
LOCATING/FINDING A CHARACTER IN ARRAYS/LISTS

Array/List: StudentNames
Index 0 1 2 3 4 5 6 7 8 9 10 11 12
Mehree
Data 'Basil Fayha Ayesha Asra Hamza Taha Areesha Noor Nadis
n
Momina Ameer Ibrahim

StudentNames [0] =
StudentNames [3] =
StudentNames [11] =
StudentNames [12] =
StudentNames [13] =
StudentNames [7] =
StudentNames [2] =
StudentNames [11] =
ARRAYS/LISTS
FINDING LENGTH OF ARRAYS/LISTS
Array/List: StudentNames
Index 0 1 2 3 4 5 6 7 8 9 10 11 12
Mehree
Data 'Basil Fayha Ayesha Asra Hamza Taha Areesha Noor Nadis
n
Momina Ameer Ibrahim

FINDING LENGTH
Length (number of characters) in a array/list can be found using LENGTH
Pseudocode function Python
Syntax LENGTH(<array>) len(<list>)
Explanatio Counts the number of data elements in Counts the number of data elemeents in
n the array the list
Example SET Size TO LENGTH(StudentNames) Size = len(StudentNames)
Result Size= Size=
ARRAYS / LISTS
STRING TRAVERSAL / SCROLLING THROUGH AN ARRAY/LIST
Array/List: StudentNames
Index 0 1 2 3 4 5 6 7 8 9 10 11 12
Mehree
Data 'Basil Fayha Ayesha Asra Hamza Taha Areesha Noor Nadis
n
Momina Ameer Ibrahim

ARRAY TRAVERSAL: A FOR LOOP IS USED TO TRAVERS/SCROLL THROUGH EACH DATA


ELEMENT OF THE ARRAY/LIST.
Each data element of a string can be accessed by traversal for printing, searching for a
certain data element etc.

PSEUDOCODE EXAMPLE PYTHON EXAMPLE

SET Subject TO [‘Basil’, ‘Fayha’, ‘Ayesha’, ‘Ayesha’, Subject = [‘Basil’, ‘Fayha’, ‘Ayesha’, ‘Ayesha’, ‘Asra’,
‘Asra’, ‘Hamza’ , ‘Taha’, ‘Areesha’ , ‘Noor’, ‘Nadis’, ‘Hamza’ , ‘Taha’, ‘Areesha’ , ‘Noor’, ‘Nadis’, ‘Maheen’,
‘Maheen’, ‘Momina’, ‘Ameer’, ‘Ibrahim’] ‘Momina’, ‘Ameer’, ‘Ibrahim’]
for index in range ( ):
FOR index FROM _____ TO _____ print StudentNames[ ]
SEND StudentNames[ ] TO DISPLAY
END FOR
ARRAYS / LISTS
STRING TRAVERSAL / SCROLLING THROUGH AN ARRAY/LIST
Array/List: StudentNames
Index 0 1 2 3 4 5 6 7 8 9 10 11 12
Mehree
Data Basil Fayha Ayesha Asra Hamza Taha Areesha Noor Nadis
n
Momina Ameer Ibrahim

FOR … EACH.. FROM.. END FOREACH


A Special FOR LOOP used with ARRAYS/LISTS
Pseudocode Python
Syntax FOR EACH <id> FROM <array> DO
for <id> in <array>:
<command>
END FOREACH command
Explanatio Executes <command> for each element of Executes <command> for each element of the
n the <array> by assigning each data element <array> by assigning each data element to
to <id> one by one. <id> one by one.
Example FOR EACH bacha FROM StudentNames DO for bacha in StudentNames:
SEND bacha TO DISPLAY print(bacha,’Nalaiq’)
SEND ‘Nalaiq’ TO DISPLAY
END FOREACH
Result
PRACTICE QUESTIONS
Q14. Write a pseudocode which makes a result report for 25 students. The code takes the
names of the students, their English marks, Urdu marks and Maths marks one by one and
saves in separate arrays. The code then calculates the total sum across three subjects
and saves the results in a new array. At the end the total marks of each student is printed
along with the names.
ARRAYCode the same in python.
Names[25]
ARRAY English [25]
ARRAY Urdu [25]
ARRAY Maths[25]
ARRAY Total [25]

FOR index 0 TO 24 DO
SEND ‘Enter Name Of Student#’ TO DISPLAY
SEND index + 1 TO DESIPLAY
RECEIVE Name[index]
SEND ‘Enter English Marks:’ TO DISPLAY
RECEIVE English[index]
SEND ‘Enter Urdu Marks:’ TO DISPLAY
RECEIVE Urdu[index]
SEND ‘Enter Maths Marks:’ TO DISPLAY
RECEIVE Maths[index]
SET Total[index] TO English[index] + Urdu[index] + Maths[index]
END FOR
FOR index 0 TO 24 DO
SEND Name[index] TO DISPLAY
SEND Total[index] TO DISPLAY
END FOR
PRACTICE QUESTIONS
Q14. Write a pseudocode which makes a result report for 5 students. The code takes the
names of the students, their English marks, Urdu marks and Maths marks one by one and
saves in separate arrays. The code then calculates the total sum across three subjects
and saves the results in a new array. At the end the total marks of each student is printed
along with the names. Code the same in python.
Names = [None]*25
English = [None]*25
Urdu = [None]*25
Maths = [None]*25
Total = [None]*25

for index in range(25):


print (‘Enter Name Of Student#’, index+1)
Name[index] = int(input())
print (‘Enter English Marks:’)
English[index] = int(input())
Urdu[index] = int(input(‘Enter Urdu Marks:’ ))
Maths[index] = Int(input(‘Enter Maths Marks:’)
Total[index] = English[index] + Urdu[index] +
Maths[index]
for index in range(25):
print(Name[index] , Total[Index])
PYTHON
LISTS
20 AMAZING
FUNCTIONS
PYTHON LISTS
FUNCTIONS/OPERATIONS
my_list = [1,0,22,34,9,101]
1. Length of a List 4. Sum of Elements
Syntax Syntax
(Example) length = len(my_list) (Example) total = sum(my_list)
: :
Description Returns the number of elements in the Description Returns the sum of all elements in the
: list. : list.
Result: 5. Sorting a List
Result:
2. Maximum Value
Syntax
Syntax max_value = (Example) my_list.sort()
(Example) :
: max(my_list)
Description
Description Sorts the list in ascending order.
Returns the maximum value in the list. :
:
6. Result:
Sorted Function
my_list =
Result:
3. Minimum Value Syntax
(Example): sorted = sorted(my_list)
Syntax
(Example)
min_value = Returns a new sorted list without
Description:
: min(my_list) modifying the original list.
Description sorted =
Returns the minimum value in the list. Result:
: my_list =
PYTHON LISTS
FUNCTIONS/OPERATIONS
my_list = [1,0,22,0,34,9,101]
7. Reversing a List 10. Appending Elements
Syntax Syntax
(Example) my_list.reverse() (Example) my_list.append(6)
: :
Description Description
Reverses the order of the list. Adds an element to the end of the list
: :
Result: my_list = my_list
11. Extending
Result: a =List
8. Clearing a List
Syntax
Syntax
(Example) my_list.clear()
(Example) my_list.extend([7, 8])
:
:
Description Adds elements from a string or a list to
Description
Removes all elements from the list : the end of the list.
:
Result: my_list =
Result: my_list =
9. Repetition 12. Removing Elements
Syntax Syntax
(Example) repeated = my_list * 2 (Example) my_list.remove(0)
: :
Description Repeats the list a specified number of Description Removes the first occurrence of the
: times. : specified element.
PYTHON LISTS
FUNCTIONS/OPERATIONS
my_list = [1,0,22,0,34,9,1,101,1]

13. Popping Elements 15. Counting Occurrences


Syntax
(Example)
element = my_list.pop() Syntax
(Example)
count =
: element2 = my_list.pop(4) : my_list.count(1)
Description Removes and returns the last element or the Description Returns the number of occurrences of the
: element at the specified index : specified element.

Result: Result:

14. Finding the Index 16. Inserting Elements


Syntax index = Syntax
(Example) (Example) my_list.insert(2, 'a')
: my_list.index(9) :
Description Returns the index of the first occurrence of Inserts an element at the specified
: the specified element. Description position. The first parameter is the
: position and second parameter is the
Result:
data element.
Result: my_list =
PYTHON LISTS
FUNCTIONS/OPERATIONS
my_list = [1,0,22,0,34,9,1,101,1]

17. Slicing 18. Checking Presence of an Element


sub_list1 = my_list[1:5] Syntax
Syntax (Example) exists = 34 in my_list
(Example) sub_list2 = my_list[ :5] :
:
sub_list3 = my_list[1: ] Description
Checks if an element exists in the list.
:
• Retrieves a sub-list from the
specified start index to the end Result:
index (exclusive).
Description
:
• In case start index is not given,
it is assumed to be 0. 19. Concatenation
• In case end index is not given it Syntax
is assumed till the end of the list combined = my_list + [9,
(Example)
: 10]
sub_list1 =
Result: sub_list2 = Description Concatenates/Combines two lists and
sub_list3 = : forms a new list.
Result:
MULTIDIMENSIONAL ARRAYS
In a 1D Array there is only one item on each index position.
A multidimensional array is an ‘array of arrays’; each item
at an index is another array.
0 Fayha
1 Taha
2 Basil
0 1 2 3
3 Nadis 1D
0 Fayha Femal Pass CSS21
4 Noor Array: 1
e
Data
5 Ayesha 1 Taha Male Pass CSS34
element
6 Ali at each 2 Basil Male Pass CSS44
7 Sara index 3 Nadis Male Fail CSS09
8 Maya Multidimensiona 4 Noor Femal Fail CSS22
l Array: An array e
exists at each 5 Ayesh Femal Fail CSS11
index a e
6 Ali Male Pass CSS3
MULTIDIMENSIONAL ARRAYS
In other words,
1D Array is a list with multiple rows and only one column.
Whereas in 2D arrays, are in the form of tables with
multiple rows & columns.

0 1 2 3
0 Fayha 0 Fayha Femal Pass CSS21
1 Taha 1D Array: e
Multiple rows and 1 Taha Male Pass CSS34
2 Basil
Only one column
3 Nadis 2 Basil Male Pass CSS44
4 Noor 3 Nadis Male Fail CSS09
5 Ayesha 2D Array: 4 Noor Femal Fail CSS22
6 Ali Multiple rows and e
multiple colunms 5 Ayesh Femal Fail CSS11
7 Sara
a e
8 Maya
6 Ali Male Pass CSS3
TWO DIMESNIONAL ARRAYS
Pseudocode Python
2D Arrays 2D Lists
Name One Unified Name for Entire 2D Array One Unified Name for Entire 2D List
All data elements in entire 2D list CAN be of
All data elements in entire 2D array are
Data Type different data type. But datatype in each
of same data type
‘column’ is preferably kept same
Indexing First element is at Index (0,0) First element is at Index [0][0]
It is essential to declare and define the As python doesn’t require declaration,
Size
size of the 2D array defining size is also not required
ARRAY <AarrayName> [<Row>,<Col>]
<ListName> = [ ] OR
SET <ArrayName> TO [[<value>,…],[.. ,
Declaratio ..],..] <ListName> = [[<value>,…],[.. , ..],..]
n&
Initializatio The first statement declares a 2D array
n called <ArrayName> and the second Initializes a two-dimensional list called
statement Initializes that 2D array with a <ListName> with OR without set of values
set of values
ARRAY 2DArray [2,3] 2DArray= [ ]
Example
SET 2DArray TO [[11,50,6],[5,4,90]] 2DArray = [[11,50,6],[5,4,90]]
2D ARRAYS/2D LISTS
LOCATING/FINDING A CHARACTER IN 2D ARRAYS/2D LISTS
0 1 2 3
Array/List: Data 0 1 2 3
0 Fayha Femal Pass CSS21 0 Fayha F 82 YES
e
1 Taha M 88 NO
1 Taha Male Pass CSS34 A 2D ARRAY
(Pseudocode 2 Basil M 90 YES
2 Basil Male Pass CSS44 )
3 Nadis M 12 NO
3 Nadis Male Fail CSS09
4 Noor F 67 NO
4 Noor Femal Fail CSS22
e 5 Ayesh F 98 NO
a
5 Ayesh Femal Fail CSS11 A 2D LIST
a e (Python) 6 Ali M 11 YES

6 Ali Male Pass CSS3 7 Sara F 23 YES


D 8 Maya F 67 YES
Data[0,0] = Data[0][3] =
7 Sara Femal Fail CSS45
Data[3,0] = Data[3][3] =
e
Data[4,3] = Data[2][3] =
8Data[7,2]
Maya= Femal Pass CSS55 Data[5][5] =
Data[5,1] = e Data[8][2] =
Data[6,4] = Data[4][0] =
2D ARRAYS /2D LISTS
STRING TRAVERSAL / SCROLLING THROUGH A 2D ARRAY/LIST
ARRAY TRAVERSAL: A NESTED FOR LOOP IS USED TO TRAVERS/SCROLL THROUGH EACH
DATA ELEMENT OF THE 2D ARRAY/LIST.

PSEUDOCODE EXAMPLE PYTHON EXAMPLE

(Consider the 2D Array on Last Slide) (Consider the 2D List on Last Slide)

FOR row FROM _____ TO _____ for row in range ( ):


FOR col FROM _____ TO ______ for col in range ( ):
SEND Data[ ] TO DISPLAY print Data[ ] [ ]
END FOR
END FOR
PRACTICE QUESTIONS
Q15. Write a pseudocode which makes a result report for 25 students. The code takes the
names of the students in an array. It also takes their English marks, Urdu marks and
Maths marks and saves in a 2D array. The code then calculates the total sum across three
subjects and saves the results in a new array. At the end the total marks of each student
is printed along with the
ARRAY names.
Names[25]
ARRAY Marks[25,3]
ARRAY Total [25]

FOR row 0 TO 24 DO
SEND ‘Enter Name Of Student’ TO DISPLAY
RECEIVE Name[row]
FOR col 0 TO 2
SEND ‘Enter Marks:’ TO DISPLAY
RECEIVE Marks[row][col]
END FOR
SET Total[row] TO Marks[row][0] + Marks[row][1] + Marks[row][2]
END FOR

FOR index 0 TO 24 DO
SEND Name[index] TO DISPLAY
SEND Total[index] TO DISPLAY
END FOR
PRACTICE QUESTIONS
Q16. The students of a class participated in a game and each student scored points. A 2D
list GameData has the names, genders(M/F) and points stored. Code a program which
prints the list of names of boys and girls separately, counts and prints the number of boys
and girls separately, totals the points scored by boys and girls separately and declare
who amongst the both genders won. Code in python.
Length = len(GameData)
boys = 0 print(‘Boys:’,boys)
BoysTotal = 0 print(‘Girls:,girls)
girls = 0
GirlsTotal = 0 if (GirlsTotal>BoysTotal):
print(‘Winner: Girls’)
print{‘Boys:’)
for row in range (length):
elif (BoysTotal>GirlsTotal):
for col in range(3): print(‘Winner: Boys’)
if (GameData[row][1] == ‘M’): else
print(GameData[row][0]) print(‘Tie’)
boys = boys + 1
BoysTotal = BoysTotal + GameData[row][2]

print{‘Girls:’)
for row in range (length):
for col in range(3):
if (GameDate[row][1] == ‘F’):
print(GameData[row][0])
girls = girls + 1
GirlsTotal = GirlsTotal + GameData[row][2]
RECORDS
(PSEUDOCODE FOR PYTHON 2D LISTS)
TOPIC 9: INPUT / OUTPUT
VALIDATION
Validation: The process in which the program code automatically ensures that the data
entered by the user meets a certain criteria and is reasonable.

Validation Checks: The criteria set by the coder while coding against which the entered
data is checked, are called validation checks.
1. Range Check
2. Length Check
3. Presence Check
4. Lookup Check

TIP: All types of Validation Checks are coded using WHILE LOOP in pseudocode / python
VALIDATION

Range
Check
Range Check: It is used to ensure that the data entered by user is within a specified
range.
Pseudocode Python
Example SET Age TO 0
Age = 0
WHILE (Age < 10 OR Age > 20) DO
while (Age < 15 or Age > 25):
SEND ‘Enter Age:’ TO DISPLAY
Age=int(input(‘Enter age:’))
RECEIVE Age FROM KEYBOARD
END WHILE
Explanatio This will ensure that the user enters an This will ensure that the user enters an
n age from 10 to 20. It keeps on asking for age from 15 to 25 It keeps on asking for
age unless use enters the age from age unless use enters the age from
specified range. specified range.
VALIDATION
Length
Check
Length Check: It is used to ensure that the data entered by user is of a specified
length.
Pseudocode Python
Example SET Leng TO 0
WHILE (Leng <> 8) DO Leng = 0
SEND ‘Enter Password:’ TO while (Leng != 8):
DISPLAY Password=str(input(‘Enter
RECEIVE Password FROM Password:’))
KEYBOARD Leng = len(Password)
Leng = LENGTH(Password)
END WHILE
Explanatio This will ensure that the password
n This will ensure that the password entered
entered has only 8 characters. It will
has only 8 characters. It will keep on asking
keep on asking for password if the
for password if the entered data has more
entered data has more or less
or less characters than 8
characters than 8
VALIDATION

Presence
Check
Presence Check: It is used to ensure that some form of data has been entered by user
and user hasn’t entered a blank or left the field empty
Pseudocode Python
Example SET Name TO ‘ ’
Name = ‘ ’
WHILE (Name = ‘ ’) DO
while (Name = ‘ ’):
SEND ‘Enter Name:’ TO DISPLAY
Name=str(input(‘Enter Name:’))
RECEIVE Name FROM KEYBOARD
END WHILE
Explanation This will ensure the user enters anything This will ensure the user enters anything
other than a blank space other than a blank space
VALIDATION

Lookup
Check
Lookup Check: It is used to ensure that the data entered by user is one of the
predefined acceptable data values. The acceptable data can be store pre-hand in an
array.
Pseudocode Python
Example SET Code TO ‘Nill’
Code = ‘Nill’
WHILE (Code <> ‘Alpha’ AND Code <>
while (Code !=‘Alpha’ and Code != ‘Tarvis’
Travis AND Code <> ‘Jack’) DO
and Code !=‘Jack’)
SEND ‘Enter Code:’ TO DISPLAY
Code=string(input(‘Enter Code:’))
RECEIVE Code FROM KEYBOARD
END WHILE
Explanation This will only accept Alpha, Jack or Travis
This will only accept Alpha, Jack or Travis as
as code. Every other entry will be
code. Every other entry will be rejected
rejected
TEST DATA
Test Data: The data entered by programmer to test the program to see if
its working how it is supposed to against different types of input data.
Types of Test Data:
1. Normal Test Data: These are the data values which
should be accepted by code and program should work
accordingly.
2. Boundary Test Data: If a code has Range Check
included, the last allowed values in the range are called
Boundary Values and they are entered to test if the
program accepts them and works correctly.
3. Erroneous Test Data: These are the data values which
should be rejected by the code and program should not
accept them. These can consist of any kind of garbage
TEST DATA
Example: A program is coded which takes the percentages of a student
in exams. Give examples of the three sets of test data for this code

1. Normal Test Data:

2. Boundary Test Data:

3. Erroneous Test Data:


TOPIC 10: SUBPROGRAMS
SUBPROGRAMS / SUBROUTINES
A subroutine/subprogram is a self-contained piece of code / module that
performs a specific task. They are written once at the start of program and
can then be used again and again by just addressing their name

PROCEDURE FUNCTION LIBRARY ROUTINE


A type of subprogram A type of subprogram A type of subprogram
which doesn’t return which always return which is built-in the
a value after some value(s) after IDE for programmers
execution execution pre-hand
PROCEDURES

A type of subprogram which doesn’t return a value after execution

A procedure can be WITH or WITHOUT a parameter

Parameter: Value(s) received by a procedure from the main program


to use in the statements in the procedure
PROCEDURES
Pseudocode Python
PROCEDURE <ProcedureName>
(<parameter>, ..) def <ProcedureName> (<parameter>, ..) :
BEGIN PROCEDURE
Syntax <command> <command>
END PROCEUDRE
CALLING: <ProcedureName> (<parameter>, CALLING: <ProcedureName>
..) (<parameter>, ..)
Explanatio This defines a procedure with This defines a procedure with
n <PrcoedureName>. There can be multiple or <PrcoedureName>. There can be multiple or
NO parameters at all. NO parameters at all.
Example PROCEDURE AVGFinder(N1, N2, N3) def AVGFinder(N1, N2, N3) :
(w/parameter BEGIN PROCEDURE
) SET SUM TO N1+N2+N3 SUM = N1+N2+N3
SET AVG TO SUM/3 AVG = SUM/3
SEND AVG TO DISPLAY print (AVG)
END PROCEDURE
CALLING: AVGFinder (10,20,Marks) CALLING: AVGFinder (10,20,Marks)
Example PROCEDURE RandomGen( ) def RandomGen( ) :
(without BEGIN PROCEDURE
parameter) SET Num TO RANDOM(100) Num = random.randint(0,101)
SEND ‘Number Generated: ‘ TO print (‘Number Generated:’, Num)
DISPLAY
SEND Num TO DISPLAY
FUNCTIONS

A type of subprogram which always return some value(s) after execution

A function can be WITH or WITHOUT a parameters

Parameter: Value(s) received by a procedure from the main program


to use in the statements in the procedure
FUNCTIONS
Pseudocode Python
FUNCTION <FunctionName> (<parameter>, ..) def <FunctionName> (<parameter>, ..) :
BEGIN FUNCTION
<command> <command>
Syntax RETURN <expression(s)>
END FUNCTION return <expression(s)>
CALLING: <Variable>= <FunctionName> CALLING: <Variable>= <FunctionName>
(<parameter>,..) (<parameter>,..)
Explana This defines a function with <FunctionName>
This defines a function with <FunctionName> and
tion and returns the <expression(s)> back to main
returns the <expression(s)> back to main program.
program. There can be multiple or NO
There can be multiple or NO parameters at all.
parameters at all.
Exampl FUNCTION AVGFinder(N1, N2, N3) def AVGFinder(N1, N2, N3) :
e BEGIN FUNCTION
(w/parame SET SUM TO N1+N2+N3 SUM = N1+N2+N3
ter) SET AVG TO SUM/3 AVG = SUM/3
RETURN AVG return AVG
END PROCEDURE
CALLING: SET Average TO AVGFinder (10,29,Marks) CALLING: Average = AVGFinder (10,29,Marks)
Exampl FUNCTION RandomGen( ) def RandomGen( ) :
e (without BEGIN FUNCTION
parameter SET Num TO RANDOM(100) Num = random.randint(0,101)
) SEND ‘Number Generated! ‘ TO DISPLAY print (‘Number Generated!’)
RETURN Num return Num
END PROCEDURE
CALLING: SET GuessNumber TO RandomGen ( ) CALLING: GuessNumber = RandomGen ( )
ARGUMENTS & PARAMETERS
The Variables in which the In this example,
Procedures/Functions receive Argument 10 is saved in Parameter N1
Argument 20 is saved in Parameter N2
and save the Arguments sent
Value of Argument Marks is saved in
from the main program are Parameter N3
called PARAMETERS

Pseudocode Python

The Variables or Values sent


Example fromAVGFinder(N1,
PROCEDURE the main program
N2, N3)TO the def AVGFinder(N1, N2, N3) :
(w/parameter Procedure/Functsions to use are
BEGIN PROCEDURE
) called
SET SUM ARGUMENTS
TO N1+N2+N3 SUM = N1+N2+N3
SET AVG TO SUM/3 AVG = SUM/3
SEND AVG TO DISPLAY print (AVG)
LOCAL VS GLOBAL VARIABLES

LOCAL VARIABLES GLOBAL VARIABLES


The variables The variables
declared/created inside a declared/created in the main
function / procedure are program are called GLOBAL
called LOCAL VARIABLES. VARIABLES.
They exist ONLY in the They exist in the whole code
function/procedure they and can be used inside
are created in and can only anywhere in the code
be used inside it including all the functions
and procedures
LOCAL VS GLOBAL VARIABLES
Q. Identify the local and global variables in this code:
# Function rectangle
def rectangle(length, width):
area = length * width
return area

#Main program
rectangleLength = int(input(‘Please enter the length of the rectangle’))
rectangleWidth = int(input(‘Please enter the width of the rectangle’))
rectangleArea = rectangle(rectangleLength, rectangleWidth)
print(rectangleArea)

LOCAL VARIABLES: area, length, width

GLOBAL VARIABLES: rectangleLength, rectangleWidth, rectangleArea


PRACTICE QUESTIONS
Q13. Write a pseudocode which takes the name, age and percentage score of a student as input. The
name must be less than 15 characters and the percentage must be reasonable. A Function takes the
score as parameter returns the grade. A procedure takes the name, age and grade as parameter and
displays if the student has graduated or not depending on the following criteria:

Age < 15 & Grade is either A, B, C, D : Graduated


Age >=15 & Grade is A, B : Graduated
Age >=15 & Grade is C,D : Not Graduated

Grading Policy:
< 40 = D
40-60 = C
61-80 = B
81-100 = A

Your code must have all the required validation checks and prompts for the user.

Code the same in Python.


Q13-PSEUDOCODE SOLUTION
#Function #Main Program
FUNCTION GradeCalculator(Percentage) SET Name TO ‘MoreThan15Charachters’
BEGIN FUCNTION
SET Score TO 101
IF (Percentage < 40) THEN
Grade = ‘D’ WHILE (LENGTH(Name) > 15)
ELSE IF (Percentage >=40 AND Percentage < 60) THEN SEND ‘Enter A Valid Name’ TO DISPLAY
Grade = ‘C’ RECEIVE Name FROM KEYBOARD
ELSE IF (Percentage >=60 AND Percentage < 80) THEN END WHILE
Grade = ‘B’ WHILE (Score <=0 OR Score >=100)
ELSE SEND ‘Enter a valid score percentage’ TO
Grade = ‘A’
DISPLAY
ENDIF
ENDIF RECEIVE Score FROM KEYBOARD
ENDIF END WHILE
RETURN Grade SEND ‘Enter Age’ TO DISPLAY
END FUNCTION RECEIVE Age FROM KEYBOARD
#Procedure
Grade = GradeCalculator(Score)
PROCEDURE ResultPrinter(StdName, StdGrade, StdAge) ResultPrinter(Name,Grade,Age)
BEGIN PROCEDURE
IF (Age <15 AND (Grade=‘A’ OR Grade=‘B’ OR Grade=‘C’ OR Grade=‘D’)) THEN
SEND StdName TO DISPLAY
SEND ‘Graduated!’ TO DISPLAY
ELSE IF (Age > 15 AND (Grade=‘A’ OR Grade=‘B’)) THEN
SEND StdName TO DISPLAY
SEND ‘Graduated!’ TO DISPLAY
ELSE IF (Age > 15 AND (Grade=‘C’ OR Grade=‘D’)) THEN
SEND StdName TO DISPLAY
SEND ‘Not Graduated!’ TO DISPLAY
END PROCEDURE
PYTHON
# Function to calculate grade based on percentage
def GradeCalculator(Percentage):
if Percentage < 40: # Main program
Grade = 'D' Name = 'MoreThan15Characters'
elif 40 <= Percentage < 60: Score = 101
Grade = 'C'
elif 60 <= Percentage < 80:
Grade = 'B'
while len(name) > 15:
else: print('Enter A Valid Name')
Grade = 'A' Name = input()
return grade
while score <= 0 or score >= 100:
# Procedure to print the result based on name, grade, print('Enter a valid score
and age percentage')
def ResultPrinter(StdName, StdGrade, StdAge):
Score = int(input())
if StdAge < 15 and StdAge in ['A', 'B', 'C', 'D']:
print(StdName)
print('Graduated!') print('Enter Age')
elif StdAge > 15 and StdGrade in ['A', 'B']: Age = int(input())
print(StdName)
print('Graduated!') Grade = GradeCalculator(Score)
elif StdAge > 15 and StdGrade in ['C', 'D']: ResultPrinter(Name, Grade, Age)
print(StdName)
print('Not Graduated!')
TOPIC 11: TESTING & EVALUATION
TYPES OF ERRORS
Logic Errors Syntax Errors Runtime Errors
When an error occurs during the
When the programmer makes When the programmer makes
execution of the program. These
such a logical mistake knowingly some grammatical or syntax
errors are caused due to some un-
or unknowingly. mistake i.e. doesn’t follow the
catered /un-expected situation
The program works but doesn’t writing rule(s) of the language.
which occurs after program starts
give the desired results. The program will not work at all.
execution.
An IDE / Computer can not identify
such errors. Only excessive testing IDE / Computer immediately IDE can not identify these errors
can be done to catch logical identifies syntax errors. and they are hardest to rectify.
errors.

• Program takes 2 numbers


and perform division
• User enters 0 as the second
number
TRACE TABLES

A Trace Table is used to test the working of an algorithm (flowchart /


program code / pseudocode) by tracing the values of the variables &
inputs/outputs used from start till the end of the algorithm.
TRACE TABLES
NUMBER NUMBER
NUMBER INDEX OUTPUT
1 2

3 1 3 6

2 6 12

3 18 36 36

4 72 144 144

5 360 720 720


TRACE TABLES
X Y OUTPUT

1 3 3

2 5 5

3 8 8

4 12 12

5 17 17

6 23 23
TRACE TABLES

Number Number Number Count=2


Count Output
1 2 3 ?

1 1 - 0 11 False

You might also like