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

Python important question

Part B

Important Question

1.Compare break and Continue statement.

A: BREAK

 Break statements can alter the flow of a loop.

 It terminates the current loop and executes the remaining statement outside the

loop.

 If the loop has else statement, that will also gets terminated and come out of the

loop completely.

syntax:break

example

for i in “welcome”:

if(i=="c"):

break

print(i)

CONTINUE

It terminates the current iteration and transfer the control to the next iteration in th

loop.

Syntax:Continue

for i in "welcome":

if(i=="c"):

continue

print(i)

e
l

2. State the try--finally block with an example.

Using try....finally block:

 The close( ) method is not entirely safe. If an exception occurs when we are

performing some operation with the file, the code exits without closing

the file.

 The finally block is a place to put any code that must execute, whether

the try-block raised an exception or not.

Syntax:

try:

code that create exception

except:

exception handling statement

else:

statements

finally:

statements

Example: Output:

try:

age=int(input("enter your age:"))

except ValueError:

print("entered value is not a number")

else:

print("your age :”,age)

finally:
print("Thank you")

enter your age: six

entered value is not a number

Thank you

enter your age:5

your age is 5

Thank you

3. What do you mean by fruitful function?

A:The function that returns a value is called a fruitful function

Example:

#Example for fruitful function

def add(x,y):

sum=x+y

return sum

a=int(input("Enter a ="))

b=int(input("Enter b ="))

print("Addition of two numbers=",add(a,b))

Output:

Enter a=5

Enter b=5

Addition of two numbers= 10

4. Distinguish between Algorithm and Program.

Algorithm is defined as a sequence of instructions that

describe a method for solving a problem..in other words it is a step by step procedure for solving a
problem

A program is the actual implementation of an algorithm in a specific programming language, written to be


executed on a computer.

5. Write a Program to check whether the given String is palindrome or not.

A: a=input("enter a string:")

if a[::-1]==a:
print("the entered string is a palindrome")

else:

print("the entered string is not a palindrome")

output:

enter a string:racecar

the entered string is a palindrome

6. Write a Python program to change a given string to a new string where the first and last chars have
been exchanged.

A: l='throughout heaven and earth i alone am the honoured one'

l1=l[-1]+l[1:-1]+l[0]

print(l1)

output:

ehroughout heaven and earth i alone am the honoured ont

7.Write a program to reverse a string.

A: l='throughout heaven and earth i alone am the honoured one'

print(l[::-1])

output:

eno deruonoh eht ma enola i htrae dna nevaeh tuohguorht

8. Define a dictionary.

A: DICTIONARIES

A Dictionary is a collection of items are separated by commas, enclosed in curly braces {}. A dictionary

contains a collection of indices, which are called keys, and a collection of values. Each key is associated

with a single value. The association of a key and a value is called a key value pair or sometimes an item. A

dictionary represents a mapping from keys to values

9. sort the dictionary items in ascending order.

A: my_dict = {'banana': 3, 'apple': 1, 'orange': 2, 'grape': 4}

# Sort the dictionary items in ascending order based on values

sorted_dict = dict(sorted(my_dict.items(), key=lambda x: x[1]))


print(sorted_dict)

output:

{'apple': 1, 'orange': 2, 'banana': 3, 'grape': 4}

10. Explain with an example to copy the contents of one file to another.

A: f=open('out.txt','r')

a=f.read()

f1=open('out2.txt','w+')

f1.write(a)

f1.seek(0)

a1=f1.read()

print(a1)

f.close()

f1.close()

file ‘f’contains:

throughout heaven and earth I alone am the honoured one

output:

‘throughout heaven and earth I alone am the honoured one’

11. Write the algorithm to print the first n natural numbers.

A:

Step 1: Start

Step 2: get n value.

Step 3: initialize i=1

Step 4: if (i<=n) go to step 5 else go to step 8

Step 5: Print i value

step 6 : increment i value by 1

Step 7: go to step 4

Step 8: Stop

12. define algorithm and list its building blocks.

A: Algorithm is defined as a sequence of instructions that


describe a method for solving a problem.in other words it is the step by step procedure of solving a
problem

 BUILDING BLOCKS OF ALGORITHMS (statements, state, control flow, functions)

The building blocks of algorithm refer to the blocks such as statements, state, control flow

structures, functions, etc that are used to develop algorithms

Building blocks of algorithms:

The following are the various building blocks of algorithms:

 Statements

 State

 Control flow

 Functions

13. Differentiate compiler and interpreter

A:

S.no Compiler Interpreter

1 Translates High level language into Translates each instruction one by one from HLL
target language in binary form into low level machine language

2 Reads the whole program Reads each instruction one by one and first and then
translates it translate each instruction immediately into the machine language
one by one

16
3 It is a faster It is a slow process because the interpreter has to wait while each
process instruction is being translated

4 Examples: C,C++ Examples :Python

14.Find out the output of the program:

for i in “programming”:

if(i==”a”):

continue
print(i)

A:p

15.What will be the output for the following code:

a=”Python Programming”

print(a[2:8])

print(a[-3:])

A: thon P

ing

16. Differentiate Iteration and Recursion with examples.

A: In some programs, certain set of statements are executed again

and again based upon conditional test. i.e. executed more than

one time. This type of execution is called looping or iteration.

for i in range(1,6):

print(i)

else:

print("the number greater than 6")

output:

4
5

the number greater than 6

Recursions:

 A function that calls itself is known as recursion.

 Recursion is a process by which a function calls itself repeatedly until some

specified condition has been satisfied.

def factorial(n):

# Base case: factorial of 0 is 1

if n == 0:

return 1

# Recursive case: n! = n * (n-1)!

else:

return n * factorial(n - 1)

# Example usage:

number = 5

result = factorial(number)

print(f"The factorial of {number} is {result}")

output:

The factorial of 5 is 120

17. Define Membership operation in List with example.

A: 3. MEMBERSHIPOPERATION:

The operators in and not in operators are the membership operators in python. The in operator

is used to test whether a element is present in a list. It returns True if the element is present in the

list otherwise False. The not in operator is used to test if the element is not present in the list. It

returns True if the element is not present in the list, False otherwise

>>> list1=[1,2,3,"hello"]

>>> 1 in list1

True
>>> "Hello" in list1

False

18.Define key-value pairs.

A: DICTIONARIES

A Dictionary is a collection of items are separated by commas, enclosed in curly braces {}. A dictionary

contains a collection of indices, which are called keys, and a collection of values. Each key is associated

with a single value. The association of a key and a value is called a key value pair or sometimes an item. A

dictionary represents a mapping from keys to values

19.Define various access modes in file operations.

A: in oreder to access the file, first the file need to be opened

which can be done in two ways:

using open()-requires closing the file

using with open()-doesn’t require closing the file

then the file can be accessed in three different mdes:

r-read only mode

w-write only mode

a-append mode

20.Differentiate syntax errors from exceptions.

 Syntax errors are related to the structure of your code and occur during the parsing phase before the
program starts executing. They prevent the program from running.
 Exceptions are errors that occur during the execution of a program and can be caused by various
runtime issues. Exception handling mechanisms, such as try, except, and finally blocks, can be used to
handle and recover from these errors during runtime
In practice, when you encounter a syntax error, you need to fix the code structure before the program can
run. On the other hand, when an exception occurs, you can use exception handling to gracefully handle
the error and prevent the program from crashing.

21. Describe repetition operation in String with example

A: Repetitions:

a= “gojo ”

>>>print(3*a)

gojogojogojo

The * operator repeats the string on the left


hand side times the value on right hand side.

22. Differentiate List aliasing and List Cloning.

A: LIST ALIASING:

When two variables refer to the same object or list ,it is known as aliasing. When two variables

refer to the same list, changes made in one variable are reflected in the list

If the aliased object is mutable, changes made with one alias affect the other

Example:

#List Aliasing

list1=[1,2,3,4,5]

list2=list1

print(list1)

print("Aliased list",list2)

10

list1[0]=10 #changes in list1

print(list1)

print(list2) #changes affected the alias object

Output:

[1, 2, 3, 4, 5]

Aliased list [1, 2, 3, 4, 5]

[10, 2, 3, 4,5]

[10, 2, 3, 4,5]

LIST CLONING:

Cloning creates a new list with same values under another name. Cloning is the process of

making a copy of the list without modifying the original list. The changes will not affect the

original copy but reflected only in the duplicate copy

Various methods of cloning:

1. Cloning by Copy():
This is done by using the copy(). This creates a new reference from the original list

#Cloning by copy()

a=[1,2,3]

b=copy(a)

b[1]=12

print(a)

print(b)

Output:

[1, 2, 3]

[1,12,3]

2. Cloning by slicing

A clone of the list is created by slicing using [:]

#Cloning by Slicing

a=[1,2,3]

b=a[:]

print(a)

b[0]=10

print(b)

print(a)

Output:

[1, 2, 3]

[10, 2, 3]

[1, 2, 3]

3. Clone bylist()

A clone of the list is created by using the list() constructor.

a=[1,2,3]

b=list(a)

print(a)

print(b)

b[0]=10
print(a)

print(b)

Output:

[1, 2,3]

[1, 2,3]

[10, 2, 3]

23. Describe Nested List with example

A:a list which is enclosed within another list is called a nested list in other words a nested list is a list
which contains several other lists as its elements.eg:[[1,2,3],[4,5,6]]

24. What are the operations on String?

A: Operations onstring:

1. Indexing

2. Slicing

3. Concatenation

4. Repetitions

5. Membership

25. Describe Key pair value with example.

A: Each key is associated

with a single value. The association of a key and a value is called a key value pair or sometimes an item.

d={‘a’:1,’b’:2,’c’:3}

here a,b,c are keys and 1,2,3 are values a:1 is called a key value pair or item

26. Difference between pop( ) and remove( ) methods in List with example.

A:pop():

pop() function is used to remove the element from a list and return it it takes a paramenter where the
user have to give an index of the element to be removed.if it is not specified it removes and returns the
last element of the list.

l=[1,2,3,4,5,6,7,8]

l.pop(1)

l.pop()

output:

8
remove():

the remove function is used to remove a particular element from thelist.it takes a parameter whrer the
user have to enter the element to be removed.if there are two or more of the elements present then it only
removes the element that is occurring first.

eg:

l=[1,2,8,4,5,6,7,8]

l.remove(8)

output:

[1,2,4,5,6,7,8]

Part C

1. List, Tuple, Dictionary – operations and methods


A: LIST OPERATIONS:

The following are the operations that can be performed on the lists:

1. CONCATENATION:

The concatenation operator(+) is used to concatenate two lists.

Example:

>>> list1=[10,20,30,40]

>>> list2=['python','program']

>>> list3=list1+list2

>>> list3

[10, 20, 30, 40, 'python', 'program']

2. REPETITION:

The repetition operator(*) is used to repeat the list for a given


number of times. Example:

>>> list4=[1,2,3,'python']

>>> list4*3

[1, 2, 3, 'python', 1, 2, 3, 'python', 1, 2, 3, 'python']

3. MEMBERSHIPOPERATION:

The operators in and not in operators are the membership operators in python. The in
operator is used to test whether a element is present in a list. It returns True if the
element is present in the list otherwise False. The not in operator is used to test if the
element is not present in the list. It returns True if the element is not present in the list,
False otherwise

>>> list1=[1,2,3,"hello"]

>>> 1 in list1
True

>>> "Hello" in list1

False

LIST SLICES:

Slicing refers to extracting a subset of list. The operator [:] is used to perform the slice
operation. Syntax:

Listname[start:stop:step]

where start is the starting index for the slice which is included in the slice
operation stop is the stopping index for the slice which is excluded
in the slice operation step is the next index for slice which is
optional

Example:

#Example for slicing lists

a=[1,2,3,4,5,6]

print(a)

print(a[0])

print(a[0:])

print(a[1:4])

print(a[1:4:2])

print(a[-1:])

print(a[-4:-1])

print(a[-1:-4])

Output:

[1, 2, 3, 4, 5,6]

[1, 2, 3, 4, 5,6]

[2, 3, 4]

[2, 4]

[6]

[3, 4,

5] []
5

LIST INBUILT METHODS:


6

clear() - Removes all items from the list

Syntax:

Listname.clear()

copy() - Returns a shallow copy of the list


Syntax:

Listname.copy()

#Example for List Methods #Append()

list1=[1,2,3,5]

print("List before appending",list1)

list1.append(10)

print("List after appending",list1)

Output:

List before appending [1, 2, 3, 5]

List after appending [1, 2, 3, 5, 10]

Basic Tuples Operations

methods example description

a.index(tuple) >>> a=(1,2,3,4,5) Returns the index of the first


matched item.
>>> a.index(5) 4

15
a.count(tuple) >>>a=(1,2,3,4,5) Returns the count of the given
element.
>>> a.count(3) 1

len(tuple) >>> len(a) 5 return the length of the

tuple

min(tuple) >>> min(a) 1 return the minimum

element in a tuple

max(tuple) >>> max(a) 5 return the maximum

element in a tuple

del(tuple) >>> del(a) Delete the entire tuple.

DICTIONARY OPERATIONS

Dictionaries are mutable datatypes in python. The following operations are possible on
dictionaries:

1. Updating a dictionary

The values in a dictionary can be changed ,added or deleted. If the key is present in
the dictionary, then the associated value with key is updated or changed ,otherwise a
new key:value pair is added

Example:

#Dictionary updation

d={'name':'John','age':27}

print(d)

d['age']=30

print(d)

d['address']='brazil'

print(d)

19

Output:

{'name': 'John', 'age':27}


{'name': 'John', 'age':30}

{'name': 'John', 'age': 30, 'address': 'brazil'}

When the value of age is changed, the interpreter searches for key “age” in the
dictionary and changes its value.

When d[“address”] is executed, the interpreter does not find the key “address” in the
dictionary, hence a new key:value pair is added

2. Deleting elements from dictionary

The elements can be removed or deleted from a dictionary by using


pop(),popitem(),clear(),del keyword

pop(): Removes an element from the dictionary for which the key is provided

popitem(): Removes or deletes and returns an arbitary element from


the dictionary. clear(): Removes all the elements from the dictionary at
once.

del: Deletes the entire dictionary

Example:

#Dictionary Deletion

cubes={1:1,2:8,3:27,4:64,5:125,6:216}

print(cubes)

print("deletion using pop()",cubes.pop(6))

print("deletion using popitem()",cubes.popitem())

print("deletion using clear()",cubes.clear())

del cubes

print(cubes)

Output:

{1: 1, 2: 8, 3: 27, 4: 64, 5: 125, 6: 216}

deletion using pop() 216

deletion using popitem() (5, 125)

deletion using clear()None

NameError: name 'cubes' is not defined

3.Traversal:

Traversal in dictionary is done on the basis of keys. For traversal, for loop is used which
iterates over the keys in the dictionary and prints the corresponding values using keys

#Dictionary traversal

cubes={1:1,2:8,3:27,4:64,5:125}
for i in cubes:

print(i,cubes[i])

Output:

11

28

3 27

4 64

5 125

20

4. Membership

Using the membership operators in and not in, whether a key is present in the
dictionary or not can be tested. If the key is present in the dictionary the in operator
returns True other False. The not operator returns True if the key is not present in the
dictionary, False otherwise

Example:

#Dictionary membership

cubes={1:1,2:8,3:27,4:64,5:125}

print(1 in cubes)

print(27 in cubes)

print(27 not in cubes)

Output:

True

False

True

DICTIONARY METHODS:

S.no Method Description

1. dict.clear() Removes all elements of dictionary at once

2. dict.copy() Returns a copy of dictionary dict

3. dict.fromkeys() It Create a new dictionary with keys from sequence and


values set to value.
4. dict.get(key, For the key passed as parameter, returns value or
default if key not in dictionary
default=None)

5. dict.items() Returns a list of (key, value) pairs of the dictionary

6. dict.keys() Returns list of all keys in the dictionary

7. dict.setdefault(ke Similar to get(), but will set dict[key]=default if key is not


y , default=None) already in dict

8. dict.update(dict2) It addsthe items from dict2 to dict

9. dict.values() It returns all the values in the dictionary

dict.clear():

This method is used to remove all the items from the dictionary. This method does
not return any value

Syntax:

dictname.clear()

Example:

#Dictionary method clear()

d={1:1,2:8,3:27,4:64,5:125}

22

print(d)

d.clear()

print(d)

Output:

{1: 1, 2: 8, 3: 27, 4: 64, 5: 125}

{}

dict.copy():
This method returns a copy of the dictionary.

Syntax:

dictname.copy()

Example:

#Dictionary method copy()

d={1:1,2:8,3:27,4:64,5:125}

print(d)

c=d.cop

y()

print(c)

Output:

{1: 1, 2: 8, 3: 27, 4: 64, 5:125}

{1: 1, 2: 8, 3: 27, 4: 64, 5:125}

dict.fromkeys():

This method creates a new dictionary with keys from seq and values set to
value. This method returns the list.

Syntax:

dictname.fromkeys(seq[, value]))

