0% found this document useful (0 votes)
27 views241 pages

Comp Paper 2

The document provides an introduction to Python programming, covering its applications, development environment (IDLE), and basic syntax including running programs in Interactive and Script modes. It explains fundamental concepts such as variables, data types, comments, input/output statements, and arithmetic operations, along with examples and exercises for practice. Additionally, it discusses string manipulation, including concatenation and slicing, and emphasizes the importance of using comments and indentation in code.

Uploaded by

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

Comp Paper 2

The document provides an introduction to Python programming, covering its applications, development environment (IDLE), and basic syntax including running programs in Interactive and Script modes. It explains fundamental concepts such as variables, data types, comments, input/output statements, and arithmetic operations, along with examples and exercises for practice. Additionally, it discusses string manipulation, including concatenation and slicing, and emphasizes the importance of using comments and indentation in code.

Uploaded by

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

Objectives

• Know what Python is and some of the applications it


is used for
• Run a simple Python program in Interactive mode
using the input and print functions
• Write, save and run a program in Script mode
• Understand what a syntax error is and how to
interpret an error message
• Know the rules for variable names and use variables
in a program
• Understand the use and value of using comments
Example code
Python’s development environment
• Called IDLE – Integrated Development Environment
• Two Modes:
• Interactive Mode let you see your results as you type them
• This mode uses the Shell window
Python’s development environment
• Script Mode lets you save your program and run it again later
• This mode uses the Editor window
“Hello World!”
• A programming tradition
• A simple program to display text on the screen
• In IDLE’s Interactive Mode, at the prompt, type:
print ("Hello World!")

• Press Enter, the result will be:


Hello World!
Python’s development environment
Getting it wrong - De-bugging
• Syntax errors
• Experiment with errors
• In IDLE type the following erroneous lines:

primt ("Hello World!")


Print ("Hello World!")
print (Hello World!)
print "Hello World!"
De-bugging
De-bugging
De-bugging
• Syntax errors
• Reading interpreter feedback
Using Script mode
• In the Shell window, select File, New File from
the menu
• Type:
print ("What is your name?")
firstname = input()
print ("Hello, ",firstname)
• Save the program as MyFirstPython.py
• Select Run, Run Module or press F5 to execute
(run) the program
Adding comments
• Comments are useful to document your program
and make it easier to understand your code
• They will not affect the way a program runs
• Comments start with a # symbol and appear in red
#Program name: MyFirstPython.py
#firstname is a variable
print ("What is your name?")
firstname = input()
print ("Hello,",firstname)
What is a variable?
• A variable is a location in memory in which you can
temporarily store text or numbers
• It is used like an empty box or the Memory function
on a calculator
• You can choose a name for the box (the “variable name”) and
change its contents in your program

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.

• You can define constants in python program

• Constants are typically shown in uppercase


Definitions of data types
Typical amount of
Data type Type of data Python
memory
Whole number
INTEGER such as 156, 0 - 2 bytes int
54
Number with a
fractional part
REAL 4 bytes float
such as 1.5276, -
68.4, 20.0
A single ASCII
CHAR character such as 1 byte Not used
A, b, 3, ! or space
Zero or more 1 byte per character in the
STRING str
characters string
Theoretically just one bit, but
Can only take the
in a high level language such
BOOLEAN values True or bool
as Python, Pascal etc., one
False
Data type Description Example
Integer An integer is a whole number. The numbers can -5, 123, 0
positive or negative but they must be whole. This
means that they do not have any decimal places.

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.

Null A null value is used to indicate ‘nothing’; the lack Null


of any value, of any type of data.
String: is an ordered sequence of letters/characters. They are enclosed in single
quotes (‘ ’) or double (“ “). The quotes are not part of string. They only tell the
computer where the string constant begins and ends.
?????
Input and output statements
• In Python, you can combine a user prompt with an
input function:
firstname = input (“What is your name? ”)
• This statement first displays the message “What is
your name?” and then waits for the user to enter
some text and press Enter
• The response is then assigned to the variable
firstname
• To output , print( ) is used.
Inputting numeric variables
• In Python, all input is accepted as a string
• Therefore if you are inputting an integer or real number,
you have to convert it before it can be used in a
calculation
tickets = input(“Please enter number of tickets required:”)
tickets = int(tickets)

• Or alternatively, in a single statement:


tickets = int (input(“Please enter number of tickets required:”))
conversion functions
• High-level programming languages have built-in functions which are part of the
language
• Examples of functions:

• int(s)converts a string s to an integer


• float(s) converts a string s to a number with a decimal point
• str(x)converts an integer or number with a decimal point to a
string
• ord(‘a’) evaluates to 97, using ASCII
• chr(97) evaluates to ‘a’
x = str(3)
y = int(3)
z = float(3)
By default python’s print() function ends with a newline.

