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

COMP PAPER 2

The document provides an introduction to Python programming, covering its applications, basic syntax, and development environments (Interactive and Script modes). It explains variables, data types, input/output functions, arithmetic operators, and the importance of comments and indentation in code. Additionally, it includes exercises for practical application and examples of string manipulation and control structures.

Uploaded by

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

COMP PAPER 2

The document provides an introduction to Python programming, covering its applications, basic syntax, and development environments (Interactive and Script modes). It explains variables, data types, input/output functions, arithmetic operators, and the importance of comments and indentation in code. Additionally, it includes exercises for practical application and examples of string manipulation and control structures.

Uploaded by

djay19842020
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 211

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 :

You might also like