Parameters

seq - This is the list of values which would be used for dictionary keys

value - This is optional, if provided then value would be set to thisvalue

Example:

#Dictionary method fromkeys()

d={1:1,2:8,3:27,4:64,5:125}

print(d)

c=d.fromkeys([1,2,3],"python")

print(c)

Output:

{1: 1, 2: 8, 3: 27, 4: 64, 5: 125}

{1: 'python', 2: 'python', 3: 'python'}

dict.get(key, default=None)

The method get() returns a value for the given key. If the key is not available then returns
default value None. This method returns a value for the given key. If the key is not
available, then returns default value as None.

Syntax:

dict.get(key, default=None)

23

Parameters

key - This is the Key to be searched in the dictionary.

default - This is the Value to be returned in case key does not exist.

Example:

#Dictionary method get()

d={1:1,2:8,3:27,4:64,5:125}

print(d)

print("The value at key 2 is",d.get(2))

print("The value at key 6 is",d.get(6))

print("The value at key 6 is",d.get(6,216))

Output:

{1: 1, 2: 8, 3: 27, 4: 64, 5: 125}

The value at key 2 is 8

The value at key 6 is None

The value at key 6 is 216

dict.items():

This method items() returns a list of dict's (key, value) tuple pairs.

dict.items()

Example:

#Dictionary method items()

d={1:1,2:8,3:27,4:64,5:125}

print(d)

print("The items in the dictionary is",d.items())

Output:

{1: 1, 2: 8, 3: 27, 4: 64, 5: 125}

The items in the dictionary is dict_items([(1, 1), (2, 8), (3, 27), (4, 64),
(5, 125)]) dict.keys():

This method returns a list of all the available keys in the dictionary
Syntax:

dict.keys()

Example:

#Dictionary method keys()

d={1:1,2:8,3:27,4:64,5:125}

print(d)

print("The items in the dictionary is",d.keys())

Output:

{1: 1, 2: 8, 3: 27, 4: 64, 5: 125}

The items in the dictionary is dict_keys([1, 2, 3, 4, 5])

dict.setdefault():

This method is similar to get(), but will set dict[key]=default if the key is not already
in dict. This method returns the key value available in the dictionary and if given key is
not available then it will return provided default value.

Syntax:

dict.setdefault(key, default=None)

Example:

24

#Dictionary method setdefault()

d={1:1,2:8,3:27,4:64,5:125}

print(d)

print("The value at keyis",d.setdefault(6))

print(d)

Output:

{1: 1, 2: 8, 3: 27, 4: 64, 5: 125}

The value at key is None

{1: 1, 2: 8, 3: 27, 4: 64, 5: 125, 6: None}

dict.update(dict2)

The method adds dictionary dict2's key-values pairs in to dict. This function does
not return anything. This method does not return any value.

Syntax:

dict.update(dict2)

Example:
#Dictionary method update()

d1={1:1,2:8,3:27,4:64,5:125}

print(d1)
d2={"one":"python","two":"python","three":"python"}
print(d2) d2.update(d1)

print(d2) Output:

{1: 1, 2: 8, 3: 27, 4: 64, 5: 125}

{'one': 'python', 'two': 'python', 'three': 'python'}

{'one': 'python', 'two': 'python', 'three': 'python', 1: 1, 2: 8, 3: 27, 4: 64, 5: 125}

dict.values()

The method values() returns a list of all the values available in a given
dictionary. Syntax:

dict.values()

Example:

#Dictionary method values()

d={1:1,2:8,3:27,4:64,5:125}

print(d)

print("The value at key is",d.values())

Output:

{1: 1, 2: 8, 3: 27, 4: 64, 5: 125}

The value at key is dict_values([1, 8, 27, 64, 125])

2. Write a python program to store n numbers in a list and sort the list in Ascending order.
A: n=int(input("how many numbers you want in the list?"))

l=[]

for i in range(n):

a=int(input("enter the numbers"))

l.append(a)

print("the entered list",l)

print("the list after ascending order sorting",sorted(l))

output:

how many numbers you want in the list?8

enter the numbers8

enter the numbers7


enter the numbers6

enter the numbers5

enter the numbers4

enter the numbers3

enter the numbers2

enter the numbers1

the entered list [8, 7, 6, 5, 4, 3, 2, 1]

the list after ascending order sorting [1, 2, 3, 4, 5, 6, 7, 8]

3.Get positive numbers and negative numbers from user. Find the mean for positive numbers and
negative numbers and also find the average for positive and negative numbers.
A: l=[]

a=int(input("enter how many positive numbers you want"))

for i in range(a):

a1=int(input("enter posititve numbers"))

if a1>0:

l.append(a1)

elif a1<0:

print("enter positive numbers only")

b=int(input("enter how many negative numbers you want"))

for j in range(b):

b1=int(input("enter negative numbers"))

if b1<0:

l.append(b1)

elif b1>0:

print("enter negative numbers only")

print("the list created",l)

print("the mean of the numbers entered:",sum(l)/len(l))

print("the average of the numbers entered:",sum(l)/len(l))

output:

enter how many positive numbers you want3

enter posititve numbers55

enter posititve numbers88

enter posititve numbers77


enter how many negative numbers you want2

enter negative numbers-43

enter negative numbers-3

the list created [55, 88, 77, -43, -3]

the mean of the numbers entered: 34.8

the average of the numbers entered: 34.8

4.Write an algorithm, pseudo code and draw the flowchart to solve the quadratic equation.
A:quadratic equation=-b+or-(b**2-4ac)**1/2/2a discriminant is d=b**2-4ac
if d<0(negative)-no real roots
d=0 one solution exists x=-b/2a
if d>0 then find the solutions by the formula
5.explain the Building blocks of Algorithm

A: BUILDING BLOCKS OF ALGORITHMS (statements, state, control flow, functions) The building
blocks of algorithm refer to the blocks such as statements, state, control flow structures, functions, etc
that are used to develop algorithms

Building blocks of algorithms:

The following are the various building blocks of algorithms:

∙ Statements
∙ State
∙ Control flow
∙ Functions
Statements:
1.

A statement is a command given to the computer that instructs the computer to take a
specific action, such as display to the screen, or collect input. A computer program is
made up of a series of statements.

Example: Statements in Python are made up of:

Reserved words - words that have pre-defined meanings in the Java language Identifiers - words
that are created by programmers for names of variables, functions, classes, etc.
Literals - literal values written in code, like strings or numbers
Operators - special symbols that perform certain actions on their operands Calls
to functions

2. State:

Transition from one process to another process under specified condition with in a
time is called state.

3
State is the information that the program manipulates to accomplish some task. It is data
or information that gets changed or manipulated throughout the runtime of a program. The state
of an algorithm is defined as its condition regarding stored data. Example: state refers to the set of
variables and the values to which they refer.

3. Control flow:

The process of executing the individual statements in a given order is called


control flow.

Control flow is the order that instructions are executed in a program .A control statement is
a statement that determines the control flow of a set of instructions The control can be
executed in three ways
1. sequence
2. selection
3. Iteration
Sequence:
All the instructions are executed one after another is called sequence execution.
Pseudocode Flowchart

BEGIN
statement
Statement Action1
END
Action2

Example:
Add two
numbers
Selection:
It is provided by a control statement that selectively executes instructions.

4
The selection structure allows the programs to make a choice between two alternate
paths, whether it is true or false. These statements are known as conditional or
decision making or selection statements or branching statements
Example
Write an algorithm to check whether he is eligible to
vote?
Step 1: Start
Step 2: Get age
Step 3: if age >= 18 print “Eligible to Vote”
Step 4: else print “Not eligible tovote”
Step 6: Stop
Algorithm to find biggest among 2 nos
Step1: Start
Step 2: Get two numbers as input and store it in to a and b
Step 3: If a is greater than b then
Step 4: Print a is big
Step 5: else
Step 6: Print b is big
Step 7:Stop
5
Iteration:
In some programs, certain set of statements are executed again and again based upon
conditional test. i.e. executed more than one time. This type of execution is called
looping or iteration.