Python’s print() function comes with a parameter called ‘end’. By


default, the value of this parameter is ‘\n’, i.e. the new line character.

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)

• The operator DIV is used for integer division, also


known as quotient
• MOD (modulus) is used to find the remainder when
dividing one integer by another
• What is the result of the following operations?
• weeks ← 31 DIV 7
• daysLeft ← 31 MOD 7
MOD and DIV
• weeks ← 31 DIV 7
• The variable weeks is assigned the value 4
• This is because 7 goes into 31 four times (remainder 3)
• daysLeft ← 31 MOD 7
• The variable daysLeft is assigned the value 3
• This is because the remainder after the division is 3
Orders of precedence
• Remember BIDMAS
• Brackets
• Indices
• Division
• Multiplication
• Addition
• Subtraction
• Calculate: x ← (5 – 2) + (16 – 6 / 2)
y ← 7 * 3 + 10 / 2
Are brackets needed in the first expression?
Using comments
• You should use comments in your programs:
• to describe the purpose of the program
• to state the author of the program
• to explain what the code does

• Pseudo-code comments start with a # symbol


• In Python, comments start with #
• In C#, comments start with //
• In VB, comments start with '

• Comments are ignored when your program is


translated to machine code and executed
Indentation
Python relies on indentation (whitespace at the beginning of a line) to define scope in the
code. Other programming languages often use curly-brackets for this purpose.
Exercise:
1. Write a program to find largest of three numbers, a, b and c. Print appropriate
message.
2. Write an if statement that asks for the user's name via input() function. If the name is
"Bond" make it print "Welcome on board 007." Otherwise make it print "Good
morning NAME". (Replace Name with user's name)
3. WAP for water park entry fee where calculate the entry fee as per given requirement,
if weekend rate is applied, and the visitor is junior, fee is Rs 2 otherwise Rs 5. If
weekend rate is not applied and visitor is junior, Rs 1 otherwise Rs 2 (Using nested if)
4. 4. WAP to read remaining charge in the battery and print appropriate message for
<=20%, 100% and otherwise. (Using if…elif..)
5. WAP to print sum of negative numbers, sum of positive numbers and sum of positive
odd numbers from a list of numbers entered by the user. The loop should end when
the number entered is 0.
Print First 10 natural numbers using while loop
Display Fibonacci series up to 10 terms

Print the following pattern using while loop


Display Fibonacci series up to 10 terms
Print the following pattern using while loop
5 4 3 2 1
4 3 2 1
3 2 1
2 1
1
The range() Function
To loop through a set of code a specified number of times, we can use
the range() function,

The range() function returns a sequence of numbers, starting from 0 by default,


and increments by 1 (by default), and ends at a specified number. range( )
generates a list of values starting from start till stop-1.
Output:
Example:

1. Print multiplication table of given number

2. Accept number from user and calculate the sum of all number between 1 and given
number

3. Python program to display all the prime numbers within a range


2. Accept number from user and calculate the sum of all number between 1
and given number
3. Python program to display all the prime numbers within a range
CPT ASSIGNMENTS : SUBMIT on WEDNESDAY
1 : Python program to display -10 to -1 using for loop
2 : Python program to find the factorial of any number
Example = factorial of 5 = 5x4x3x2x1 = 120

3 : Python program to display Reverse a given integer number

4 : Python program to display


the sum of the series 2 +22 + 222 + 2222 + .. n terms
take value of n from the user.
OUTPUT:
OUTPUT:
OUTPUT:
OUTPUT:
For example, the following pseudocode algorithm uses nested loops
to provide a solution for the problem set out here:
» calculate and output highest, lowest, and average marks awarded
for a class of twenty students
» calculate and output largest, highest, lowest, and average marks
awarded for each student
» calculate and output largest, highest, lowest, and average marks
for each of the six subjects studied by the student; each subject has
five tests.
» assume that all marks input are whole numbers between 0 and
100.
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” is a String is a list of sequence of char data type.


It is an ordered set of values enclosed in square brackets [].
Values in the string can be modified. As it is set of values, we can use index in
square brackets [] to identify a value belonging to it.

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

• What will be output?


• What will be output by the program?
x ← "6" + "3"
OUTPUT x
Concatenating strings
firstname ← "Rose"
surname ← "Chan"
fullname ← firstname + " " + surname
OUTPUT fullname

• What will be output? "Rose Chan"


• What will be output by the program
x ← "6" + "3"
OUTPUT x
"63"
Python Strings

Strings in python are surrounded by either single quotation marks, or


double quotation marks.

