Comp Paper 2
Comp Paper 2
HIGHEST
Rules for naming variables
• A variable name can contain only numbers, letters and
underscores
• A variable name cannot start with a number
• You can’t use a Python “reserved word” as a variable name – for
example class is a reserved word so class = input() will result in
a syntax error
• To make your programs easier to understand, use meaningful
names for your variables, such as ‘firstName’ rather than ‘var1’
If a variable is going to hold a person's name, then an appropriate
variable name might be: user_name.
Using a variable
print ("What is your name?")
firstname = input()
print ("Hello,",firstname)
Python does not require you to declare variables; instead, you associate a
variable name with a piece of data. This can be done at any time in a
program, but it is good practice to associate the variable with a value at the
start. Python will decide the type of data from the value you assign, rather
than the programmer having to specify the data type.
Constants : A constant is a type of identifier whose value cannot be changed.
Real (float) Real is also referred to as float. Real numbers 1.1, -1.0,
include numbers with decimal places. A real 382.0,
number can be positive or negative. 12.125
Boolean The Boolean data type is based on logic and can True, False
have one of only two values, True or False.
Char Char refers to a single character. The character can c, A, X, £
be any letter, digit, or symbol.
String The string data type refers to text. A string is a Hello,
collection of characters and includes spaces, 1$34A,
punctuation, numeric digits and any other symbols ninety-
such as $, &, £, etc. Strings can also contain four
numeric digits but these will be handled as text
characters, not numbers.
You can end a print statement with any character/string using this
parameter.
Arithmetic operators
• The operators +, -, * and / are used for addition,
subtraction, multiplication and division
• ** is used for an exponent (power of)
2. Accept number from user and calculate the sum of all number between 1 and given
number
Example
# Declaring a string in python
myfirst=“Save Earth”
print( myfirst)
The values that make up a list are called its elements, and they can be of any
type.
L2 = [“Delhi”, “Chennai”, “Mumbai”] #list of 3 string elements.
L3 = [ ] # empty list i.e. list with no element
Concatenating strings
• Concatenating means joining together
• The + concatenate operator is used to join together strings
firstname ← "Rose"
surname ← "Chan"
fullname ← firstname + " " + surname
OUTPUT fullname
By using a colon you can create a substring. If no start or end number is written,
Python assumes you mean the first character or last character.
STRING
In python, consecutive sequence of characters is known as a string.
An individual character in a string is accessed using a subscript (index).
The subscript should always be an integer (positive or negative). A subscript starts from 0.
Example
# Declaring a string in python
>>>myfirst=“Save Earth”
>>>print (myfirst )
Save Earth
To access the last character of the string Subscript 0 or –ve n(where n is length of the
>>>print (myfirst[-1]) string) displays the first element.
h Example : A[0] or A[-5] will display “H”
To access the third last character of the string
>>>print (myfirst[-3])
r
String traversal using for loop
A=‟Welcome”
for i in A:
print (i)
letter = 'A’
print( ord(letter) )
code = 101
print( chr(code) )
Python String Methods / Functions
Python has a set of built-in methods that you can use on strings.
Method Description
isalnum() Returns True if all characters in the string are alphanumeric, else FALSE
Python String Methods / Functions
Python has a set of built-in methods that you can use on strings.
Method Description
isalpha() Returns True if all characters in the string are in the alphabet, FALSE otherwise
isdecimal() / Returns True if all characters in the string are decimals. Decimal characters are those that can be used to
isnumeric() form numbers in base 10.
isupper() Returns True if all characters in the string are upper case
islower() Returns True if all characters in the string are lower case
Python String Methods / Functions
Python has a set of built-in methods that you can use on
strings.
Method Description
strip() Returns a trimmed version of the string. Return a copy of the string with the leading and trailing
characters removed. The chars argument is a string specifying the set of characters to be removed.
swapcase() Swaps cases, lower case becomes upper case and vice versa
startswith() Returns true if the string starts with the specified value
str.startswith(prefix)
Python String Methods / Functions
Python has a set of built-in methods that you can use on strings.
Method Description
upper() Converts a string into upper case
split() Splits the string at the specified separator, and returns a list
replace() Returns a string where a specified value is replaced with a specified value
string.replace(oldvalue, newvalue)
String handling functions
Function Example Result
word ← "Algorithm"
LEN(str) 9
OUTPUT LEN(word)
SUBSTRING(start, end,
OUTPUT(3,6,word) "orit"
str)
POSITION(str, char) POSITION(word, 'r') 4
b ← LEN(a) – 30 b ← 37 - 30
b ←7
c ← SUBSTRING(0,b,a) c ← SUBSTRING(0,7,a)
c ← "The qual"
d ← SUBSTRING(0,LEN(c)-2,c) d ← SUBSTRING(0,6,c)
d ← "The qua"
The difference between these only matters if, in the statements of the
procedure, the value of the parameter is changed, in case of pass by ref.
If there are several parameters, they should all be passed by the same method
and the BYVALUE or BYREF keyword need not be repeated.
By default, it BYVALUE
The scope of a variable refers to where in the
program a variable or constant can be
accessed. The scope of a variable can either
be local to a particular subroutine, or part of a
subroutine, or global to the whole program.
A local variable is a variable that is only accessible within a
specific part of a program. These variables are usually local to a
subroutine and are declared or defined within that routine.
Such variables are distinct from each other, because the data of
each variable is stored in a separate place in main memory.
If you do not use functions, any variables you define will have
global scope.
6
1
6
Study the following program that is expressed in pseudocode.
Trace the pseudocode and enter the number that will be when the program is run.
Study the following program that is expressed in pseudocode.
Answer : 18
Trace the pseudocode and enter the number that will be when the program is run.
Pre-defined subroutines are provided to carry out common tasks.
They are either built-in as part of a programming language, or they are part of modules that can be
imported from external libraries of code.
For example, many programming languages have a math library that will contain a pre-defined
subroutine for finding the square root of a number.
To use code from an external library, you must import it into your program. To use it, you will often
have to prefix the name of the subroutine with the name of the library.
Data Structures
Any facility that holds more than one item of data is known as
a data structure. Therefore, an array / a list is a data structure.
Imagine that a score table in a game needs to record ten
scores. One way to do this is to have a variable for each
score:
• Store 11 high scores
Array is a container which can hold a fix number of items and these items should be of the same type. Most of the data
structures make use of arrays to implement their algorithms.
Following are the important terms to understand the concept of Array.
Naming arrays - Arrays are named like variables. The number in brackets determines how many data items the array can hold.
Index − Each location of an element in an array has a numerical index, which is used to identify the element.
Array Representation
Arrays can be declared in various ways in different languages. Below is an illustration.
arr[10]= [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
As per the above illustration, following are the important points to be considered.
Index starts with 0.
Array length is 10 which means it can store 10 elements.
Each element can be accessed via its index. For example, we can fetch an element at index 6 as 7.
Python Lists
A list can have any number of elements. They are similar to arrays.
Lists can hold all and any kinds of datas: integers (whole numbers), floats, characters, texts and many more.
Empty list
To define an empty list you should use brackets. Brackets is what tells Python that the object is a list.
Lists can hold both numbers and text. Regardless of contents, they are accessed in the same fashion.
To access a list add the id between the brackets, such as list[0], list[1] and so on.
Define list
friends = ["John","Paul","Fred","Ringo"]
for loop in range(4):
print(friends[loop])
You can use the loop counter to step through each value. First
friends[0], then friends[1] and so on…
Lists
friends = ["John","Paul","Fred","Ringo"]
print(friends)
Append Operation
Here, we add a data element at the end of the array using the python in-built
append() method.
Syntax
listname.append(value to be added at the end of an array)
extend()
The extend() method adds the specified list elements (or array) to the end of the current list.
Syntax:
List1name.extend(list2name / arrayname to be added at the end of list1)
Deleting array elements
Deletion refers to removing an existing element from the array and re-organizing all elements of an array.
Here, we remove a data element at the middle of the array using the python in-built remove() method.
remove() method only removes the first occurrence of the specified value.
Deleting array elements
pop ()
The pop() method removes the item at the given index from the array and returns the removed item.
Syntax :
listname.pop(index/position of element to be removed)
Example
Delete the second element of the cars array:
cars.pop(1)
• city.pop(4) removes item 4 from the list and returns the value “d”
• city.pop() without a parameter would remove and return the last item “s”
Interrogating lists
• And if you know a value is in the list, you can find out where
• Try this code:
friends = ["John","Paul","Fred","Ringo"]
print(friends.index("Paul"))
Appending a new list element
• Try this code:
friends = ["John","Paul","Fred”,"Ringo"]
print(friends)
friends[4] = "Stuart"
print(friends)
friends = ["John","Paul","Fred","Ringo"]
print(friends)
friends.append("Stuart")
print(friends)
• It should work! Why?
#reverse the elements of a string
name = input("Please enter name: ")
name2=[ ]
print("length = ",len(name))
for n in range(len(name)):
m = len(name) - n -1
name2.append(name[m])
print(name2)
Interrogating lists
• You can search lists line by line, or you can use a simpler shortcut
• Try this code:
friends = ["John","Paul","Fred","Ringo"]
if "Paul" in friends:
print("Found him")
else:
print("Not there")
Reading list methods
• What word will be printed?
word =["c","b","e","g","h","d"]
word[0] = "e“
print(word)
word.pop(2)
print(word)
word.remove("g")
print(word)
word.insert(0,"z")
print(word)
word.pop(3)
print(word)
word.insert(3,"r")
print(word)
word.pop()
print(word)
word.append("a")
print(word)
Now, you have an index for each row as well as an index for each column. To access an element, you need to
specify a column number and a row number. These are known as a column index and a row index.
To retrieve, insert, or delete a value from a two-dimensional array, you must specify two index values.
Output :
File handling
A file is a sequence of data that is stored in secondary memory (usually on a disk drive).
Files can contain any data type, but the easiest files to work with are those that contain text.
A special character or sequence of characters is used to mark the end of each line. There are numerous conventions
for end-of-line markers.
Python uses a single character called newline as a marker. A newline character is generated, when <Enter> key is
pressed and marked as ‘\n’ in python.
The file identifier will usually be the name of the file. The following file modes are used:
• READ : for data to be read from the file
• WRITE : for data to be written to the file. A new file will be created and any existing data in the
file will be lost.
• APPEND : for data to be added to the file, after any existing data.
Data is read from the file (after the file has been opened in READ mode) using the READFILE
command as follows:
The Variable should be of data type STRING. When the command is executed, the next line of text in the file is read
and assigned to the variable.
It is useful to think of the file as having a pointer which indicates the next line to be read. When the file is opened,
the file pointer points to the first line of the file. After each READFILE command is executed the file pointer moves
to the next line, or to the end of the file if there are no more lines.
The function EOF is used to test whether the file pointer is at the end of the file. It is called as follows:
This function returns a Boolean value: TRUE if the file pointer is at the end of the file and FALSE otherwise.
Data is written into the file (after the file has been opened in WRITE or APPEND mode) using the
WRITEFILE command as follows:
When the command is executed, the string is written into the file and the file pointer moves to the next line.
Files should be closed when they are no longer needed using the CLOSEFILE command as follows:
This example uses the operations together, to copy all the lines from FileA.txt to FileB.txt, replacing any blank lines by
a line of dashes.
To handle data files in python, we need to have a file object. Object can be created by using open()
function
Syntax of open() function is
file_object = open(filename [, access_mode])
( filename ) is the name of the file on secondary storage media. The name can include the description of
path, in case, the file does not reside in the same folder / directory in which we are working.
The second parameter (access_mode) describes how file will be used throughout the program. This is an
optional parameter and the default access_mode is reading.
r will open the text file for reading only
r+ will open a text file for both reading and writing purpose.
w will open a text file for writing
w+ will open a text file for both reading and writing purpose.
a mode allow us to append data in the text file
a+ will open a text file for both reading and appending purpose.
file= open("Sample.txt","r+")
<filevar>.read() seek()method can be used to position the file object at particular place in the
<filevar>.readline() file. It's syntax is :
<filevar>.readlines() fileobject.seek(offset [, reference point])
reference point is used to calculate the position of fileobject in the file in bytes.
Offset is added to reference point to get the position.
Value reference point
0 beginning of the file
1 current position of file
2 end of file
default value of from_what is 0, i.e. beginning of the file.
DELHI PUBLIC SCHOOL BANGALORE EAST
Cambridge International
Academic Session 2022-23
2023-24
1. Write a program to store data about DVDs that are for sale. It should start by asking the
user to enter 5 film titles using a loop. The program should then print out the list of film
titles. [4]
2. Add to the previous program so that, once finished, the user should be asked to enter
the name of a film that they want to see. The program should then check whether that
film is in the list or not.
1
3. Add to the previous program so
that there is a second list, this time
with the Director for each film. The finished program should ask the user for the name of
the first film (which will be stored in the first list) and the name of the director for that film
(which will be stored in the second list).
The user should then be able to choose a number and the program will print out the
name of that film and the director for that film.
4. Extend the previous program even further. This time the user should be able to enter the
name of a film. If the film is present then the program should find its position (index) and
use that information to print out the director of that film.
2
3
DELHI PUBLIC SCHOOL BANGALORE EAST
Cambridge International
Academic Session 2022-23
2023-24
Answer 2.
Answer 3.
Answer 4.
Answer 5, 6 and 7
Answer 8
1
1. Paula wants to check your understanding before she hires you as a new programmer. Answer the following
questions about this list (called ‘royals’) to show your understanding:
Elizabeth Charles William George Henry Andrew
a. Who is royals[2]?
Answer :
William
b. Write out the list after this line of code has been run: royals[5] = “Beatrice”
Answer :
Elizabeth,Charles,William,George,Henry,Beatrice
2. Phil has written some Python code, but it won’t run. He has made three syntax errors – highlight them and
explain each one to Phil.
scores = [0]*2
scores0 = input(“Enter matches won: ”)
scores[1] = input(“Enter matches drawn: ”)
scores[2] = input(“Enter matches lost: ”)
points = 3*scores[0] + 1*scores[1]
print(points)
Answer:
scores = [0]*2
scores = [0]*3
scores0 = input(“Enter matches won: ”)
scores[0] = input(“Enter matches won: ”)
scores[1] = input(“Enter matches drawn: ”)
scores[2] = input(“Enter matches lost: ”)
points = 3*scores[0] + 1*scores[1]
points = 3*int(scores[0]) + 1*int(scores[1])
print(points)
2
1. Line 1: Three values need to be stored, so the list declaration needs to say 3
3. Line 5: The inputs will be text by default and can’t be multiplied. Either the 3 inputs will need to be
int(input(…)) OR line 5 will have to cast the values as integers.
3. Olivia has been looking at a program that will collect in the names of athletes as they finish a race and then
search for a particular competitor. Add some comments to explain to her how the program works.
#
results = []
more = “y”
#
while more == “y”:
name = input(“Enter the next name: ”)
results.append(name)
more = input(“More names to add? (y/n): ”)
name = input(“Who do you want to find? ”)
#
if name in results:
#
print(name,”finished in position”,results.index(name))
else:
print(name,”not found”)
Answer
# This declares an empty list called results.
results = []
more = “y”
# This section asks for a name and adds (appends) it to the
# end of the list.
while more == “y”:
name = input(“Enter the next name: ”)
results.append(name)
more = input(“More names to add? (y/n): ”)
name = input(“Who do you want to find? ”)
# This line checks to see if the name is in the list
#
if name in results:
# If the name is in the list then it prints out the
# position (index) of that name
print(name,”finished in position”,results.index(name))
else:
print(name,”not found”)
3
4. Predict the output you would see if you were to run this program.
friends = ["Fred","Paul","George","Ringo"]
print("One of my friends is called ",friends[1])
print(friends)
Answer :
7. The following code will create an empty list of 4 names, then ask the user for a name to place in the list. The
last line is just there so we can see what the list looks like at the end.
friends = [None] * 4
name = input("Enter the name of a friend: ")
friends[0] = name
print(friends)
Answer:
friends = [None] * 4
name = input("Enter the name of a friend: ")
friends[0] = name
name = input("Enter the name of a friend: ")
friends[1] = name
name = input("Enter the name of a friend: ")
friends[2] = name
name = input("Enter the name of a friend: ")
friends[3] = name
print(friends)
4
Add more code that will ask the user for more names to complete the list. The last line should still print the
complete list out.
8. Write a program for a takeaway restaurant. It should start by asking the user to enter 5 dishes that they sell.
The program should then print out the list of dishes so the user can check it is right.
Answer :
meals = [None] * 5
name = input("Enter the name of a meal: ")
meals[0] = name
name = input("Enter the name of a meal: ")
meals[1] = name
name = input("Enter the name of a meal: ")
meals[2] = name
name = input("Enter the name of a meal: ")
meals[3] = name
name = input("Enter the name of a meal: ")
meals[4] = name
print(meals)
9. Add to the previous program so that, once finished, the user should be asked to enter a number for which
dish they want. The program should then print out the name of the dish they have chosen.
Hint: Remember to use int(input(…))
Answer :
meals = [None] * 5
name = input("Enter the name of a meal: ")
meals[0] = name
name = input("Enter the name of a meal: ")
meals[1] = name
name = input("Enter the name of a meal: ")
meals[2] = name
name = input("Enter the name of a meal: ")
meals[3] = name
name = input("Enter the name of a meal: ")
meals[4] = name
print(meals)
choice = int(input("Which meal do you want to select? "))
print("You have chosen ",meals[choice])