Download as pdf or txt
Download as pdf or txt
You are on page 1of 53

CCA62-PYTHON PROGRAMMING

UNIT I
Introduction to Python:
Python is a widely used general-purpose, high level programming language. It was initially
designed by Guido van Rossum in 1991 and developed by Python Software Foundation. It was
mainly developed for emphasis on code readability, and its syntax allows programmers to express
concepts in fewer lines of code.
Python is a programming language that lets you work quickly and integrate systems more efficiently.

There are two major Python versions- Python 2 and Python 3.

• On 16 October 2000, Python 2.0 was released with many new features.
• On 3rd December 2008, Python 3.0 was released with more testing and includes new
features.

Why to use Python:


The following are the primary factors:

1. Python is object-oriented
Structure supports such concepts as polymorphism, operation overloading and
multiple inheritance.
2. Indentation
Indentation is one of the greatest feature in python
3. It’s free (open source)
Downloading python and installing python is free and easy
4. It’s Powerful
• Dynamic typing
• Built-in types and tools
• Library utilities
• Third party utilities (e.g. Numeric, NumPy, sciPy)
• Automatic memory management
5. It’s Portable
• Python runs virtually every major platform used today
• As long as you have a compaitable python interpreter installed, python
programs will run in exactly the same manner, irrespective of platform.
6. It’s easy to use and learn
• No intermediate compile
• Python Programs are compiled automatically to an intermediate form calledbyte
code, which the interpreter then reads.
• This gives python the development speed of an interpreter without the
performance loss inherent in purely interpreted languages.
• Structure and syntax are pretty intuitive and easy to grasp.
7. Interpreted Language
Python is processed at runtime by python Interpreter
8. Interactive Programming Language
Users can interact with the python interpreter directly for writing the programs
9. Straight forward syntax
The formation of python syntax is simple and straight forward which also makes itpopular.

Working with Python Python Code


Execution:

Python’s traditional runtime execution model: Source code you type is translated to bytecode,
which is then run by the Python Virtual Machine (PVM). Your code is automatically compiled, but
then it is interpreted.

Source Byte code Runtime

PVM
m.py m.pyc

Source code extension is .py


Byte code extension is .pyc (Compiled python code)

There are two modes for using the Python interpreter:

• Interactive Mode
• Script Mode
Data types:

The data stored in memory can be of many types. For example, a student roll number is
stored as a numeric value and his or her address is stored as alphanumeric characters.
Python has various standard data types that are used to define the operations possible on
them and the storage method for each of them.

Int:
Int, or integer, is a whole number, positive or negative, without decimals, of
unlimitedlength.

>>>
print(24656354687654+2
)24656354687656
>>>
print(20
)20
>>> a=10
>>>
print(a
)10
# To verify the type of any object in Python, use the type() function:
>>> type(10)
<class 'int'>

Float:

Float, or "floating point number" is a number, positive or negative, containing one or


moredecimals.

Float can also be scientific numbers with an "e" to indicate the power of 10.

>>> y=2.8
>
>
>

2
.
8
>>> y=2.8
>>> print(type(y))
<class 'float'>

Boolean:

Objects of Boolean type may have one of two values, True or False:

>>> type(True)

<class 'bool'>

>>> type(False)

<class 'bool'>

String:

1. Strings in Python are identified as a contiguous set of characters represented in


thequotation marks. Python allows for either pairs of single or double quotes.

• 'hello' is the same as "hello".

• Strings can be output to screen using the print function. For example:
print("hello").