'hello' is the same as "hello".

You can display a string literal with the print() function:

Strings are Arrays


Strings in Python are arrays of bytes representing unicode characters.
Square brackets can be used to access elements of the string.
Python - Slicing Strings
Specify the start index and the end index, separated by a colon, to
return a part of the string (slicing).

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 first character of the string


>>>print (myfirst[0] )
S
Positive subscript helps in accessing the string
To access the fourth character of the string from the beginning
>>>print (myfirst[3]) Negative subscript helps in accessing the string
e from the end.

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)

String traversal using while loop


A=‟Welcome”
i=0
while i<len(A)
print (A[i] )
i=i+1
Consider the given figure. Write the output for each print statement.
to find part of a string, known
as a substring.

Suppose that to find the first


two characters of a UK
postcode. specify the starting
position (starting from 0), and
the no of characters that are
required.
postcode = "AB1 2CD“
area =
postcode.subString(0, 2)
print(area)
Output : AB

Each character is associated


with a number that is its
equivalent in ASCII code. You
can convert to and from the
ASCII values for a character.

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

title() Converts the first character of each word to upper case

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

lower() Converts a string into lower 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

• What will be the values of a, b


and c below?
zooName ← "London Zoo"
a ← LEN(zooName)
b ← SUBSTRING(1,4)
c ← POSITION(zooName, 'd')
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

• What will be the values of a, b


and c below?
zooName ← "London Zoo"
a ← LEN(zooName) 10
b ← SUBSTRING(1,4) "ondo"
c ← POSITION(zooName, 'd’) 3
Uppercase and lowercase
• In Python, a string can be converted to uppercase or
lowercase letters as follows:
phrase1 = "Good morning"
phrase2 = "HAPPY BIRTHDAY"
print(phrase1.upper()) #"GOOD MORNING"
print(phrase2.lower()) #"happy birthday"

• What is the output of the following program?


a ← "The quality of mercy is not strained."
b ← LEN(a) – 30
c ← SUBSTRING(0,b,a)
d ← SUBSTRING(0,LEN(c)-1,c)
OUTPUT d
String handling
• What is the output of the following program?
a ← "The quality of mercy is not strained."

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"

OUTPUT d "The qua"


A subroutine is a named block of code that performs a specific task.
What are functions and procedures for?
To save you rewriting same code again and again(reusability), computer
programs are often divided up into smaller sections called subroutines.

A subroutine is a named set of instructions that only executes when it is called


within the program.
A subroutine is written / defined once and can be called no of times.
values can be passed into a subroutine via parameters, and out of a subroutine
via a return value.
There are two types of subroutines : Procedures and Functions.

Procedures and Functions allow for you to:


1. Reuse code
2. Structure your programming
3. Easily incorporate other peoples code
In computer programming, a procedure is an independent code module that
fulfills some concrete task and it does not return any value.
While a function is an independent code which always return a value.
A procedure is a named block of code that performs a specific task. A common procedure that you may use is print() . You can
also create your own procedures. Procedures are designed to run a sequence of code that does not return any value to the
main program. The procedure can be used (called) by another part of the program.
When the procedure is called, control is passed to the procedure.
If there are any parameters, these are substituted by their values, and the statements in the procedure are executed.
Control is then returned to the line that follows the procedure call.
When we define a procedure or a function, and identify the data it can accept, each thing is a Parameter.
When we use the procedure or function within a program, and provide it with an actual piece of data, they are called
Arguments.
Write a program to read name of the user. Define a procedure “greet” to
print hello followed by the user name
Write a program to read name of the user. Define a procedure “greet”
to print hello followed by the user name
The keyword RETURN is used as one of the statements within the body of the function to
specify the value to be returned, which will be the last statement in the function
definition.

A function returns a value that is used when the function is called.


Functions should only be called as part of an expression.
When the RETURN statement is executed, the value returned replaces the function call in
the expression and the expression is then evaluated.
FUNCTION TO FIND MAX OF TWO NUMBERS
Parameters can be passed either by value or by reference to a procedure or a
subroutine.

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.

A reference (address) to that variable is passed to the procedure when it is


called and if the value is changed in the procedure, this change is reflected in
the variable which was passed into it, after the procedure has terminated.

To specify whether a parameter is passed by value or by reference, the keywords


BYVALUE and BYREF precede the parameter in the pseudocode definition of the
procedure.

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.

Parameters that are defined by value can also be considered as


local variables.

Local variables in different subroutines are allowed to have the


same identifier (name).

Such variables are distinct from each other, because the data of
each variable is stored in a separate place in main memory.

Changing the value of a local variable in one subroutine will not


affect the value of any local variables with the same identifier in
other subroutines.
A global variable can be accessed anywhere in a program for the
duration of the program's execution.

A global variable has global scope.

Global variables need to be preserved in memory until the


program has stopped running.

This means global variables can sometimes use more resources


than local variables, which are removed from memory once a
subroutine has ended.

If you do not use functions, any variables you define will have
global scope.

The variables (including parameters) that are defined inside a


function will have local scope. The variables that are defined
outside of a function will have global scope.
1

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

Variables are needed to store values.


If you have a lot of values then storing them all individually makes the code very long-winded.
• How many variables do we need to store these names?

Friend 1: Ananda Friend 2: Paul Friend 3: Kevin

Friend 4: Uwais Friend 5: Diana

Friend 6: Sarah Friend 7: Rob Friend 8: Alison


Starter
• How many variables do we need?
• You could use eight variables. This would work, but there is a better way. It is much simpler to keep
all the related data under one name.
• We do this by using an array.
• Instead of having ten variables, each holding a score, there could be one array that holds all the
related data.

Why use arrays?

A variable holds a single item of data. There may


be a situation where lots of variables are needed to
hold similar and related data. In this situation,
using an array can simplify a program by storing all
related data under one name. This means that a
program can be written to search through an array
of data much more quickly than having to write a
new line of code for every variable. This reduces
the complexity and length of the program which
makes it easier to find and debug errors.
ARRAY

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.

Element− Each item stored in an array is called an element.

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

To output simple print them

Access list items


You can access a list item by using brackets and its index. Python starts counting at zero, that means the first element is
zero.
Creating and reading lists / array
• When using lists/ arrays we can use the index in square brackets to
refer to one element in the list
• highScore[0] is the first element in the list /array(remember that
computers count from 0)
highscore = [125,63,35,12]
print(highscore)
print(highscore[0])
print(highscore[1])
Array / List operations
Following are the basic operations supported by an array.
 Traverse − access all the array elements one by one.
 Insertion − Adds an element at the given index.
 Deletion − Deletes an element at the given index.
 Search − Searches an element using the given index or by the value.
 Update − Updates an element at the given index.

Fetch any element through its index using index() method


Here is an example :
• A = mylist.index(5)

Check for number of occurrences of an element using count() method


Here is an example :
• A = mylist.count(11)

Len( ) returns total number of elements in an array


• X = len(mylist)
Traverse - Accessing Array Element
We can access each element of an array using the index of the element. The below code
shows how
Creating a blank list
• Sometimes you might want to create an empty list and fill in the values
later
• Try this code:
note :
# Blank list
Stepping through lists
Remember FOR loops?
Try this code:

for loop in range(city):


print(loop)
Stepping through lists
Try this code:

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

Append operation is to insert one data element at the end of array.

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)