Example
Algorithm to print first 10 natural numbers
Step1: Start
Step 2: Initailize a=0
Step 3: Repeat Step 3 until a<=10
Step 3.1: a=a+1,
Step 3.2: Print the value of a
step 4:Stop
4. Functions:
Function is a sub program which consists of block of code(set of instructions) that
performs a particular task.

❖ For complex problems, the problem is been divided into smaller and simpler tasks
during algorithm design.

6
Benefits of Using Functions
❖ Reduction in line of code
❖ code reuse
❖ Better readability
❖ Information hiding
❖ Easy to debug and test
❖ Improved maintainability

Example:
∙ Function: piece of prewritten code that performs an operation ∙ print
function: displays output on the screen
∙ Argument: data given to a function
Example: data that is printed to screen
Types of functions/categories of functions:
Pre-defined functions-built in functions provided by programming languages
Example: print() in python
User-defined functions-created by user.
Example fact()
Pseudocode:
BEGIN BEGINPROCEDURE
CALLPROCEDURE statement1
END statement2
END PROCEDURE
Example:
Algorithm for addition of two numbers using function
Main function()
Step 1: Start
Step 2: Call the function add()
Step 3: Stop

sub function add()


Step 1: Function start
Step 2: Get a, b Values
Step 3: add c=a+b
Step 4: Print c
Step 5: Return
6.Explain operators with an example

A: OPERATORS:
❖ Operators are the constructs which can manipulate the value of operands. ❖
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is
called operator.
❖ Types of Operators:
-Python language supports the following types of operators
∙ Arithmetic Operators
∙ Comparison (Relational)Operators
∙ Assignment Operators
∙ Logical Operators
∙ Bitwise Operators
∙ Membership Operators
∙ Identity Operators
Arithmetic operators:
Arithmetic operators are used to perform mathematical operations
like addition, subtraction, multiplication etc.
Arithmetic operators in Python

Operator Meaning Example

+ Add two operands or unary plus x+y

- Subtract right operand from the left or unary minus x-y

* Multiply two operands x*y

/ Divide left operand by the right one (always results into float) x/y

% Modulus - remainder of the division of left operand by the right x%y


(remainder of
x/y)

// Floor division - division that results into whole number adjusted to x // y


the left in the number line

** Exponent - left operand raised to the power of right x**y


(x to the power
y)
Example 1: Arithmetic operators in Python
#To demonstrate the arithmetic operators
x=10
y=8
a=x+y
print("The addition is:",a)
b=x-y
print("The subtraction is:",b)
c=x*y

23
print("The multiplication is:",c)
d=x/y
print("The division is:",d)
e=x%y
print("The modulo division is:",e)
f=x//y
print("The floor division is:",f)
g=x**y
print("The exponentiation is:",g)

OUTPUT:

When you run the program, the output


will be:
The addition is: 18
The subtraction is: 2
The multiplication is: 80
The division is: 1.25
The modulo division is: 2
The floor division is: 1
The exponentiation is: 100000000

Comparison (Relational)Operators:
∙ Comparison operators are used to compare values.
∙ It either returns True or False according to the condition. Assume, a=10 and b=5
Operator Description Example

== If the values of two operands are equal, then the condition (a == b) is


becomes true. not true.

!= If values of two operands are not equal, then condition (a!=b) istrue
becomes true.

> If the value of left operand is greater than the value of right (a > b) is
operand, then condition becomes true. not true.
< If the value of left operand is less than the value of right (a < b) is
operand, then condition becomes true. true.

>= If the value of left operand is greater than or equal to the value (a >= b) is
of right operand, then condition becomes true. not true.

24

<=

Example
If the value of left operand is less than or equal to the value of right operand, (a <= b) is
then condition becomes true. true.

a=10 Output:
b=5 a>b=> True
print("a>b=>",a>b) a>b=> False
print("a>b=>",a<b) a==b=> False
print("a==b=>",a==b) a!=b=> True
print("a!=b=>",a!=b) a>=b=> False
print("a>=b=>",a<=b) a>=b=> True
print("a>=b=>",a>=b)

Assignment Operators:
-Assignment operators are used in Python to assign values to variables.
Operator Description Example

= Assigns values from right side operands to left side c=a+b


operand assigns
value of a + b
into c

+= Add It adds right operand to the left operand and assign the c += a is
AND result to left operand equivalent
to c = c +a
-= It subtracts right operand from the left operand and assign c -= a is
Subtract the result to left operand equivalent
AND to c = c -a

*= It multiplies right operand with the left operand and assign c *= a is


Multiply the result to left operand equivalent
AND to c = c *a

/= It divides left operand with the right operand and c /= a is


Divide assign the result to left operand equivalent
AND to c = c /a

%= It takes modulus using two operands and assign the result c %= a is


Modulu to left operand equivalent
s AND to c = c % a

25

**= Exponent AND

//= Floor Division

Example:
Performs exponential(power) calculation on operators and assign value to the leftoperand

It performs floor division on operators and assign value to the left operand
c **= a is equivalent to c = c ** a

c //= a is equivalent to c = c // a

#To demonstrate assignment operators


x=10
y=12
print(y)
y+=x
print(y)
y-=x
print(y)
y*=x
print(y)
y/=x
print(y)
y%=x
print(y)
y**=x
print(y)
y//=x
print(y)

OUTPUT
12
22
12
120
12.0
2.0
1024.0
102.0
Logical Operators:
-Logical operators are the and, or, not operators.

26

Example
a = True
b = False
print('a and b is',a and b) print('a or b is',a or b) print('not a is',not a)
Output
x and y is False x or y is True not x is False
27

Truth tables for And ,or ,not


Truth table for and

A B A and B

True True True

True False False

False True False

False False False

Bitwise Operators:
Truth table for or

A B A or B

True True True

True False True

False True True

False False False

Truth table for


not

A not A

True False

∙ A bitwise operation operates on one or more-bit patterns at the level of


individual bits
Example: Let x = 10 (0000 1010 in binary) and
y = 4 (0000 0100 in binary)
Example:
#To demonstrate bitwise operators
x=10
y=12
print("The bitwise and is:",x&y)
print("The bitwise or is:",x|y)
print("The bitwise xor is:",x^y)
print("The bitwise not is:",~x)
print("The bitwise left shift by 2 positions is:",x<<2)
print("The bitwise right shift by 2 positions is:", x>>2)
OUTPUT:
The bitwise and is: 8
The bitwise or is: 14
The bitwise xor is: 6
The bitwise not is: -11
The bitwise left shift by 2 positions is: 40
The bitwise right shift by 2 positions is: 2
Membership Operators:

❖ Evaluates to find a value or a variable is in the specified sequence of string, list, tuple,
dictionary or not.
❖ Let, x=[5,3,6,4,1]. To check particular item in list or not, in and not in
operators are used.
28
Example:
x=[5,3,6,4,1]
>>>5 in x
True
>>>5 not in x
False

Identity Operators:
❖ They are used to check if two values (or variables) are located on the same part
of the memory.

Example
x1 =5 Output
y1 =5 False
x2 = 'Hello' True
y2 = 'Hello'
print(x1 is not y1)
print(x2 is y2)
7.Analyze the different types of iterative structures allowed in Python with example programs.
A: ITERATION:
The process of repeated execution of a set of statements is called iteration or looping
.Python has two statements for iteration.
• while
• for

❖ state
❖ while
❖ for
State:
Transition from one process to another process under specified condition with in a
time is called state.
Whileloop:
∙ While loop statement in Python is used to repeatedly executes set of statement as long
as a given condition istrue.
∙ In while loop, test expression is checked first. The body of the loop is entered only if
the test expression is True. After one iteration, the test expression is checked
again. This process continues until the test expression evaluates toFalse.
∙ In Python, the body of the while loop is determined throughindentation. ∙ The
statements inside the while start with indentation and the first unindented line
marks the end.

Syntax:
Flowchart:
else in while loop:
❖ If else statement is used within while loop , the else part will be executed when the
condition become false.

37
❖ The statements inside for loop and statements inside else will also execute.
Program output

i=1
while(i<=5):
print(i)
i=i+1
else:
print("the number greater than 5") Nested while:
1
2
3
4
5
the number greater than 5