>>> print("ASMW

college")

ASMWcollege

>>> type("ASMW college")

<class 'str'>
List:
⚫ It is a general purpose most widely used in data structures.
⚫ List is a collection which is ordered and changeable and allows duplicate members.
⚫ To use a list, you must declare it first.
⚫ Do this using square brackets and separate values with commas.
⚫ We can construct / create list in many ways.
Ex: >>> list1=[1,2,3,'A','B',7,8,[10,11]]
>>> print(list1)
[1, 2, 3, 'A', 'B', 7, 8, [10, 11]]
Keywords:
The keywords have predefined meaning assigned by the Python Complier. The
keywords are also called as reserved word. All keywords are written in lower case alphabets.
The Python keywords are:
and del for lambda true as elif from
not try assert else global or while break
except if pass with class exec import print
yield continue false in raise def finally is return
Variables:
Variables are nothing but reserved memory locations to store values.
This means that when you create a variable you reserve some space in memory.
Based on the data type of a variable, the interpreter allocates memory and decides
what can be stored in the reserved memory.
Rules for Python variables:
• A variable name must start with a letter or the underscore character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and underscores
(A-z, 0-9, and _ )
• Variable names are case-sensitive (age, Age and AGE are three different
variables)
Assigning Values to Variables:
Python variables do not need explicit declaration to reserve memory space. The
declaration happens automatically when you assign a value to a variable. The equal sign (=)
is used to assign values to variables. The operand to the left of the = operator is the name of
the variable and the operand to the right of the = operator is the value stored in the variable.
For example −
a= 100 # An integer assignment
b = 1000.0 # A floating point
c = "John" # A string
print (a)
print (b)
print (c)
Multiple Assignment:
Python allows you to assign a single value to several variables simultaneously.
For example : a = b = c = 1
Expressions:
An expression is a combination of values, variables, and operators. An expression is
evaluated using assignment operator.
Example: Y=x + 17
Comments :
Comments are non-executable statements. Comments are any text to the right of the #
symbol and is mainly useful as notes for the reader of the program.
There are two types of comments in Python,
1. Single line comments
2. Multiline comments
a. Single line Comments: this comment starts with a hash symbol (#) and are useful
to mention that the entire line till the end should be treated as comments.
Eg. # To find the sum of two number
k=5 # assign 5 to variable k.
b. Multi line Comments: The triple double quotes (“””) or triple single quotes (‘’’)
are called multi line comments or block comments. They are used to enclose a block of
lines as comments.
Eg-1. “”” This is illustrated as multi line comments
To find the sum of two number
Using Triple double quotes “””
Python Type Conversion

In programming, type conversion is the process of converting data of one type to another. For
example: converting int data to str.
There are two types of type conversion in Python.

• Implicit Conversion - automatic type conversion

• Explicit Conversion - manual type conversion

Implicit Type Conversion

In certain situations, Python automatically converts one data type to another. This is known as
implicit type conversion.

Example:
integer_number = 123
float_number = 1.23
new_number = integer_number + float_number
# display new value and resulting data type
print("Value:",new_number)
print("Data Type:",type(new_number))
Output:

Value: 124.23
Data Type: <class 'float'>

Explicit Type Conversion

In Explicit Type Conversion, users convert the data type of an object to required data type.

We use the built-in functions like int(), float(), str(), etc to perform explicit type conversion.
This type of conversion is also called typecasting because the user casts (changes) the data type
of the objects.

Example:
num_string = '12'
num_integer = 23
print("Data type of num_string before Type Casting:",type(num_string))
# explicit type conversion
num_string = int(num_string)
print("Data type of num_string after Type Casting:",type(num_string))
num_sum = num_integer + num_string
print("Sum:",num_sum)
print("Data type of num_sum:",type(num_sum))
Output:

Data type of num_string before Type Casting: <class 'str'>


Data type of num_string after Type Casting: <class 'int'>
Sum: 35
Data type of num_sum: <class 'int'>

Operator:

Operators are special symbols which represents computation. They are applied on
operand(s), which can be values or variables. Same operator can behave differently on
different data types. Operators when applied on operands form an expression. Operators
are categorized as Arithmetic, Relational, Logical and Assignment. Value and variables
when used with operator are known as operands.

1. Arithmetic Operators :

Symbol Description Example


+ Addition >>> 5 + 6
11
- Subtraction >>>10-5
5
* Multiplication >>> 5*6
30
/ Division >>> 10 / 5
2
% Remainder / Modulo >>> 5 % 2
1
** Exponentiation >>> 2**3
8
// Integer Division >>> 7.0 // 2
3.0
2.Relational Operator

Symbol Description Example

< Less than >>> 7<10


True
> Greater Than >>> 7 >10
False
<= Less than or equal to >>> 7<=10
True
>= Greater than or equal >>> 7>=10
to False
!= , <> Not equal to >>> 7!=10
True
== Equal to >>> 7==10
False
3.Logical Operator

Symbol Description Example


or If any one of the >>> 7<=10 or 7
==10
operand is true, then
True
condition becomes
TRUE
and If both the operands >>>7<10 and 7
>20
are true, then the
False
condition becomes
TRUE
not Reverse the state of >>> not 7<10 False
operand / condition
4.Assignment Operator:

Symbol Description Example-1


= Assigned values from >>> x=10 10
right side operands to
left variable.
+= added and assign >>> x+=2 7
back the result
to left operand
-= subtracted and assign >>> x-=2 3
back the
result to left operand
*= multiplied and assign >>> x*=2 10
back the
result to left operand
/= divided and assign >>> x/=2 2
back the
result to left operand
%= taken modulus using >>> x%=2 1
two
operands and assign
the result to left
operand
**= performed >>> x**=2 25
exponential (power)
calculation on
operators and assign
value to the left
operand
//= performed floor >>> x//=2 2.5
division on
operators and assign
value to the left
operand
5.Bitwise Operator:a bit is the smallest unit of data storage and it can have only one of the
two values, 0 and 1. Bitwise operators works on bits and perform bit-by-bit operation.

Symbol Description Example


| Performs binary OR 5 | 3 gives 7
operation
& Performs binary AND 5 & 3 gives 1
operation
~ Performs binary XOR 5 ^ 3 gives 6
operation
^ Performs binary one's ~5 gives -6
complement operation
<< Left shift operator: 0010 << 2 gives 8
The left-hand side
operand bit is
moved left by the
number specified on
the right-hand side
(Multiply by 2)
>> Left shift operator: 100 << 2 gives 1
The left-hand side
operand bit is moved
left by the number
specified on the right-
hand side (Divided by
2)
6.Membership operators: Python has membership operators, which test for
membership in a sequence, such as strings, lists or tuples. There are two membership
operators are:
Symbol Description Example
in Returns True if the >>> x = [1,2,4,6,8]
specified operand is >>> 3 in x false
found in the sequence
Not in Returns True if the >>> x = [1,2,4,6,8]
specified operand is >>> 3 not in x true
found in the sequence
7.Identity Operator: Identity operators compare the memory locations of two objects.
There are two Identity operators are:
Symbol Description Example Example
is Returns True if two variables point >>>X=10 >>> x=[1,2,3]
>>>Y=10 >>> y=[1,2,3]
to the same object and False, >>> X is Y >>> x is y
otherwise true false
is not Returns False if two variables point >>>X=10 >>> x=[1,2,3]
>>>Y=10 >>> y=[1,2,3]
to the same object and True, >>> X is not >>> x is
otherwise Y false not y true
Input Function:
Programs may use the input function to obtain information from the user.
The simplest use of the input function assigns a string to a variable:
x = input()
The parentheses are empty because the input function does not require
any information to do its job. usinginput.py demonstrates that the
input function produces a string value.
Example:
print('Please enter some text:') x = input()
print('Text entered:', x) print('Type:',
type(x))
Since user input always requires a message to the user about the
expected input, the input function optionally accepts a string and prints
just before the program stops to wait for the user to respond.
The statement variable = input("Enter a value: ")
The value entered is a string. You can use the function eval to
evaluate and convert it to a numeric value.
Example: eval("34.5") returns 34.5, eval("345")returns 345.
Example:
radius = int(input("Enter a value for radius: "))
area = radius * radius * 3.14159
print("The area for the circle of radius",radius,"is",area)

Print Function
The print a line of text, and then the cursor moves down to the next line so
any future printing appears on the next line.
Example:
print('Please enter an integer value:')
The print statement accepts an additional argument that allows the
cursor to remain on the same line as the printed text:
print('Please enter an integer value:', end=' ')
Example:
>>> amount = 12618.98
>>> interestRate = 0.0013
>>> interest = amount * interestRate
>>> print("Interest is", format(interest, ".2f "))

Output:Interest is 16.40
UNIT II

Conditional Statement:
If statement:
The if statement contains a logical expression using which data is compared and a
decision is made based on the result of the comparison.
Syntax:
if expression:
statement(s)
Example:
a=3
if a > 2:
print(a, "is greater")
print("done")
if (If-Else):
An else statement can be combined with an if statement. An else statement contains
the block of code (false block) that executes if the conditional expression in the if
statement resolves to 0 or a FALSE value.
Syntax:
if test expression:
Body of if stmts
else:
Body of else stmts
Example:
a=int(input('enter the number'))
if a>5:
print("a is greater")
else:
print("a is smaller than the input given")
If-elif-else:
The elif statement allows us to check multiple expressions for TRUE and execute a
block of code as soon as one of the conditions evaluates to TRUE. Similar to the else, the
elif statement is optional. However, unlike else, for which there can be at most one
statement, there can be an arbitrary number of elif statements following an if.
Syntax :
if test expression:
Body of if stmts
elif test expression:
Body of elif stmts
else:
Body of else stmts

Example:
a=int(input('enter the number'))
b=int(input('enter the number'))
c=int(input('enter the number'))
if a>b:
print("a is greater")
elif b>c:
print("b is greater")
else:
print("c is greater")

Nested If Statement:
Syntax:
if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here
Example:
num = 15
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")

Iteration:
A loop statement allows us to execute a statement or group of statements multiple times
as long as the condition is true.
In Python Iteration (Loops) statements are of three types:
1. While Loop
2. For Loop
3. Nested For Loops

While loop:
Loops are either infinite or conditional. Python while loop keeps reiterating a block of
code defined inside it until the desired condition is met.
The while loop contains a boolean expression and the code inside the loop is repeatedly
executed as long as the boolean expression is true.
The statements that are executed inside while can be a single line of code or a block of
multiple statements.
Syntax:
while(expression):
Statement(s)
Example
i=1
while i<=6:
print("ASMW college")
i=i+1
For loop:
Python for loop is used for repeated execution of a group of statements for the desired
number of times.
It iterates over the items of lists, tuples, strings, the dictionaries and other iterable
objects
Syntax:
for var in sequence:
Example:
1.
numbers = [1, 2, 4, 6, 11, 20]
seq=0
for val in numbers:
seq=val*val
print(seq)
2.
list = ['A','S','M','W']
i=1
for item in list:
print ('college ',i,' is ',item)
i = i+1
Nested For loop:
When one Loop defined within another Loop is called Nested Loops.
Syntax:
for val in sequence:
for val in sequence:
statements
Statements
Example:
for i in range(1,6):
for j in range(0,i):
print(i, end=" ")
print('')
Break:
The break statement terminates the loop containing it and control of the program flows
to the statement immediately after the body of the loop. If break statement is inside a
nested loop (loop inside another loop), break will terminate the innermost loop.
Example:
for letter in "Python": # First Example
if letter == "h":
break
print("Current Letter :", letter )

Continue:
The continue statement is used to skip the rest of the code inside a loop for the current
iteration only. Loop does not terminate but continues on with the next iteration.
Example:
for val in "string":
if val == "i":
Continue
print(val)
print("The end")

Strings:
A string is a group/ a sequence of characters.We can use a pair of single or double
quotes. Every string object is of the type ‘str’.
Example:
1 >>> a=str('ASMWC')
>>> a
>>>'ASMWC'

2 >>> a=str(asmwc)
>>> a[2]
>>> 'm'
String slices:
A segment of a string is called a slice. Selecting a slice is similar to selecting a
character: Subsets of strings can be taken using the slice operator ([ ] and [:]) with
indexes starting at 0 in the beginning of the string and working their way from -1 at the
end. Slice out substrings, sub lists, sub Tuples using index.
Syntax:[Start: stop: steps]
• Slicing will start from index and will go up to stop in step of steps.
• Default value of start is 0

Example:
>>> x='computer'
>>> x[1:4]
'omp'
>>> x[1:6:2]
'opt'
>>> x[3:]
'puter'
>>> x[:5]
'compu'
String functions:

1. isalnum() -Returns true if string has at least 1 character and all characters are
alphanumeric and false otherwise.
2. isalpha() Returns true if string has at least 1 character and all characters are
alphabetic and false otherwise.
3. isdigit() Returns true if string contains only digits and false otherwise.
4. islower() Returns true if string has at least 1 cased character and all cased characters
are in lowercase and false otherwise.
5. isnumeric() Returns true if a string contains only numeric characters and false
otherwise.
6. isspace() Returns true if string contains only whitespace characters and false
otherwise.
7. istitle() Returns true if string is properly “titlecased” and false otherwise.
8. isupper() Returns true if string has at least one cased character and all cased
characters are in uppercase and false otherwise.
9. replace(old, new [, max]) Replaces all occurrences of old in string with new or at
most max occurrences if max given.
10. split() Splits string according to delimiter str (space if not provided) and returns list
of substrings;
11. count() Occurrence of a string in another string
12. find() Finding the index of the first occurrence of a string in another string.

EXCEPTION HANDLING
Exception handling enables a program to deal with exceptions and
continue its normal execution.
The run-time exceptions immediately terminate a running program. Rather
than terminating the program’s execution, an executing program can detect
the problem when it arises and possibly execute code to correct the issue or
soften it in some way.
An error that occurs at runtime is also called an exception. The run-
time exceptions immediately terminate a running program. Python
provides a standard mechanism called exception handling that
allows the program to catch the error and prompt the user to
correct the issue or soften it in some way
This can be done using Python’s exception handling syntax.

Syntax:
try:
<body>
except <ExceptionType>:
<handler>
Here, <body> contains the code that may raise an exception.
When an exception occurs, the rest of the code in <body> is
skipped. If the exception matches an exception type, the
corresponding handler is executed. <handler> is the code that
processes the exception.
Example:
def divide(a,b):
try:
c = a/b
return c
except :
print ("Error in divide function")
print(divide(10,0))#function call

Output
Error in divide function
None
>>>
A try with multiple except clause
A try statement can have more than one except clause to
handle different exceptions.
The statement can also have an optional else and/or
finally statement, in a syntax like this:
try:
<body>
except <ExceptionType1>:
<handler1>
...
except <ExceptionTypeN>:
<handlerN>
except:
<handlerExcept>
else:
<process_else>
finally:
<process_finally>

The multiple excepts are similar to elifs. When an exception


occurs, it is checked to match an exception in an except clause
after the try clause sequentially. If a match is found, the handler
for the matching case is executed and the rest of the except
clauses are skipped.
Note that the <ExceptionType> in the last except clause may
be omitted. If the exception does not match any of the exception
types before the last except clause, the
<handlerExcept> for the last except clause is executed.
A try statement may have an optional else clause, which is
executed if no exception is raised in the try body.
A try statement may have an optional finally clause, which is
intended to define clean- up actions that must be performed under
all circumstances.

Ex : Multiple excepts
def main():
try:
number1, number2 = eval(input("Enter two numbers, separated by
a comma: ")) result = number1 /
number2 print("Result is", result) except
ZeroDivisionError:
print("Division by zero!") except
SyntaxError:
print("A comma may be missing in the input")
except:
print("Something wrong in the input")
else:
print("No exceptions")
finally:
print("The finally clause is executed") main() #
Call the main function
The try...finally statement
A try statement may include an optional finally block. Code
within a finally block always executes whether the try block raises
an exception or not. A finally block usually contains “clean-up
code” that must execute due to activity initiated in the try block.
The syntax is as follows:
try:
#run this action
first except:
# Run if exception occurs
Finally :
#Always run this code

The order of the statement should be:


try -> except -> else -> finally

Example: to demonstrate finally


def
mai
n():
try:
num = int(input("Enter the number "))
re = 100/num
except:
print ("Something is
wrong") else:
print ("result is ",re)
finally :
print ("finally program ends")
main()
Output
Enter the number 15
result is
6.666666666666667
finally program ends
>>>
UNIT-III
Functions:
Function is a group of related statements that perform a specific task.
Uses:
• Functions help break our program into smaller and modular chunks.
• As our program grows larger and larger, functions make it more organized and
manageable.
• It avoids repetition and makes code reusable.
Basically, we can divide functions into the following two types:
1. Built-in functions - Functions that are built into Python.
Ex: abs(),all().ascii(),bool()………so on….
integer = -20
print('Absolute value of -20 is:', abs(integer))
Output: Absolute value of -20 is: 20
2. User-defined functions - Functions defined by the users themselves.
Ex:def add_numbers(x,y):
sum = x + y
return sum
print("The sum is", add_numbers(5, 20))
Output: The sum is 25
Python Function Declaration
A function definition consists of the function’s name, parameters, and
body.
The syntax for defining a function is as follows:
def functionName(list of parameters):
Statements # Note that the statement(s) must be indented return

➢ A function contains a header and body. The header begins with the
def keyword, followed by the function’s name known as the
identifier of the function and parameters, and ends with a colon.
➢ The variables in the function header are known as formal parameters
or simply parameters. When a function is invoked, you pass a value
to the parameter. This value is referred to as an actual parameter or
argument. Parameters are optional; that is, a function may not have
any parameters.
➢ Statement(s) – also known as the function body – are a nonempty
sequence of statements executed each time the function is called.
This means a function body cannot be empty, just like any
indented block.
➢ Some functions return a value, while other functions perform
desired operations without returning a value. If a function
returns a value, it is called a value- returning function.
Calling a Function
Calling a function executes the code in the function. In a
function’s definition, you define what it is to do. To use a
function, you have to call or invoke it. The program that calls the
function is called a caller. There are two ways to call a function,
depending on whether or not it returns a value. If the function
returns a value, a call to that function is usually treated as a value.

For example,
larger = max(3, 4)
Calls max(3, 4) and assigns the result of the function to the variable
larger.
Another example of a call that is treated as a value is
print(max(3, 4))
This prints the return value of the function call max (3, 4).

Example:
max(num1, num2):
if num1 >
num2:
result =
num1
else:
result =
num2 return
result
def main():
i=5
j=2

k = max(i,j)# Call the max function


print("The larger number of", i, "and", j, "is", k)
main() # Call the main function
Output
The larger number of 5 and 2 is 5

*args and **kwargs in Python


In Python, we can pass a variable number of arguments to a function using special
symbols. There are two special symbols:

1. *args (Non Keyword Arguments)

2. **kwargs (Keyword Arguments)

We use *args and **kwargs as an argument when we are unsure about the number of
arguments to pass in the functions.
Python *args

Python has *args which allow us to pass the variable number of non keyword
arguments to function.
In the function, we should use an asterisk * before the parameter name to pass
variable length arguments. The arguments are passed as a tuple and these passed
arguments make tuple inside the function with same name as the parameter excluding
asterisk *.
Example :

def adder(*num):
sum = 0
for n in num:
sum = sum + n

print("Sum:",sum)

adder(3,5)
adder(4,5,6,7)
adder(1,2,3,5,6)

When we run the above program, the output will be

Sum: 8
Sum: 22
Sum: 17

Python **kwargs

Python passes variable length non keyword argument to function using *args but
we cannot use this to pass keyword argument. For this problem Python has got a solution
called **kwargs, it allows us to pass the variable length of keyword arguments to the
function.
In the function, we use the double asterisk ** before the parameter name to
denote this type of argument. The arguments are passed as a dictionary and these
arguments make a dictionary inside function with name same as the parameter excluding
double asterisk **.
Example:

def intro(**data):
print("\nData type of argument:",type(data))

for key, value in data.items():


print("{} is {}".format(key,value))

intro(Firstname="Yaazh", Lastname="vendhan", Age=22, Phone=1234567890)


intro(Firstname="Shree", Lastname="Shakthi", Email="shreeshakthi@nomail.com",
Country="USA", Age=25, Phone=9876543210)
When we run the above program, the output will be

Data type of argument: <class 'dict'>


Firstname is Yaazh
Lastname is vendhan
Age is 22
Phone is 1234567890

Data type of argument: <class 'dict'>


Firstname is Shree
Lastname is Shakthi
Email is shreeshakthi@nomail.com
Country is USA
Age is 25
Phone is 9876543210

List:
• It is a general purpose most widely used in data structures
• List is a collection which is ordered and changeable and allows duplicate members.
(Grow and shrink as needed, sequence type, sortable).
• To use a list, you must declare it first.
• Do this using square brackets and separate values with commas.
• We can construct / create list in many ways.
Example:
list1=[1,2,3,'A','B',7,8,[10,11]]
>>> print(list1)
[1, 2, 3, 'A', 'B', 7, 8, [10, 11]]
--------------------------
>>> x=list()
>>> x []
--------------------------
>>> tuple1=(1,2,3,4)
>>> x=list(tuple1)
>>> x [1, 2, 3, 4]

List operations:
These operations include indexing, slicing, adding, multiplying, and checking for
membership
Basic List Operations:
Lists respond to the + and * operators much like strings; they mean concatenation and
repetition here too, except that the result is a new list, not a string.
List slices:
>>> list1=range(1,6)
>>> list1
range(1, 6)
>>> print(list1)
range(1, 6)
>>> list1=[1,2,3,4,5,6,7,8,9,10]
>>> list1[1:]
[2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> list1[:1]
[1]
>>> list1[2:5]
[3, 4, 5]
>>> list1[:6]
[1, 2, 3, 4, 5, 6]
>>> list1[1:2:4]
[2]
>>> list1[1:8:2]
Tuples:
• A tuple is a collection which is ordered and unchangeable.
• In Python tuples are written with round brackets.
• Supports all operations for sequences.
• Immutable, but member objects may be mutable.
• If the contents of a list shouldn’t change, use a tuple to prevent items from
accidently being added, changed, or deleted.
• Tuples are more efficient than list due to python’s implementation.
Example:
>>> x=(1,2,3)
>>> print(x)
(1, 2, 3)
>>> x (1, 2, 3)
>>> x=()
>>> x ()
----------------------------
>>> x=[4,5,66,9]
>>> y=tuple(x)
>>> y (4, 5, 66, 9)
-----------------------------
Access tuple items:
Access tuple items by referring to the index number, inside square brackets
>>> x=('a','b','c','g')
>>> print(x[2])
c
Change tuple items:
Once a tuple is created, you cannot change its values. Tuples are unchangeable.
>>> x=(2,5,7,'4',8)
>>> x[1]=10
Traceback (most recent call last): File "<pyshell#41>", line 1, in x[1]=10
TypeError: 'tuple' object does not support item assignment
>>> x
(2, 5, 7, '4', 8) # the value is still the same
Count (): Returns the number of times a specified value occurs in a tuple
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> x.count(2)
4
Index (): Searches the tuple for a specified value and returns the position of where it was
found
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> x.index(2)
1
Length ():To know the number of items or values present in a tuple, we use len().
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> y=len(x)
>>> print(y)
12

Sets:
Sets are like lists in that you use them for storing a collection of elements.
The element in sets are non duplicate and are not placed in any particular order.

Creating Sets
Python provides a data structure that represents a mathematical
set. As with mathematical sets, elements of Set are enclosed
inside a pair of curly braces ({ }). The elements are non-duplicate,
separated by commas. You can create an empty set, or you can
create a set from a list or a tuple, as shown in the following
examples:
s1 = set( ) # Create an empty set
s2 = {1, 3, 5} # Create a set with
three elements
s3 = set([1, 3, 5]) # Create a set
from a tuple

Example:
Operations on Sets:
s1 = {1, 2, 4}
s1.add(6)
print(s1)#prints {1, 2, 4, 6}
print(len(s1))
#prints 4
print(max(s1))
#prints 6
print(min(s1))
#prints 1
print(sum(s1))
#prints 13
print(3 in s1)
#prints False
s1.remove(4)
print(s1) #prints
{1,2,6)
s1 = {1, 2, 4}
s2 = {1, 4, 5, 2, 6}
print(s1.issubset(s2)) # s1 is a subset of s2
#prints True
s1 = {1, 2, 4}
s2 = {1, 4, 5, 2, 6}
print(s2.issuperset(s1)) # s2 is a superset of s1
#prints True
s1 = {1, 2, 4}
s2 = {1, 4, 2}
print(s1 == s2)#prints True
print(s1 != s2)#prints False

Set Operations
Python provides the methods for performing set union, intersection,
difference, and symmetric difference operations.
Example:
s1 = {1, 4, 5, 6}
s2 = {1, 3, 6, 7}
print(s1.union(s2))
print(s1 | s2)
print(s1.intersection(s2))
print(s1 & s2)
print(s1.difference(s2))
print(s1 - s2)
print(s1.symmetric_difference(s2))
print(s1 ^ s2)
Output:
{1, 3, 4, 5, 6, 7}
{1, 3, 4, 5, 6, 7}
{1, 6}
{1, 6}
{4, 5}
{4, 5}
{3, 4, 5, 7}
{3, 4, 5, 7}
>>>

Python zip()

The zip() function takes iterables (can be zero or more), aggregates them in a tuple, and
returns it.
Example:
languages = ['Java', 'Python', 'JavaScript']
versions = [14, 3, 6]

result = zip(languages, versions)


print(list(result))

# Output: [('Java', 14), ('Python',


3), ('JavaScript', 6)]

frozenset()

Frozen set is just an immutable version of a Python set object. While elements of a
set can be modified at any time, elements of the frozen set remain the same after creation.
Due to this, frozen sets can be used as keys in Dictionary or as elements of another set.
But like sets, it is not ordered (the elements can be set at any index).
The syntax of frozenset() function is:

frozenset([iterable])

Example : Working of Python frozenset()


# tuple of vowels
vowels = ('a', 'e', 'i', 'o', 'u')

fSet = frozenset(vowels)
print('The frozen set is:', fSet)
print('The empty frozen set is:', frozenset())

# frozensets are immutable


fSet.add('v')
Run Code
Output

The frozen set is: frozenset({'a', 'o', 'u', 'i', 'e'})


The empty frozen set is: frozenset()
Traceback (most recent call last):
File "<string>, line 8, in <module>
fSet.add('v')
AttributeError: 'frozenset' object has no attribute 'add'
nset([iterable])
UNIT IV
Using Lists

A list refers to a collection of objects; it represents an ordered sequence of data. In


that sense, a list is similar to a string, except a string can hold only characters. We may access
the elements contained in a list via their position within the list. A list need not be
homogeneous; that is, the elements of a list do not all have to be of the same type.
Like any other variable, a list variable can be local or global, and it must be defined
(assigned) before it is used. The following code fragment declares a list named lstthat holds the
integer values 2, −3, 0, 4, −1:
lst = [2, -3, 0, 4, -1]

The right-hand side of the assignment statement is a literal list. The elements of the list appear
within square brackets ([]), the elements are separated by commas. The following statement:
a = []

assigns the empty list to a. We can print list literals and lists referenced through variables:
lst = [2, -3, 0, 4, -1] # Assign the list
print([2, -3, 0, 4, -1]) # Print a literal list
print(lst) # Print a list variable

The above code prints

[2, -3, 0, 4, -1]


[2, -3, 0, 4, -1]

We can access individual elements of a list using square brackets:


lst = [2, -3, 0, 4, -1] # Assign the list
lst[0] = 5 # Make the first element 5
print(lst[1]) # Print the second element
lst[4] = 12 # Make the last element 12
print(lst) # Print a list variable
print([10, 20, 30][1]) # Print second element of literal list

This code prints


-3
[5, -3, 0, 4, 12]
20
The elements of a list extracted with [] can be treated as any other variable;
for example,
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
# Print the fourth element
print(nums[3])
# The third element is the average of two other
elements
nums[2] = (nums[0] + nums[9])/2;
# Assign elements at indices 1
and 4 from user input # using
tuple assignment
nums[1], nums[4] = eval(input("Enter a, b: "))

The expression within [] must evaluate to an integer; some examples include

• an integer literal: a[34]


• an integer variable: a[x] (x must be an integer)
• an integer arithmetic expression: a[x + 3] (x must be an integer)
• an integer result of a function call that returns an integer: a[max(x, y)] (max must
return an integer)
• an element of another list: a[b[3]] (element b[3] must be an integer)

List Assignment and Equivalence

Given the assignment


lst = [2, 4, 6, 8]

the expression lstis very different from the expression lst[2]. The expression lst is a
reference to the list, while lst[2] is a reference to a particular element in the list, in this
case the integer 6. The integer 6 is immutable. A literal integer cannot change to be
another value. Six is always six. A variable, of course, can change its value and its
type through assignment. Variable assignment changes the ob- ject to which the
variable is bound.

a = [10, 20, 30, 40]


b = [10, 20, 30, 40]
1
print('a =', a)
print('b =', b)
b[2] = 35
print('a =', a)
9.1
print('b =',
List
b)
Bounds
In the following code fragment:
a = [10, 20, 30, 40]

All of the following expressions are valid: a[0], a[1], a[2] and a[3]. The expression a[4] does
not represent a valid element in the list. An attempt to use this expression, as in
a = [10, 20, 30, 40]
print(a[4]) # Out-of-bounds access
Slicing

We can make a new list from a portion of an existing list using a technique known
as slicing. A list slice is an expression of the form

list [begin :end ]

where

• list is a list—a variable referring to a list object, a


literal list, or some other expression that evaluates to
a list,
• begin is an integer representing the starting index of a subsequence
of the list, and
• end is an integer that is one larger than the index of the last element
in a subsequence of the list.

If missing, the begin value defaults to 0. A begin value less than zero is treated as zero.
If the end value is missing, it defaults to the length of the list. An end value greater than
the length of the list is treated as the length of the list.
Example:
lst = [10, 20, 30, 40, 50, 60, 70, 80]
print(lst) # [10, 20, 30, 40, 50, 60, 70, 80]
print(lst[0:3]) # [10, 20, 30]
print(lst[4:8]) # [50, 60, 70, 80]
print(lst[2:5]) # [30, 40, 50]
print(lst[-5:-3]) # [40, 50]
print(lst[:3]) # [10, 20, 30]
print(lst[4:]) # [50, 60, 70, 80]
print(lst[:]) # [10, 20, 30, 40, 50, 60, 70, 80]
print(lst[-100:3]) # [10, 20, 30]
print(lst[4:100]) # [50, 60, 70, 80]
Lists and Functions
def sum(lst):
'''
Adds up the contents of a list of numericvalues
result = 0;
for item in lst:
result += item
return result

def clear(lst):
'''
Makes every element in list lst zero'''
for i in range(len(lst)):
lst[i] = 0

def random_list(n):
'''
Builds a list of n integers, where each integeris a
pseudorandom number in the range 0...99.
Returns the random list.'''
import randomresult=
[]
for i in range(n):
rand = random.randrange(100)
result += [rand]
return result

def main():
a = [2, 4, 6, 8]
# Print the contents of the list
print(a)
# Compute and display sum
print(sum(a))
# Zero out all the elements of list
clear(a)
# Reprint the contents of the list
print(a)

# Compute and display sum


print(sum(a))
# Test empty list
a = []
print(a)
print(sum(a))
# Test pseudorandom list with 10 elements
a = random_list(10)print(a)
print(sum(a))

main()

Sorting

Sorting—arranging the elements within a list into a particular order—is a


common activity. For example, a list of integers may be arranged in ascending order
(that is, from smallest to largest). A list of strings may be arranged in lexicographical
(commonly called alphabetical) order. Many sorting algorithms exist, and some perform
much better than others. We will consider one sorting algorithm that is relatively easy to
implement.
The selection sort algorithm is relatively easy to implement and easy to
understand how it works.
If A is a list, and i represents a list index, selection sort works as follows:

1. Set n = length of list A.


2. Set i = 0.
3. Examine all the elements A[ j], where i < j < n. (This
simply means to consider all the elements in the list from
index i to the end.) If any of these elements is less than
A[i], then exchange A[i] with the smallest of these
elements. (This ensures that all elements after position
i are greater than or equal to A[i].)
4. If i is less than n− 1, set i equal to i + 1 and go to Step 2.
5. Done; list A is sorted.

The command to “go to Step 2” in Step 4 represents a loop.


When the value of i in Step 3 equals n, the algorithm
terminates with a sorted list.
Example:
from random import randrange

def random_list():
'''
Produce a list of pseudorandom integers.
The list's length is chosen pseudorandomly in therange 3-
20.
The integers in the list range from -50 to 50.'''
result = []
count = randrange(3, 20)for i
in range(count):
result += [randrange(-50, 50)]
return result

def selection_sort(lst):
'''
Arranges the elements of list lst in ascending order.
The contents of lst are physically rearranged.
'''
n = len(lst)
for i in range(n - 1):
# Note: i, small, and j represent positions within lst
# lst[i], lst[small], and lst[j] represent the elements at
# those positions.
# small is the position of the smallest value we've seen
# so far; we use it to find the smallest value less
# than lst[i]
small = i
# See if a smaller value can be found later in the list
# Consider all the elements at position j, where i < j < n
for j in range(i + 1, n):
if lst[j] < lst[small]:
small = j # Found a smaller value
# Swap lst[i] and lst[small], if a smaller value was found
if i != small:
lst[i], lst[small] = lst[small], lst[i]
def main():
'''
Tests the selection_sort function
'''
for n in range(10):
col = random_list()
print(col)
selection_sort(col)
print(col)
print('==============================')
main()
Search:

Searching a list for a particular element is a common activity. We examine two basic
strategies: linear search and binary search.
Linear Search:

Linear search is a method of finding elements within a list. It is also called a sequential search. It
is the simplest searching algorithm because it searches the desired element in a sequential
manner.
Example:
1. def linear_Search(list1, n, key):
2.
3. # Searching list1 sequentially
4. for i in range(0, n):
5. if (list1[i] == key):
6. return i
7. return -1
8.
9.
10. list1 = [1 ,3, 5, 4, 7, 9]
11. key = 7
12.
13. n = len(list1)
14. res = linear_Search(list1, n, key)
15. if(res == -1):
16. print("Element not found")
17. else:
18. print("Element found at index: ", res)

Binary Search

Linear search is acceptable for relatively small lists, but the process of examining
each element in a large list is time consuming. An alternative to linear search is
binary search. In order to perform binary search, a list must be in sorted order. Binary
search exploits the sorted structure of the list using a clever but simple strategy that
quickly zeros in on the element to find:

1. If the list is empty, return None.


2. Check the element in the middle of the list. If that
element is what you are seeking, return its position. If
the middle element is larger than the element you are
seeking, perform a binary search on the first half of the
list. If the middle element is smaller than the element
you are seeking, perform a binary search on the
second half of the list.

This approach is analogous to looking for a telephone number in the phone book in
this manner:

1. Open the book at its center. If the name of the person


is on one of the two visible pages, look at the phone
number.
2. If not, and the person’s last name is alphabetically less
the names on the visible pages, apply the search to the
left half of the open book; otherwise, apply the search
to the right half of the open book.
3. Discontinue the search with failure if the person’s
name should be on one of the two visible pages but is
not present.
Example:
1. def binary_search(list1, n):
2. low = 0
3. high = len(list1) - 1
4. mid = 0
5.
6. while low <= high:
7. # for get integer result
8. mid = (high + low) // 2
9.
10. # Check if n is present at mid
11. if list1[mid] < n:
12. low = mid + 1
13.
14. # If n is greater, compare to the right of mid
15. elif list1[mid] > n:
16. high = mid - 1
17.
18. # If n is smaller, compared to the left of mid
19. else:
20. return mid
21.
22. # element was not present in the list, return -1
23. return -1
24.
25.
26. # Initial list1
27. list1 = [12, 24, 32, 39, 45, 50, 54]
28. n = 45
29.
30. # Function call
31. result = binary_search(list1, n)
32.
33. if result != -1:
34. print("Element is present at index", str(result))
35. else:
36. print("Element is not present in list1")

Reversing a List

It contains a recursive function named revthat accepts a list as a parameter and


returns a new list with all the elements of the original list in reverse order.

1def rev(lst):
2 return [] if len(lst) == 0 else rev(lst[1:]) + lst[0:1]

3print(rev([1, 2, 3, 4, 5, 6, 7]))

Python has a standard function, reversed, that accepts a list parameter. The reversed
function does not return a list but instead returns an iterable object that can be used like the
range function within a for loop .

1for item in reversed([1, 2, 3, 4, 5, 6, 7]):


print(item)
2
UNIT-V

Using Objects

• An object is an instance of a class.


• Integers, floating-point numbers, strings, lists, and functions are all objects in
Python. With the exception of function objects, we have treated these objects as
passive data. We can assign an integer and use its value.
• We can add two floating-point numbers and concatenate two strings with the +
operator. We can pass objects to functions and functions can return objects.
• Objects fuse data and functions together.
A typical object consists of two parts: data and methods. An object’s data is
sometimes called its attributes or fields. Methods are like functions, and they also are
known as operations. The data and methods of an object constitutes its members.
The assignment statement
x = 2

binds the variable x to an integer object with the value of 2. The name of the
class of x is int. To see some of the capabilities of intobjects, issue the command
dir(x)or dir(int)in the Python interpreter:

>>> dir(x)
[’ abs ’, ’ add ’, ’ and ’, ’ bool ’, ’ ceil ’,
’ class ’, ’ delattr ’, ’ divmod ’, ’ doc ’, ’ eq ’,
’ float ’, ’ floor ’, ’ floordiv ’, ’ format ’,
’ ge ’, ’ getattribute ’, ’ getnewargs ’, ’ gt ’,
’ hash ’, ’ index ’, ’ init ’, ’ int ’, ’ invert ’,
’ le ’, ’ lshift ’, ’ lt ’, ’ mod ’, ’ mul ’,
’ ne ’, ’ neg ’, ’ new ’, ’ or ’, ’ pos ’, ’ pow ’,
’ radd ’, ’ rand ’, ’ rdivmod ’, ’ reduce ’, ’ reduce_ex ’,
’ repr ’, ’ rfloordiv ’, ’ rlshift ’, ’ rmod ’, ’ rmul ’,
’ ror ’, ’ round ’, ’ rpow ’, ’ rrshift ’, ’ rshift ’,
’ rsub ’, ’ rtruediv ’, ’ rxor ’, ’ setattr ’, ’ sizeof ’,
’ str ’, ’ sub ’, ’ subclasshook ’, ’ truediv ’, ’ trunc ’,
’ xor ’, ’bit_length’, ’conjugate’, ’denominator’, ’from_bytes’,
’imag’, ’numerator’, ’real’, ’to_bytes’]
add is a method in the intclass, so it is available to all integer objects. The expression x.
add (3)is an example of a method invocation. A method invocation works like a
function invocation, except we must qualify the call with an object’s name (or
sometimes a class name). The expression begins with the ob- ject’s name, followed by a
dot (.), and then the method name with any necessary parameters. The following
interactive sequence shows how we can use the add method:

>>> x = 2
>>> x
2
>>> x + 3
5
>>> x. add (3)
5
>>> int. add (x, 3)
5

Compare the code fragment


s = "ABC"
print(s. add ("DEF"))
print(str. add (s, "DEF"))

The expressions s. add ("DEF")and str. add (s, "DEF")are equivalent to s +


"DEF", which we know is string concatenation. The interpreter translates the
symbol for integer addition or string con- catenation, +, into the appropriate
method call, in this case str. add .

String Objects

Strings are like lists is some ways because they contain an ordered sequence of
elements. Strings are distinguished from lists in three key ways:

• Strings must contain only characters, while lists may contain objects of any type.
• Strings are immutable. The contents of a string object may not be changed.
• If two strings are equal with == comparison, they automatically are aliases
(equal with the is opera- tor). This means two identical string literals that
appear in the Python source code refer to the same string object.
Example:

1 word1 = 'Wow'
word2 = 'Wow'
2 print('Equality:', word1 == word2, ' Alias:', word1 is word2)
3

Example 2:
1 name = input("Please enter your name: ")
2 print("Hello " + name.upper() + ", how are you?")

Please enter your name: Rick


Hello RICK, how are you?

The expression
name.upper()

within the printstatement represents a method call.


The general form of a method call is

object.methodname (parameterlist )
• object is an expression that represents object. nameis a reference to a string object.
• The period, pronounced dot, associates an object expression with the method to be
called.
• Method name is the name of the method to execute.
• The parameter list is comma-separated list of parameters to the
method. For some methods the parameter list may be empty, but the
parentheses always are required.
Example:3

1 word = "ABCD"
print(word.rjust(10, "*"))
2 print(word.rjust(3, "*"))
print(word.rjust(15, ">"))
3 print(word.rjust(10))
4
5The output:

******ABCD
ABCD
>>>>>>>>>>>ABCD
ABCD
strMethods
upper
Returns a copy of the original string with all the characters converted to
uppercase
lower
Returns a copy of the original string with all the characters converted to
lower case
rjust
Returns a string right justified within a field padded with a specified
character which de-
faults to a space
ljust
Returns a string left justified within a field padded with a specified character
which defaults
to a space
center
Returns a copy of the string centered within a string of a given width
and optional fill
characters; fill characters default to spaces
strip
Returns a copy of the given string with the leading and trailing whitespace
removed; if provided an optional string, the stripfunction strips leading and
trailing characters found in the parameter string
startswith
Determines if the string is a prefix of the string
endswith
Determines if the string is a suffix of the string
count
Determines the number times the string parameter is found as a substring;
the count in-
cludes only non-overlapping occurrences
find
Returns the lowest index where the string parameter is found as a substring;
returns −1 if
the parameter is not a substring
format
Embeds formatted values in a string using 1, 2, etc. position parameters (see
Listing 11.4 (stripandcount.py) for an example) parameter is found as a
substring; returns −1 if the parameter is not a substring

Table 11.1: A few of the methods available to strobjects


Example for string methods:

# Strip leading and trailing whitespace and count substrings


s = " ABCDEFGHBCDIJKLMNOPQRSBCDTUVWXYZ "
2 print("[", s, "]", sep="")
3 s = s.strip()
print("[", s, "]", sep="")
4
5 #print(s.count("BCD"))
Count occurrences of the substring "BCD"

6
Output:

3
8

s = "ABCDEFGHIJK"
print(s)
for i in range(len(s)):
print("[", s[i], "]", sep="", end="")
print() # Print newline

for ch in s:
print("<", ch, ">", sep="", end="")
print() # Print newline
List Objects

All Python lists are instances of the listclass. Table ?? lists some of the
methods available to listobjects.

listMethods
count
Returns the number of times a given element appears in the list.
Does not modify the list.
insert
Inserts a new element before the element at a given index.
Increases the length of the list
by one. Modifies the list.
append
Adds a new element to the end of the list. Modifies the list.
index
Returns the lowest index of a given element within the list.
Produces an error if the element
does not appear in the list. Does not modify the list.
remove
Removes the first occurrence (lowest index) of a given element
from the list. Produces an
error if the element is not found. Modifies the list if the item to
remove is in the list.
reverse
Physically reverses the elements in the list. The list is modified.
sort
Sorts the elements of the list in ascending order. The list is
modified.

Table- A few of the methods available to listobjects

Since lists are mutable data structures, the listclass has both getitem and
setitem meth- ods. The statement
x = lst[2]

behind the scenes becomes the method call


x = list. getitem (lst, 2)

and the statement


lst[2] = x
maps to
list. setitem (lst, 2, x)

The strclass does not have a setitem method, since strings are immutable.
The code
lst = ["one", "two", "three"]lst +=
["four"]

is equivalent to
lst = ["one", "two", "three"]
lst.append("four")

Geometric Points

Consider two-dimensional geometric points from mathematics. We consider a


single point object to consist of two real number coordinates: x and y. We ordinarily
represent a point by an ordered pair (x, y). In a program, we could model the point (2.5,
1) as a list:
point = [2.5, 6]
print("In", point, "the x coordinate is", point[0])

or as a tuple:
point = 2.5, 6
print("In", point, "the x coordinate is", point[0])
Python provides the classreserved word to allow the creation of new types
of objects. We can create a new type, Point, as follows:
class Point:
def init (self, x, y):
self.x = x
self.y = y

This code defines a new type. This Point class contains a single method named
init . This special method is known as a constructor, or initializer. The
constructor code executes when the client creates an object. The first
parameter of this constructor, named self, is a reference to the object being
created. The statement
self.x = x

within the constructor establishes a field named xin the newly created Point
object. The expression self.xrefers to the x field in the object, and the x variable
on the right side of the assignment operator refers to the parameter named x.
These two xnames represent different variables.
Once this new type has been defined in such a class definition, a client
may create and use variables of the type Point:
# Client code
pt = Point(2.5, 6) # Make a new Point object
print("(", pt.x, ",", pt.y, ")", sep="")

The expression Point(2.5, 6)creates a new Pointobject with an x coordinate of


2.5 and a y coordinate of 6. The expression pt.x refers to the x coordinate of the
Point object named pt. Unlike with a list or a tuple, you do not use a numeric
index to refer to a component of the object; instead you use the name of the
field (like xand y) to access a part of an object.
A definition of the form
class MyName:
# Block of method definitions

creates a programmer-defined type. Once the definition is available to the


interpreter, programmers can define and use variables of this custom type.

p1

x 2.5

y 1.0

Figure: A Point object


A component data element of an object is called a field. Our Point objects
have two fields, x and y. The terms instance variable or attribute sometimes
are used in place of field. As with methods, Python uses the dot (.) notation
to access a field of an object; thus,
pt.x = 0

assigns zero to the xfield of point pt.


Consider a simple employee record that consists of a name (string), an
identification number (integer) and a pay rate (floating-point number). Such
a record can be represented by the class
class EmployeeRecord:
def init (n, i, r):
name = n
id = i
pay_rate =
r

Such an object could be created and used as


rec = EmployeeRecord("Mary", 2148, 10.50)

Class Inheritance

We can base a new class on an existing class using a technique known as inheritance.
Our Stopwatch objects may be started and stopped as often as necessary without resetting the
time. Support we need a stopwatch object that records the number of times the watch is started
until it is reset. We can build our enhanced Stopwatch class from scratch, but it would more
efficient to base our new class on the existing Stopwatch class.defines our enhanced stopwatch
objects.
Example:
from stopwatch import Stopwatch

class CountingStopwatch (Stopwatch):def init (self):


# Allow superclass to do its initialization of the# inherited fields
super(CountingStopwatch, self). init ()
# Set number of starts to zero
self. count = 0

def start(self):
# Let superclass do its start code super(CountingStopwatch,
self).start()# Count this start message
self. count += 1

def reset(self):
# Let superclass reset the inherited fields
super(CountingStopwatch, self).reset()
# Reset new field
self. count = 0

def count(self):
return self. count
The line
from stopwatch import Stopwatch

indicates that the code in this module will somehow use the Stopwatchclass from Listing
(stopwatch.py).
The line
class CountingStopwatch (Stopwatch):

defines a new class named CountingStopwatch, but this new class is based on the existing
class Stopwatch. This single line means that the CountingStopwatch class inherits everything
from the Stopwatch class. CountingStopwatchobjects automatically will have start, stop, reset,
and elapsedmethods.
We say stopwatchis the superclass of CountingStopwatch. Another term for
superclass is base class. CountingStopwatchis the subclass of Stopwatch, or, said another way,
CountingStopwatchis a derived class of Stopwatch.
Even though a subclass inherits all the fields and methods of its
superclass, a subclass may add new fields and methods and provide new code for an
inherited method. The statement

super(CountingStopwatch, self). init ()

in the init method definition calls the constructor of the superclass. After executing the
superclass constructor code, the subclass constructor defines and initializes the new count
field. The start and resetmethods in CountingStopwatchsimilarly invoke the services of their
counterparts in the superclass. The countmethod is a brand new method not found in the
superclass.
Notice that the CountingStopwatch class has no apparent stop method. In fact,
it inherits the stopmethod as is from Stopwatch.

Example:
from countingstopwatch import CountingStopwatchfrom time import
sleep

timer = CountingStopwatch()timer.start()
sleep(10) # Pause program for 10 seconds
timer.stop()
print("Time:", timer.elapsed(), " Number:", timer.count())

timer.start()
sleep(5) # Pause program for 5 seconds
timer.stop()
print("Time:", timer.elapsed(), " Number:", timer.count())

timer.start()
sleep(20) # Pause program for 20 seconds
timer.stop()
print("Time:", timer.elapsed(), " Number:", timer.count())

You might also like