• You should find you get an error!


Appending to a list
• A list is a fixed size – this one has four values:
friends[0]
friends[1]
friends[2]
friends[3]
• To add an extra one you need to append (add) a new value to the end
The append() list method
• Now try this code:

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.

We can create two types of files,


1. Text file(contains more than a single line of text.) and
2. Binary file(also called Random files contain a collection of data in their binary representation, normally as records
of fixed length. )

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.

Basic operations performed on a data file are:


• Opening a file
• Reading data from the file
• Writing data in the file
• Closing a file
Text File Handling
Text files consist of lines of text that are read or written consecutively as strings.
A file must be opened in a specified mode before any file operations are attempted.

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.

A file should be opened in only one mode at a time.

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

Subject: Computer Science Topic: Arrays worksheet 1


Name: Class: X Roll No. :

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

Subject: Computers Topic: List Worksheet No: 2


Name: Class: X Roll No. :
Answer1.

Answer 2.

Answer 3.

Answer 4.
Answer 5, 6 and 7

Answer 8
1

DELHI PUBLIC SCHOOL BANGALORE EAST


Cambridge International
Academic Session 2022-23
2023-24
Subject: Computers Topic: Arrays Worksheet No: 3
Name: Class: X Roll No. :

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

c. Write the code that would change “Charles” to “Prince of Wales”


Answer :

royals[1] = “Prince of Wales”

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

2. Line 2: A list needs square brackets around the index.

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])

Answer : One of my friends is called Paul

5. Alter the program so that it will print out “Ringo” instead.


Answer : print("One of my friends is called ",friends[3])

6. The first name in the list is wrong.


Add a new line to the program that will change the first name from “Fred” to “John”.
Add this line to the very end of the program so that you can see if it has worked.
friends = ["Fred ", "Paul ", "George","Ringo"]
#add line here

print(friends)

Answer :

friends = ["Fred ", "Paul ", "George","Ringo"]


friends[0] = "John"
print(friends)

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])

You might also like