∙ While inside another while is called nested while


∙ The syntax for a nested while loop statement in Python programming language is as
follows

∙ Syntax

While condition1:
while
condition2:
statement2(
s) statement1(s)
Nested While( to multiply numbers):
i=1 4
while 5
i<4: 8
j=4 10
while j<6: 12
print(i*j) 15
j=j+
i=i+1
Examples:
1. program to find sum of n numbers:
2. program to find factorial of a number
3. program to find sum of digits of a number:
4. Program to Reverse the given number:
5. Program to find number is Armstrong number or not
6. Program to check the number is palindrome or not
Sum of n numbers: output

n=int(input("enter n")) i=1


sum=0
while(i<=n):
sum=sum+i
i=i+1
print(sum)
enter n 10
55

38

Factorial of a numbers:
n=int(input("enter n"))
i=1
fact=1
while(i<=n):
fact=fact*i
i=i+1
print(fact)
Sum of digits of a number: n=int(input("enter the number")) sum1=0
while n>0:
d=n%10
sum1=sum1+
d n=n//10
print(sum1)
Reverse the given number: n=int(input("enter the number")) rev=0
while n>0:
d=n%10
rev=(rev*10)+d
n=n//10
print(rev)
Armstrong number or not n=int(input("enter the number")) arm=0
temp=n
while temp>0:
d=temp%10
arm=arm+(d**3)
temp=temp//10
if n==arm:
print(n,"is a armstrong number") else:
print(n,"is not armstrong")
output
enter n
5
120
output
enter a
number 123
6

output
enter a number
123
321

output
enter a number153
The given number is Armstrong number

39

Palindrome or not
n=int(input("Enter a number:")) temp=n
reverse=0
while(n>0):
d=n%10
reverse=(reverse*10)+d
n=n//10
if(temp==reverse):
print("The number is palindrome") else:
print("The number is not palindrome")

For loop:
For in sequence
output
enter a number121
The given no is palindrome

❖ The for loop in Python is used to iterate over a sequence (list, tuple, string). Iterating over
a sequence is called traversal. Loop continues until we reach the last element in the
sequence.
❖ The body of for loop is separated from the rest of the code using indentation.

Sequence can be a list, strings or tuples

1. For loop in string for i in "python": print(i)

2. For loop in list for i in [2,3,5,6,9]: print(i)

3. For loop in tuple for i in (2,3,1): print(i)


y
t
h
o
n

2
3
5
6
92 3

40
❖ for in range:
- can generate a sequence of numbers using range() function.
range(10) will generate numbers from 0 to 9 (10 numbers).
❖ In range function have to define the start, stop and step size as
range(start,stop,step size). step size defaults to 1 if not provided. syntax

Flowchart:

else in for loop:


❖ If else statement is used in for loop, the else statement is executed when the loop has
reached the limit.
❖ The statements inside for loop and statements inside else will also execute.

Example
for i in range(1,6):
print(i)
else:
print("the number greater than 6")
Output
1
2
3
4
5
the number greater than 6

Nested for:
∙ for inside another for is called nested for
∙ The syntax for a nested for loop statement in Python programming language is as follows

∙ Syntax

for iterating_var in sequence:


for iterating_var in sequence:
statements(s)
statements(s)

41

example
for i in range(1,4):
for j in range(4,7):
print(i*j)
Examples:
1. print nos divisible by 5 not by10: 2. Program to print Fibonacci series.
output 4
5
6
8
10
12
12
15
18

3. Program to find factors of a given


number 4. check the given number is
perfect number or not 5. check the no is
prime or not
6. Print first n prime numbers
7. Program to print prime numbers in range

print nos divisible by 5 not by 10 output

n=int(input("enter a"))
for i in range(1,n,1):
if(i%5==0 and i%10!=0):
print(i)

Fibonacci series
a=0
b=1
n=int(input("Enter the number of terms: ")) print("Fibonacci Series: ")
print(a,b)
for i in range(1,n,1):
c=a+b
print(c)
a=b
b=c
enter a:30
5
15
25
output
Enter the number of terms: 6 Fibonacci Series:
01
1
2
3
5
8

42
find factors of a number Output

n=int(input("enter a number:"))
for i in range(1,n+1):
if(n%i==0):
print(i)

check the no is prime or not

n=int(input("enter a number"))
for i in range(2,n):
if(n%i==0):
print("The num is not a prime")
break
else:
print("The num is a prime number.") check a number is perfect number or not

n=int(input("enter a number:"))
sum1=0
for i in range(1,n,1):
if(n%i==0):
sum1=sum1+i
if(sum1==n):
print("the number is perfect number") else:
print("the number is not perfect number")

Program to print first n prime numbers

number=int(input("enter no of prime numbers to be displayed:"))


count=1
n=2
while(count<=number):
for i in range(2,n):
if(n%i==0):
break
else:
print(n)
count=count+1
n=n+1
-/+8
enter a number:10
1
2
5
10

output

enter a no:7
The num is a prime number.

Output

enter a number:6
the number is perfect number

Output

enter no of prime numbers to be displayed:5


2
3
5
7
11
43

Program to print prime numbers in range lower=int(input("enter a lower range"))


upper=int(input("enter a upper range")) for n in range(lower,upper + 1):
if n > 1:
for i in range(2,n):
if (n % i) == 0:
break
else:
print(n)

range() and xrange():


range():
output:

enter a lower
range5 enter a
upper range15 5
7
11
13

The range is a built-in function in Python that represents an immutable sequence of


numbers. Generally, Python range is used in the for loop to iterate a block of code for the
given number of times.
Syntax:
range([start],stop,[step])

where

∙ stop is the required parameter.


∙ The start specifies where to start the range. The default value
is0. ∙ The step specifies the step between each number. The
default is1. ∙ All parameters are integers
∙ All parameters can be positive or negative
xrange():
This function works similar to range().This function returns the generator object that
can be used to display numbers only by looping. Only particular range is displayed on
demand and hence called―lazy evaluation―.

Syntax:

xrange([start],stop,[step])

where
∙ stop is the required parameter.
∙ The start specifies where to start the range. The default value
is0. ∙ The step specifies the step between each number. The
default is1. ∙ All parameters are integers
∙ All parameters can be positive or negative

Difference between range() and xrange():


s.no range() xrange()

1 returns – the list as returns – xrange() object


return
type

44
2 consumes more consumes less memory
memory

3 As range() returns the list, all the operations that can be xrange() returns the
applied on the list can be used on it xrange object,
operations associated to
list cannot
be applied on them

4 Slower Faster

Example:
#Examples for range()
#range with one parameter(stop)
for i in range(5):
print(i)

OUTPUT:
0
1
2
3
4
#range with two parameters(start,stop)
for i in range(5,10):
print(i)
OUTPUT:
5
6
7
8
9
#range with three parameters(start,stop,step)
for i in range(5,10,2):
print(i)

OUTPUT:
5
7
9

8.What is a function? How to define a function in python? Explain the types of function arguments in
Python with example
A: A function is a group of related statements that performs a specific task.

⮚ Functions help break our program into smaller and modular chunks. As our program grows
larger and larger, functions make it more organized and manageable.

⮚ Furthermore, it avoids repetition and makes the code reusable.

⮚ Python enables its programmers to break up a program into segments commonly known as
functions, each of which can be written more or less independently of the others. Every
function in the program is supposed to perform a well-defined task.

Need for Functions

⮚ Understanding, coding and testing multiple separate functions is far easier. ⮚ Without the
use of any function, then there will be countless lines in the code and maintaining it will be a
big mess.

⮚ Programmers use functions without worrying about their code details. This speeds up
program development, by allowing the programmer to concentrate only on the code that he
has to write. ⮚ Different programmers working on that project can divide the workload by
writing different functions.

⮚ Like Python libraries, programmers can also make their functions and use them from
different point in the main program or any other program that needs its functionalities.

Function Declaration and Definition

⮚ A function f, that
uses another function g, is known as the calling function and g is known as
the called function.

⮚ The inputs that the function takes are known as arguments/parameters.

⮚ The calling function may or may not pass parameters to the called function. If the called
function accepts arguments, the calling function will pass parameters, else not.

⮚ Function declaration is a declaration statement that identifies a function with its name, a
list of arguments that it accepts and the type of data it returns.

⮚ Function definition consists of a function


