Cca62-Python Programming
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.
• 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.
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.
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.
PVM
m.py m.pyc
• 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 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:
• Strings can be output to screen using the print function. For example:
print("hello").
>>> print("ASMW
college")
ASMWcollege
<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.
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'>
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:
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 :
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>
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
➢ 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
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)
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))
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]
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])
fSet = frozenset(vowels)
print('The frozen set is:', fSet)
print('The empty frozen set is:', frozenset())
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 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.
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
where
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)
main()
Sorting
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:
This approach is analogous to looking for a telephone number in the phone book in
this manner:
Reversing a List
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 .
Using Objects
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
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?")
The expression
name.upper()
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
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.
Since lists are mutable data structures, the listclass has both getitem and
setitem meth- ods. The statement
x = lst[2]
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
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="")
p1
x 2.5
y 1.0
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
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
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())