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 :