header that identifies the function, followed by the
body of the function containing the executable code for that function.
Functions and its use:

Function is a group of related statements that perform a specific task.

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. ∙ User defined functions are the functions that
programmers

create for their requirement and use.

• These functions can then be combined to form module which


can be used in other programs by importing them.

Advantages of user defined functions:

• Programmers working on large project can divide the workload by

making different functions.

• If repeated code occurs in a program, function can be used to


include those codes and execute when needed by calling that
function.

Function definition: (Sub program)

• def keyword is used to define a function.

• Give the function name after def keyword followed by


parentheses in which arguments are given.

• End with colon (:)

• Inside the function add the program statements to be executed

• End with or without return statement

Parameters/Arguments:

A function in python

• Takes input data, called parameters or arguments

• Performs some computations

• Return the result

Syntax:

def function_name(param1,param2):

Statements return

result

Function call:

Once a function is defined, it must be called

Syntax:

result=function_name(param1,param2)

Parameters:
Parameter is the input data that is sent from one function to another. The parameters
are of two types:

Formal parameters:

This parameter defined as part of the function definition.

The actual parameter value is received by the formal parameter

Actual parameters:

This parameter defined in the function call

Example:

#Example for actual and formal parameters

def cube(x):

return x*x*x

a=int(input("Enter the number="))

b=cube(a)

print("Cube of the given number=",b)

Example:

Enter the number=5

Cube of the given number= 125

Actual arguments, or simply ―arguments, are the values passed to functions to be operated
on. Formal parameters, or simply ―parameters, are the placeholder names for the
arguments passed.

9.Briefly explain about the types of parameters in detail.


A: Types of parameters / arguments:

1. Required/Positional parameters

2. Keyword parameters

3. Default parameters

4. Variable length parameters

Required/ Positional Parameter:

The number of parameter in the function definition should match exactly with
number of arguments in the function call.

Example Output:
defstudent( name, roll ): George 98

print(name,roll)

student(“George”,98)

Keyword parameter:

Python interpreter is able to use the keywords provided to match the values
with parameters even though if they are arranged in out of order.

Example Output:

def student( name, age ): George 56

print( name)

print(age)

return

