Python Important Questions and Answers
Python Important Questions and Answers
Part B
Important Question
A: BREAK
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
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
Syntax:
try:
except:
else:
statements
finally:
statements
Example: Output:
try:
except ValueError:
else:
finally:
print("Thank you")
Thank you
your age is 5
Thank you
Example:
def add(x,y):
sum=x+y
return sum
a=int(input("Enter a ="))
b=int(input("Enter b ="))
Output:
Enter a=5
Enter b=5
describe a method for solving a problem..in other words it is a step by step procedure for solving a
problem
A: a=input("enter a string:")
if a[::-1]==a:
print("the entered string is a palindrome")
else:
output:
enter a string:racecar
6. Write a Python program to change a given string to a new string where the first and last chars have
been exchanged.
l1=l[-1]+l[1:-1]+l[0]
print(l1)
output:
print(l[::-1])
output:
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
output:
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:
output:
A:
Step 1: Start
Step 7: go to step 4
Step 8: Stop
The building blocks of algorithm refer to the blocks such as statements, state, control flow
Statements
State
Control flow
Functions
A:
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
for i in “programming”:
if(i==”a”):
continue
print(i)
A:p
a=”Python Programming”
print(a[2:8])
print(a[-3:])
A: thon P
ing
and again based upon conditional test. i.e. executed more than
for i in range(1,6):
print(i)
else:
output:
4
5
Recursions:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
# Example usage:
number = 5
result = factorial(number)
output:
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
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
a-append mode
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.
A: Repetitions:
a= “gojo ”
>>>print(3*a)
gojogojogojo
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
print(list1)
Output:
[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
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
#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=[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]
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]]
A: Operations onstring:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Membership
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
The following are the operations that can be performed on the lists:
1. CONCATENATION:
Example:
>>> list1=[10,20,30,40]
>>> list2=['python','program']
>>> list3=list1+list2
>>> list3
2. REPETITION:
>>> list4=[1,2,3,'python']
>>> list4*3
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
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:
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
Syntax:
Listname.clear()
Listname.copy()
list1=[1,2,3,5]
list1.append(10)
Output:
15
a.count(tuple) >>>a=(1,2,3,4,5) Returns the count of the given
element.
>>> a.count(3) 1
tuple
element in a tuple
element in a 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:
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
pop(): Removes an element from the dictionary for which the key is provided
Example:
#Dictionary Deletion
cubes={1:1,2:8,3:27,4:64,5:125,6:216}
print(cubes)
del cubes
print(cubes)
Output:
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)
Output:
True
False
True
DICTIONARY METHODS:
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:
d={1:1,2:8,3:27,4:64,5:125}
22
print(d)
d.clear()
print(d)
Output:
{}
dict.copy():
This method returns a copy of the dictionary.
Syntax:
dictname.copy()
Example:
d={1:1,2:8,3:27,4:64,5:125}
print(d)
c=d.cop
y()
print(c)
Output:
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
Example:
d={1:1,2:8,3:27,4:64,5:125}
print(d)
c=d.fromkeys([1,2,3],"python")
print(c)
Output:
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
default - This is the Value to be returned in case key does not exist.
Example:
d={1:1,2:8,3:27,4:64,5:125}
print(d)
Output:
dict.items():
This method items() returns a list of dict's (key, value) tuple pairs.
dict.items()
Example:
d={1:1,2:8,3:27,4:64,5:125}
print(d)
Output:
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:
d={1:1,2:8,3:27,4:64,5:125}
print(d)
Output:
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
d={1:1,2:8,3:27,4:64,5:125}
print(d)
print(d)
Output:
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:
dict.values()
The method values() returns a list of all the values available in a given
dictionary. Syntax:
dict.values()
Example:
d={1:1,2:8,3:27,4:64,5:125}
print(d)
Output:
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):
l.append(a)
output:
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=[]
for i in range(a):
if a1>0:
l.append(a1)
elif a1<0:
for j in range(b):
if b1<0:
l.append(b1)
elif b1>0:
output:
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
∙ 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.
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:
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
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
/ Divide left operand by the right one (always results into float) 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:
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 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
+= 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
25
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
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
A B A and B
Bitwise Operators:
Truth table for or
A B A or B
A not A
True False
❖ 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
∙ 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
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.
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:
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
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
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)
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")
output
enter a no:7
The num is a prime number.
Output
enter a number:6
the number is perfect number
Output
enter a lower
range5 enter a
upper range15 5
7
11
13
where
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
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.
⮚ 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.
⮚ 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.
⮚ A function f, that
uses another function g, is known as the calling function and g is known as
the called function.
⮚ 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.
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.
integer = -20
Output:
Parameters/Arguments:
A function in python
Syntax:
def function_name(param1,param2):
Statements return
result
Function call:
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:
Actual parameters:
Example:
def cube(x):
return x*x*x
b=cube(a)
Example:
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.
1. Required/Positional parameters
2. Keyword parameters
3. Default parameters
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:
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:
student( “ajay”):
❖ In the function definition we use an asterisk (*) before the parameter name
to denote this is variable length of parameter.
Example Output:
print(name, mark)
student (“bala”,102,90)
A: Operations onstring:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Membership
>>>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
True
True
String slices:
String slices:
Slicing will start from index and will go up to stop in step ofsteps.
Default value of start is 0,
For example 1−
Output:
Hello World!
llo
llo 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[0]='n'
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:
>>> new_greeting
'Jello, world!'
Note: The plus (+) sign is the string concatenation operator and the asterisk (*) is
the repetition operator
print(a)
Stringname.method()
a=”happy birthday”
case
case
characters to
uppercase
and viceversa
11 a.isupper() >>> a.isupper() False checks whether all the case based
characters (letters) of the string
are
uppercase.
>>>14 string
∙ 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:
except:
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")
print("Welcome")
except:
print("This is an error
message")
∙ 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:
except:
else:
statements
Example Output
number")
else:
print("your age is %d:"%(age))
⮚ 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:
except:
else:
statements
finally:
statements
Example: Output:
print("Thank you")
try…multiple exception:
Syntax:
try:
except:
except:
statements
Example Output:
print(c) enter b: h
except ValueError:
A: FILE OPERATIONS:
∙ 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)
file_name-contains a string type value containing the name of the file which we
want to access
fp1=open("sample.txt","w")
print(fp1)
fp=open("sample.txt","r")
print(fp)
Output:
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")
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
writing.
Note: When opening a file if the access mode is not specified, the file is opened in read
mode
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
otherwise.
fp=open("sample.txt","r")
print("closed or not",fp.closed)
print("opening mode",fp.mode)
print("File object",fp)
fp.close()
print("closed or not",fp.closed)
print("opening mode",fp.mode)
print("File object",fp)
Output:
sample.txt closed or
mode r
sample.txt closed or
not True
opening mode r
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:
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:
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:
Syntax:
operations
method
fp=open("sample1.txt","r")
print(fp.read())
fp.close()
Output:
This is line3
This is line4
fp=open("sample1.txt","r")
print(fp.read(10)) fp.close()
Output:
This is li
fp=open("sample1.txt","r")
print(fp.readline())
fp.close()
Output:
methods fp=open("sample1.txt","r")
print(fp.readlines())
fp.close()
Output:
['This is line1 in file reading operation\n', 'This is line2\n', 'This is line3\n', 'This is
line4']
print(line)
fp.close()
Output:
file are
This is line2
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”)
∙ write()
∙ writelines()
write() method:
The write() method does not add a newline character ('\n') to the end of the string
Syntax:
fileobject.write(string)
writelines()
an open file.
Syntax : fileobject.writelines(string)
fp=open("sampletest.txt","w")
fp.close()
Output:
fp=open("samp.txt","w")
fp.close()
Example:
fp=open("samp1.txt","w")
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
Syntax:
fileobject=open(“filename”,”a”)
Example:
fp=open("samp1.txt","w")
fp.close()
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:
Syntax:
print(fp.read())
fp.close()
Output:
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:
Syntax: tuplevariablename=(value1,value2,…valuen)
Example:
t=(1,2,3,4)
t1=(“a”,1,2,3,”hello”)
t3=(“Python”,[1,2,3])
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)
13
t1=(1,2,3,"python",10)
print(t1)
print(t1[3])
print(type(t1))
t2=(10)
print(type(t2))
print(type(t3))
print(t1[1:])
print(t1[-4:])
print(t1[1:4])
OUTPUT:
python
<class 'tuple'>
<class 'int'>
<class 'tuple'>
(2, 3, 'python',10)
(2, 3, 'python',10)
(2, 3, 'python')
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:
t1[0]=10
15
a.count(tuple) >>>a=(1,2,3,4,5) Returns the count of the given
element.
>>> a.count(3) 1
tuple
element in a tuple
element in a 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
f1.close()
output:
17.Explain about exceptions and four types of Exceptions . Give an example for each type.
A: 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
if x<10
print(X)
Output:
Invalid Syntax
if x<10:
print(X)
Output:
(line 2)
a=[1,2,3,4,5]
print(a[10])
Output:
print(a[10])
x=10
print(X)
Output:
print(X)
i=0
while i<5:
print(i)
i=i+1
Output:
00