my_details(age=56,name="Geo

rge")

Default parameter:

Python allows function parameter to have default values; if the function is called without the
argument, the argument gets its default value in function definition.

Example Output:

def student( name, age=17): Kumar 17

print (name, age) Ajay 17


student( “kumar”):

student( “ajay”):

Variable length parameter

❖ Sometimes, we do not know in advance the number of arguments that will


be passed into a function.
❖ Python allows us to handle this kind ofsituation through function calls
with number of arguments.

❖ In the function definition we use an asterisk (*) before the parameter name
to denote this is variable length of parameter.

Example Output:

def student( name,*mark): bala ( 102 ,90)

print(name, mark)

student (“bala”,102,90)

10.Operations and methods in String.

A: Operations onstring:

1. Indexing

2. Slicing

3. Concatenation

4. Repetitions

5. Membership

indexing >>>a=”HELLO” ❖ Positive indexing helps in accessing the string


from the beginning
>>>print(a[0])
❖ Negative subscript helps in accessing the string
>>>H
from the end.
>>>print(a[-1])

>>>O
Slicing: Print[0:4] –HELL The Slice[start :stop] operator extracts sub string
from the strings.
Print[ :3] – HEL
A segment of a string is called a slice.
Print[0: ]-HELLO

Concatenation a= “save” The + operator joins the text on both sides of the
operator.
b=“earth”

>>>print(a+b)

saveearth

Repetitions: a= “Easwari ” The * operator repeats the string on the left hand side
times the value on right hand side.
>>>print(3*a)

Easwari Easwari

Easwari

Membership: >>> s="good morning" Using membership operators to check a particular


>>>"m" in s character is in string or not. Returns true if present

True

>>> "a" not in s

True

String slices:

❖ A part of a string is called string slices.

❖ The process of extracting a sub string from a string is called slicing.

String slices:

A segment of a string is called a slice. Selecting a slice is similar to selecting a character:


Subsets ofstrings 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 ofsteps.
Default value of start is 0,

- Stop is last index of list

- And for step default is 1

For example 1−

str = 'Hello World!'

print str # Prints complete string

print str[0] # Prints first character of the string

print str[2:5] # Prints characters starting from 3rd to 5th

print str[2:] # Prints string starting from 3rd character print

str * 2 # Prints string two times

print str + "TEST" # Prints concatenated string

Output:

Hello World!

llo

llo World!

Hello World!Hello World!

Hello World!TEST

Example 2:

>>> x='computer'

>>> x[1:4]

'omp'

>>> x[1:6:2]

'opt'

>>> x[3:]

'puter'

>>> x[:5]

'compu'

>>> x[-1]

'r'

>>> x[-3:]

'ter'
>>> x[:-2]

'comput'

>>> x[::-2]

'rtpo'

>>> x[::-1]

'retupmoc'

Slicing: Print[0:4] –HELL The Slice[n : m] operator extracts sub string from the
strings.
a=”HELLO” Print[ :3] – HEL
A segment of a string is called a slice.
Print[0: ]-HELLO

Immutability:

❖ Python strings are “immutable” as they cannot be changed after they are
created. ❖ Therefore [ ] operator cannot be used on the left side of an assignment.

For example:

>>> greeting= ‘Eswari college!'

>>> greeting[0]='n'

TypeError: 'str' object does not support item assignment

The reason for the error is that strings are immutable, which means we can’t change an
existing string. The best we can do is creating a new string that is a variation on the original:

>>> greeting = 'Hello, world!'

>>> new_greeting = 'J' + greeting[1:]

>>> new_greeting

'Jello, world!'

Note: The plus (+) sign is the string concatenation operator and the asterisk (*) is
the repetition operator

operations Example output

element assignment a="PYTHON" TypeError: 'str' object does not


support element assignment
a[0]='x'
element deletion a=”PYTHON” TypeError: 'str' object doesn't
support element deletion
del a[0]

delete a string a=”PYTHON” NameError: name 'my_string' is not


defined
del a

print(a)

string built in functions and methods:

A method is a function that “belongs to” an object.

Syntax to access the method

Stringname.method()

a=”happy birthday”

here, a is the string name.

syntax example description

1 a.capitalize() >>>a.capitalize() capitalize only the first letter in


a string
' Happybirthday‟

2 a.upper() >>> a.upper() change

'HAPPY BIRTHDAY‟ string to upper

case

3 a.lower() >>> a.lower() change

' happy birthday‟ string to lower

case

4 a.title() >>> a.title() change string to title case i.e.


first characters of all the
' Happy Birthday ' words are capitalized.

5 a.swapcase() >>> a.swapcase() change

'HAPPY BIRTHDAY' lowercase

characters to
uppercase

and viceversa

6 a.split() >>> a.split() returns a list of words separated


by space
['happy', 'birthday']

7 a.center(width,”fillchar”) >>>a.center(19,”*”) pads the string with the


specified “fillchar” till the
'***happy birthday***' length is equal to “width”

8 a.count(substring) >>> a.count('happy') returns the number of


occurences ofsubstring
1

9 a.replace(old,new) >>>a.replace('happy', replace all old substrings with


'wishyou happy') new substrings

'wishyou happy birthday'

10 a.join(b) >>> b="happy" returns a string

>>>a="-" concatenated with the


elements of an iterable. (Here
>>>a.join(b) 'h-a-p-p-y' “a” is the iterable)

11 a.isupper() >>> a.isupper() False checks whether all the case based
characters (letters) of the string
are

uppercase.

12 a.islower() >>> a.islower() checks whether all the case-


based characters (letters) of the
True string are lowercase.
13 a.isalpha() >>> a.isalpha() checks whether the string
consists of alphabetic
False characters only.

14 a.isalnum() >>> a.isalnum() checks whether the string


consists of alphanumeric
False characters.

15 a.isdigit() >>> a.isdigit() checks whether the string


consists of digits only.
False

16 a.isspace() >>> a.isspace() checks whether the string


consists of whitespace only.
False

17 a.istitle() >>> a.istitle() checks whether string is title


cased.
False

18 a.startswith(substring) >>> a.startswith("h") checks whether string starts


with substring
True

19 a.endswith(substring) >>> a.endswith("y") checks whether the string


ends with the substring
True

20 a.find(substring) >>> a.find("happy") returns index of substring,if it is


found. Otherwise -1
0
is returned.

21 len(a) >>>len(a) Return the length of the

>>>14 string

22 min(a) >>>min(a) Return the minimum character


in the string
>>>‟ „

23 max(a) max(a) Return the maximum character


in the string
>>>‟y‟

11.Exception Handling with example


A: Handling Exceptions:

∙ Suspicious code may raise an exception.

∙ Exceptions can be handled using try and except statement.

∙ suspicious code is placed in a try: block. Exceptions are handled in except block.

try…except

try… except…else

try…except…else….finally

try…multiple exception

try….except block:

⮚ If any code within the try statement causes an error, execution of the code
will stop and jump to the except statement.

⮚ The except block will be executed when an exception happens. ⮚ The lines
after the error line will never be executed in the try block. Syntax

try:

code that create exception

except:

exception handling statement

Example program Output: Description

try: Hello world Since, try block of code does not have
error, except block of code is not
print("Hello world") executed.

except:

print("This is an error
message")

try: Hello world First line of code in try block has no


exception and it is executed.
print("Hello world") This is an error
message But second line of code has error. So,
x=10/0 except block of code is executed.

print("Welcome")

except:

print("This is an error
message")

try ... except ... else clause:

∙ Else part will be executed only if the try block doesn’t raise an exception.

∙ Python will try to process all the statements inside try block. If value error occurs, the
flow of control will immediately pass to the except block and remaining statement in
try block will be skipped.

Syntax

try:

code that create exception

except:

exception handling statement

else:

statements

Example Output

try: enter your age: six

age=int(input("enter your age")) entered value is not a number enter


your age:6
except:
your age is 6
print("entered value is not a

number")

else:
print("your age is %d:"%(age))

Using try….finally block:

⮚ The close( ) method is not entirely safe. If an exception occurs when we are performing
some operation with the file, the code exits without closing the file.

⮚ The finally block is a place to put any code that must execute, whether the try-
block raised an exception or not.

Syntax:

try:

code that create exception

except:

exception handling statement

else:

statements

finally:

statements

Example: Output:

try: enter your age: six

age=int(input("enter your age:")) entered value is not a number Thank


you
except ValueError:
enter your age:5
print("entered value is not a number") else:
your age is 5
print("your age :”,age)
Thank you
finally:

print("Thank you")
try…multiple exception:

Syntax:

try:

code that create exception

except:

exception handling statement

except:

statements

Example Output:

a=int(input("enter a:")) enter a:2

b=int(input("enter b:")) enter b:0

try: cant divide by zero

c=a/b enter a:2

print(c) enter b: h

except ZeroDivisionError: its not a number

print("cant divide by zero")

except ValueError:

print("its not a number")

12.File operations – Open , Read, Write, Append, Close

A: FILE OPERATIONS:

Files in python can be manipulated via the following file operations: ∙


Opening a file

∙ Reading from a file

∙ Writing to a file

∙ Appending a file

∙ Closing a file

Opening a file

All files must be opened first before they can be used. In python, when a file is opened, a
file object is created that provides methods for accessing the file. In python there is a built
in function open() to open a file.

Syntax:

file_object=open(filename,accessmode)

where file_object is used as a handle to the file

file_name-contains a string type value containing the name of the file which we
want to access

access_mode-specifies the mode in which we want to open the file

#Example for opening a file

fp1=open("sample.txt","w")

print(fp1)

fp=open("sample.txt","r")

print(fp)

Output:

<_io.TextIOWrapper name='sample.txt' mode='w' encoding='cp1252'>


<_io.TextIOWrapper name='sample.txt' mode='r'

encoding='cp1252'>

#Example for opening a file when the file does not exists

fp1=open("sample1.txt","r")

print(fp1)

Output:

fp1=open("sample1.txt","r")

FileNotFoundError: [Errno 2] No such file or directory: 'sample1.txt'

PYTHON FILE OPENING MODES:

Modes Description

r Opens a file for reading only. The file pointer is placed at the beginning of the file.
This is the default mode.
rb Opens a file for reading only in binary format. The file pointer is placed at
the beginning of the file. This is the default mode.

r+ Opens a file for both reading and writing. The file pointer placed at the
beginning of the file.

rb+ Opens a file for both reading and writing in binary format. The file pointer
placed at the beginning of the file.

w Opens a file for writing only. Overwrites the file if the file exists. If the file does
not exist, creates a new file for writing.

wb Opens a file for writing only in binary format. Overwrites the file if the file exists.
If the file does not exist, creates a new file for writing.

w+ Opens a file for both writing and reading. Overwrites the existing file if the file
exists. If the file does not exist, creates a new file for reading and writing.

wb+ Opens a file for both writing and reading in binary format. Overwrites the
existing file if the file exists. If the file does not exist, creates a new file for reading
and writing.

a Opens a file for appending. The file pointer is at the end of the file if the file
exists. That is, the file is in the append mode. If the file does not exist, it creates
a new file for writing.

ab Opens a file for appending in binary format. The file pointer is at the end of the file
if the file exists. That is, the file is in the append mode. If the file does not exist, it
creates a new file for writing.
a+ Opens a file for both appending and reading. The file pointer is at the end of the file
if the file exists. The file opens in the append mode. If the file does not exist, it
creates a new file for reading and writing.

ab+ Opens a file for both appending and reading in binary format. The file pointer is
at the end of the file if the file exists. The file opens in the append mode. If the file
does not exist, it

creates a new file for reading and

writing.

Note: When opening a file if the access mode is not specified, the file is opened in read
mode

File object attributes:

Once a file is opened and a file object is created, various pieces of information about the
file can be gathered by using some predefined attributes. There are basically four types of
attributes as shown below:

Attribute Description

file.closed Returns true if file is closed, false

otherwise.

file.mode Returns access mode with

which file was opened.

file.name Returns name of the file.

file.softspace Returns false if space explicitly required with


print, true otherwise.
#File object attributes

fp=open("sample.txt","r")

print("Name of the file",fp.name)

print("closed or not",fp.closed)

print("opening mode",fp.mode)

print("File object",fp)

fp.close()

print("Name of the file",fp.name)

print("closed or not",fp.closed)

print("opening mode",fp.mode)

print("File object",fp)

Output:

Name of the file

sample.txt closed or

not False opening

mode r

File object <_io.TextIOWrapper name='sample.txt' mode='r' encoding='cp1252'>


Name of the file

sample.txt closed or

not True

opening mode r

File object <_io.TextIOWrapper name='sample.txt' mode='r' encoding='cp1252'>

Reading from a file

In order to read from a file, the file must be opened in r mode. A file can be read in four
different ways:

∙ read(size)

∙ readline()
∙ readlines()

∙ loop

read() method:

The read() enables reading the contents of an opened file.

Syntax:

fileobject.read()

fileobject.read(sie)

where size argument is optional. When the size is not specified, the entire file is read.
When the size is specified, the size number of characters is read. When an empty file is
read, no error is thrown but an empty string is returned.

readline() method:

This method is used for reading a file line by line. This method reads a file till the
newline character including the newline character.

Syntax:

fileobject.readline()

fileobject.readline(size)

where size is optional. When size is specified the size number of characters are
read, otherwise it is similar to read()

readlines() method:

The readlines() method returns a list of lines of the entire


file. Syntax:

fileobject.readlines() fileobject.readlines(size)

When size is not specified, the entire file is read and each line is added as an
element in a list.

Using loop:

A file can be read line by line using for loop

Syntax:

for line in <filevariablename>:

statements for file

operations

Example for reading a file using various methods:

Let sample1.txt be the file


#Reading a file using read()

method

fp=open("sample1.txt","r")

print("Read a file using read()")

print(fp.read())

fp.close()

Output:

Read a file using read()

This is line1 in file reading

operation This is line2

This is line3

This is line4

#Reading a file using read(size) method

fp=open("sample1.txt","r")

print(fp.read(10)) fp.close()

Output:

Read a file using read(size)

This is li

#Reading a file using readline() method

fp=open("sample1.txt","r")

print("Read a file using readline()")

print(fp.readline())

fp.close()

Output:

Read a file using readline()


This is line1 in file reading operation

#Reading a file using readlines()

methods fp=open("sample1.txt","r")

print("Read a file using readlines()")

print(fp.readlines())

fp.close()

Output:

Read a file using readlines()

['This is line1 in file reading operation\n', 'This is line2\n', 'This is line3\n', 'This is
line4']

#Reading a file using loop

fp=open("sample1.txt","r") for line in fp:

print("The contents of the file are")

print(line)

fp.close()

Output:

The contents of the file are

This is line1 in file reading

operation The contents of the

file are

This is line2

The contents of the file

are This is line3

The contents of the file

are This is line4

Writing to a file

In order to write into a file, the file has to be opened in “w” mode or “a” mode or any other
writing mode. The “w‟ mode overwrites the file if the file already exists. If the file does
notexist, a new file is opened for writing.

Syntax:

fileobject=open(“filename”,”w”)

The write operation can be done using the following ways:

∙ write()
∙ writelines()

write() method:

The write method puts data into the file.

The write() method writes any string to an open file.

The write() method does not add a newline character ('\n') to the end of the string
Syntax:

fileobject.write(string)

Where string is the content that is written to the file

writelines()

The writelines method puts multiple data into the

file. The writelines() method writes any string to

an open file.

Syntax : fileobject.writelines(string)

Example for writing a file when the file already exists

#Writing to a file when the file already exists

fp=open("sampletest.txt","w")

fp.write("This content is written to the file")

fp.close()

Output:

Before write operation

After write operation


Example:

#Writing to a file using write()

fp=open("samp.txt","w")

fp.write("This content is written to the file using write()")

fp.close()

Example:

#Writing to a file using writelines()

fp=open("samp1.txt","w")

fp.writelines("This content is written to the file using writelines()\nThis is line2")


fp.close()

Appending a file:
This operation is used to write the content to the end of the file. To perform this
operation, the file has to opened in „a‟ mode

Opening a file in append mode:

Syntax:

fileobject=open(“filename”,”a”)

Example:

#Appending to a file when the file already exists

fp=open("samp1.txt","w")

fp.write("This content is appended to the end of the file")

fp.close()

Before the append operation:

After append operation

Closing a file:

When the operations that are to be performed on an opened file are finished, the file has
to be closed in order to release the resources. Proper closing of file frees up the resources
held with the file. The closing of file is done with the built-in function close()

Syntax:

fileobject.close()

Example:
#Closing a file

fp=open("new.txt","r")

print(fp.read()) fp.close()

Output:

This file is closed

Closing a file using with:

A file can also closed using with the statement as follows:

Syntax:

with open(“filename”,accessmode) as fileobject:

statements for file operations

#Closing a file using with

with open("new.txt","r") as fp:

print(fp.read())

fp.close()

Output:

This file is closed

13.Write a python program to generate Fibonacci sequence for n terms.


A: n=int(input("enter number of terms"))
a,b=0,1
for i in range(n):
print(a)
a,b=b,a+b
output:
enter the number of terms10
0
1
1
2
3
5
8
13
21
34
14.Write a python program to generate prime number with an given range n->(n1,n2) and n1,n2
inclusive.
A: n1=int(input("enter the starting number of the range"))
n2=int(input("enter the ending number of the range"))
for i in range(n1-1,n2+1):
l=[]
for j in range(1,i+1):
if i%j==0:
l.append(j)
if len(l)==2:
print(i)
output:
enter the starting number of the range1
enter the ending number of the range100
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97
15.Describe the following
(i) Creating the tuples

(ii) Accessing values in the tuples

(iii) Deleting the tuples elements

(iv) Maximum and minimum elements in tuples


(v) Compare the elements in tuples.

A: TUPLES:

A tuple is a sequence of values enclosed in parenthesis. The values can be any type.
Tuples are immutable. The values of the tuple cannot be changed.

Creating a tuple:

The tuples can be created by placing elements inside parenthesis separated by


commas and assigned to a variable.

Syntax: tuplevariablename=(value1,value2,…valuen)

Example:

t=(1,2,3,4)

t1=(“a”,1,2,3,”hello”)

t3=(“Python”,[1,2,3])

t4=(10,) #tuple with single element

Accessing values in tuple:

In order to access the values in a tuple, it is necessary to use the index number
enclosed in square brackets along with the name of the tuple.

Example:

t1=(1,”python”,10,20)

t1[1] will access the value “python” from the tuple t1

13

#Example using tuples

t1=(1,2,3,"python",10)

print(t1)

print(t1[3])

print(type(t1))

t2=(10)

print(type(t2))

#tuple with single element should


end with a comma t3=(10,)

print(type(t3))

print(t1[1:])
print(t1[-4:])

print(t1[1:4])

OUTPUT:

(1, 2, 3, 'python', 10)

python

<class 'tuple'>

<class 'int'>

<class 'tuple'>

(2, 3, 'python',10)

(2, 3, 'python',10)

(2, 3, 'python')

TUPLES ARE IMMUTABLE:

Tuples are immutable. The elements of the tuple cannot


be changed. Example:

#Example to show tuples are

immutable list1=[10,20,30]

print(list1)

list1[0]=100

print(list1)

t1=(1,2,3,"python",10)

print(t1)

t1[0]=10

print(t1)

14

Output:

[10, 20, 30]

[100, 20, 30]

(1, 2, 3,'python', 10)

t1[0]=10

TypeError: 'tuple' object does not support item assignment

Basic Tuples Operations


Built-in Tuple Functions:

Python includes the following tuple functions

methods example description

a.index(tuple) >>> a=(1,2,3,4,5) Returns the index of the first


matched item.
>>> a.index(5) 4

15
a.count(tuple) >>>a=(1,2,3,4,5) Returns the count of the given
element.
>>> a.count(3) 1

len(tuple) >>> len(a) 5 return the length of the

tuple

min(tuple) >>> min(a) 1 return the minimum

element in a tuple

max(tuple) >>> max(a) 5 return the maximum

element in a tuple

del(tuple) >>> del(a) Delete the entire tuple.

16. Write a program that reads the contents of the file text.txt and counts the number of alphabets, blank
spaces, lowercase letters and uppercase letters, the number of words starting with a vowel, and the
number of occurrences of the word ‘is’ in the file.

A: f=open('gojo.txt','w')

a=input("enter text")

f.write(a)

f.close()

f1=open('gojo.txt','r')

a1=f1.read()

b1=a1.split()

c1=0

c2=0

c3=0

c4=0

c5=0

c6=0

for i in a1:

if i in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ':
c1+=1

if i==' ':

c2+=1

if i in'abcdefghijklmnopqrstuvwxyz':

c3+=1

if i in'ABCDEFGHIJKLMNOPQRSTUVWXYZ':

c4+=1

for j in b1:

if j[0]in'aeiouAEIOU':

c5+=1

if j=='is':

c6+=1

print("the number of alphabets is:",c1)

print("the number of blank spaces is:",c2)

print("the number of lowercase letters:",c3)

print("the number of uppercase letters:",c4)

print("the number of words starting with a vowel",c5)

print("the number of occrence of the word",'is',c6)

f1.close()

output:

enter textlove is the most twisted curse of ALL

the number of alphabets is: 30

the number of blank spaces is: 7

the number of lowercase letters: 27

the number of uppercase letters: 3

the number of words starting with a vowel 3

the number of occrence of the word is 1

17.Explain about exceptions and four types of Exceptions . Give an example for each type.
A: EXCEPTIONS:

An exception is a value (object) that is raised (“thrown”) signaling that an unexpected, or


“exceptional”, situation has occurred. Python contains a predefined set of exceptions
referred to as standard exceptions .

An exception is an event, which occurs during the execution of a program that disrupts
the normal flow of the program's instructions. In general, when a Python script
encounters a situation that it cannot cope with, it raises an exception. An exception is a
Python object that represents an error.

When a Python script raises an exception, it must either handle the exception
immediately otherwise it terminates and quits.

Errors

1. Syntax error

2. Indentation error

3. Index error

4. Name error

5. Logical error

Example.py (Syntax error)

if x<10

print(X)

Output:

Invalid Syntax

Example.py (Indentation error)

if x<10:

print(X)

Output:

Expected indent block

(line 2)

Example.py (Index error)

a=[1,2,3,4,5]

print(a[10])

Output:

print(a[10])

IndexError: list index out of range

Example.py (Name error)

x=10
print(X)

Output:

print(X)

NameError: name 'X' is not defined

Example.py (Logical error)

i=0

while i<5:

print(i)

i=i+1

Output:
00

0 (infinite loop,since i=i+1 is placed outside while loop)

You might also like