Skip to main

AK#Notes

Python

a) Name different modes of Python.

Python has two basic modes:

  1. Script mode (or Normal mode)
    • The mode where the scripted and finished .py files are in the Python Interpreter.
    • Interactive mode
    • A command line shell which gives immediate feedback for each statement, while running previously fed statements in active memory.

b) List identity Operators

Operator Description Example
is Returns True if both variables are sames object x is y
is not Returns False if both variables are sames object x is not y

c) Give two differences between list and tuple.

List

Tuple

d) Explain Local and Global variable.

Local Global
It is declare inside a function It is declared outside the function
It is created when the function starts execution and lost when the function terminate. It is created before the program's global execution starts and lost when the program terminates.
Local variables can be accessed with the help of statements, inside a function in which they are declared. You can access global variables by any statement in the program.
Parameters passing is required for local variables to access the value in other function. Parameters passing is not necessary for a global variable as it is visible throughout the program

e) Define class and object in python.

Class

f) How to give single and multiline comment in python.

Single-Line

g) List different modes of opening file in python.

There are four different methods modes for opening a file:

In addition, the file should be handled as binary or text mode:

a) Write a program to print following:

.python
rows = int(input("Enter number of rows: "))

for i in range(rows):
    for j in range(i+1):
        print(j+1, end=" ")
    print("\n")

b) Explain four Buit-in tuple functions python with example.

Explain how to use user defined function in python with example.

In Python, a user-defined function's declaration begins with the keyword def and followed by the function name.

.python
def printt():
    print("This is Python 3.2 Tutorial")
    print("This is Python 3.2 Tutorial")
    print("This is Python 3.2 Tutorial")
printt()

Output:

This is Python 3.2 Tutorial
This is Python 3.2 Tutorial
This is Python 3.2 Tutorial

d) Write a program to create class EMPLOYEE with ID and NAME and display its contents.

.python
class Employee:
	name = ""
	department = ""
	salary = 0

	def setData(self):
		self.name = input("Enter Name: ")
		self.department = input("Enter Department: ")
		self.salary = int(input("Enter Salary: "))

	def showData(self):
		print("Name:", self.name)
		print("Department:", self.department)
		print("Salary:", self.salary)

e = Employee()
e.setData()
e.showData()

Output:

Enter Name: Jonney
Enter Department: Testing
Enter Salary: 20000
Name: Jonney
Department: Testing
Salary: 20000

List Data types used in python. Explain any two with example.

Thare are three data type in python numbers, string & boolean.

String

b) Explain membership and assignment operators with example.

Operator Description Example
in True if value in list or in sequence ('H' in x) is True
not in False if value not in list or in sequence ('H' in x) is False
Operator Description Syntax
= Assign value of right side of expression to left side operand x = y + z
+= Add and Assign: Add right side operand with left side operand and then assign to left operand a += b
-= Subtract AND: Subtract right operand from left operand and then assign to left operand: True if both operands are equal a -= b
*= Multiply AND: Multiply right operand with left operand and then assign to left operand a *= b

c) Explain indexing and slicing in list with example.

d) Write a program for importing module for addition and substraction of two numbers.

.python
a = int(input("Enter first number: "))
b = int( input("Enter second number: "))
Sum = a+b; #Add two numbers
Difference = a-b; #Subtract two numbers
# To print the result
print("Addition of two numbers = ",Sum)
print("Subtraction of two numbers = ",Difference)

Output:

Output:
Enter first number: 30
Enter second number: 20
Addition of two numbers = 50
Subtraction of two numbers = 10

a) Write a program to create dictionary of students that includes their ROLL NO. and NAME:

i) Add three students in above dictionary ii) Update name= 'Shreyas' of ROLL NO = 2 iii) Delete information of ROLL NO = 1

.python
students = {
  1: "ronney",
  2: "jay"
}

students[2] = "Shreyas"
del students[1]
print(students)

Output:

{ 2: "Shreyas" }

b) Explain decision making statements If-else, if-elif-else with example.

The if…elif…else statement is used in Python for decision making.

.python
num = 3.4

if num > 0:
    print("Positive number")
elif num == 0:
    print("Zero")
else:
    print("Negative number")

c) Explain use of format () method with example.

Python format() function has been introduced for handling complex string formatting more efficiently.

.python
txt = "I have {an:.2f} Ruppes!"
print(txt.format(an = 4))

Output:

I have 4.00 Ruppes!

d) Explain building blocks of python.

e) Write a program illustrating use of user defined package in python.

Packages are a way of structuring many packages and modules which helps in a well-organized hierarchy of data set, making the directories and modules easy to access.

file1.py:

.python
class Bmw:
    # First we create a constructor for this class
    # and add members to it, here models
    def __init__(self):
        self.models = ['i8', 'x1', 'x5', 'x6']

    # A normal print function
    def outModels(self):
        print('These are the available models for BMW')
        for model in self.models:
            print('\t%s ' % model)

file2.py

.python
from Bmw import Bmw

Write the output of the following:

>>> a = [2, 5, 1, 3, 6, 9, 7]
>>> a[2:6] = [2, 4, 9, 0]
>>> print (a)

Ans:

[2, 5, 2, 4, 9, 0, 7]
b = ["Hello", "Good"]
b.append("python")
print (b)

Ans:

['Hello', 'Good', 'python']
t1 = [3, 5, 6, 7]
print (t1[2])
print (t1[-1])
print (t1[2:])
print(t1[:])

Ans:

6
7
[6, 7]
[3, 5, 6, 7]

Explain method overloading in python with example.

Write a program to open a file in write mode and some contents at the end of file.

.python
o = open("name.txt", "w")
o.write("I am a programmer")
o.close()
o = open("name.txt", "r")
print(o.read())
o.close()

O/P

I am a programmer

a) Explain package Numpy with example.

6) Write a program to implement the concept of inheritance in python.

.python
class Parent:
	parentname = ""
	childname = ""
	def show_parent(self):
		print(self.parentname)

class Child(Parent):
	def show_child(self):
		print(self.childname)

c = Child()
c.parentname = "Arati"
c.childname = "Purva"
c.show_parent()
c.show_child()

c) Explain Try-except block used in exception handling in python with example.

1. Introduction and Syntax of Python Program

3. Enlist applications for Python programming.

Python is often used as a support language for software developers, for build control and management, testing, and in many other ways.

4. What are the features of Python?

5. List any four editors used for Python programming.

6. 'Python programming language is interpreted an interactive' comment this sentence.

Python has two basic modes:

Script mode

The normal script mode is the mode where the scripted and finished .py files are run in the Python interpreter.

Interactive mode

The interactive mode is a command line shell which gives immediate feedback for each statement while running previously fed statements in active memory.

7. How to run python scripts? Explain in detail.

Open a command line and type the word python followed by the path to your script file, like this: python first_script.py Hello World! Then you hit the ENTER button from the keyboard and that's it.

8. What is interpreter? How it works? 9. Explain the following features of Python programming:

(i) Simple

Python is considered one of the easiest programming languages to learn.

(ii) Platform independent

Python is a binary platform-independent programming language. The same Python code can run on virtually all operating systems and platforms.

(iii) Interactive

Interactive mode is a command line shell which gives immediate feedback for each statement, while running previously fed statements in active memory.

(iv) Object Oriented.

Object-oriented Programming is a programming paradigm that uses objects and classes in programming. It aims to implement real-world entities like inheritance, polymorphisms, encapsulation, etc. in the programming.

12. Write in brief about characters set of Python.

The character set is a set of alphabets, letters, symbols and some special characters that are valid in Python programming language.

Keywords

13. Write in brief about any five keywords in Python.

  1. True - is used as the Boolean true value in Python code.
  2. False - is used as the Boolean false value in Python code.
  3. break - is used to break the loop.
  4. def - is used to define the function in Python.
  5. while - is used to make while loop in Python.

15. What is the role of indentation in Python?

16. How to comment specific line(s) in Python program?

17. What is variable? What are the rules and conventions for declaring a variables?

18. What are the various data types available in Python programming.

Numbers

Integers(int)

Floating Point Numbers

Complex Number

Boolean

String

19. What are four built-in numeric data types in Python? Explain.

The built-in numeric data types are Numbers, Integers, Float and Complex Number.

Numbers

Integers(int)

Floating Point Numbers

Complex Number

20. What is the difference between interactive mode and script mode of Python.

Python has two basic modes:

Script mode

The normal script mode is the mode where the scripted and finished .py files are run in the Python interpreter.

Interactive mode

The interactive mode is a command line shell which gives immediate feedback for each statement while running previously fed statements in active memory.

22. Define the following terms:

(i) Identifier

(ii) Literal

(iii) Data type

Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data.

(iv) Tuple

(v) List.

23. Explain dictionary data tune in detail

Sets

Difference between List, Set, Tuple, and Dictionary

List Set Tuple Dictionary
Mutable Mutable Mutable Immutable Mutable
Order Ordered Unordered Ordered Ordered
Can item be Replaced or Changed Can't Replaced or Changed Can't be Replaced or Changed Replace or Changed

String methods

Operation Explanation Example
upper Converts to uppercase x.upper()
lower Converts to lowercase x.lower()
title Capitalize the first letter of each word in a string x.title()
find, index Search for the target in a string. x.find("hello"), index("hello")
rfind, rindex Search for the target in a string x.xfind("hello"), x.xfind("hello")
replace Replaces the target with new string r.replace("hello", "word")
strip, rstrip, lstrip Removes whitespace or other characters from the ends of a string. x.strip()
encode Converts a Unicode string to a bytes object. x.encode("utf_8")

2. Python Operators and Control Flow Statements

1. What is operator? Which operators used in Python?

Unary Operators

Binary Operators

2. What is meant by control flow of a program?

3. Define the terms:

(i) Loop

A loop statement allows us to execute a statement or group of statements multiple times, this is called loop.

(ii) Program

A program is a sequence of statements that have been crafted to do something.

(iii) Operator

Unary operators perform mathematical operation only on one operand.

(iv) Control flow.

A program's control flow is the order in which the program's code executes.

4. What are the different loops available in Python?

5. What happens if a semicolon (;) is placed at the end of a Python statement?

In Python a semicolon works as a separated between statements and not as a terminator of statements.

6. Explain about different logical operators in Python with appropriate examples.

Operator Description Example
AND If both the values are true then condition becomes true (a and b) is False
Or If any of two values are true then condition becomes true (a or b) is True
Not Used to reverse the local state of its value not(a and b) is True

7. Explain about different relational operators in Python with examples.

Operator Name Example
== Equal x == y
!= Not equal x != y
> Greater than x > y
< Less than x < y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y

8. Explain about membership operators in Python.

Operator Description Example
in True if value in list or in sequence ('H' in x) is True
not in False if value not in list or in sequence ('H' in x) is False

9. Explain about Identity operators in Python with appropriate examples.

Operator Description Example
is True if the variable on either side points to the same object (a is b) is False
is not False if the variable on either side points to the same object (a is not b) is False

10. Explain about arithmetic operators in Python.

Operator Name Example
+ Addition x + y
- Subtraction x - y
* Multiplication x * y
/ Division x / y
% Modulus x % y
** Exponentiation x ** y
// Floor division x // y

11. List different conditional statements in Python.

Python conditional statements includes:

12. What are the different nested loops available in Python?

13. What are the different loop control (manipulation) statements available in Python? Explain with suitable examples.

There three loop control statements available in Python:

14. Explain if-else statement with an example.

15. Explain continue statement with an example.

The continue statement in Python returns the control to the beginning of the while loop.

.python
i = 0
while i < 10:
  i = i + 1
  if i == 5:
    continue

16. Explain use of break statement in a loop with example.

The break statement in Python terminates the current loop and resumes ececution at next statement.

.python
i = 0
while i<10:
  i=i+1
  if i == 5:
    break
  print("i = ", i)

17. Predict output and justify your answer:

(i) -11 % 9

>>> print(-11 % 9)
-2

(ii) 7.7 // 7

>>> print(7.7 // 7)
1.0

(iii) (200 - 70) * 10 / 5

>>> print((200 - 70) * 10 / 5)
260.0

(iv) 5 * 1 ** 2

>>> print(5 * 1 ** 2)
5

18. What the difference is between == and is operator in Python?

19. List different operators in Python, in the order of their precedence.

Operators Example
Arithmetic Operators a + b
Assignment Operators c = a + b
Comparison Operators a == b
Logical Operators a and b
Bitwise Operators a & b
Identity Operators a = 3
Membership Operators a in b

20. Write a Python program to print factorial of a number. Take input from user.

21. Write a Python program to calculate area of triangle and circle and print the result.

22. Write a Python program to check whether a string is palindrome.

23. Write a Python program to print Fibonacci series up to n terms.

.python
num = int(input("Enter a num: "))
x = 0
y = 1

if num < 0:
  print("Invalid term")
else:
  for i in range(num):
    print(x)
    z = x + y
    x = y
    y = z

O/P

Enter a num: 3
0
1
1

24. Write a Python program to print all prime numbers less than 256.

.python
num = int(input("Enter number: ")
for n in range(2, num):
  if n % 1 == 0:
    break
  else:
    print(n)

25. Write a Python program to find the best of two test average marks out of three test's mark accepted from the user.

Assignment Operator

Operator Example Same As
= x = 5 x = 5
+= x += 3 x = x + 3
-= x -= 3 x = x - 3
*= x *= 3 x = x * 3
/= x /= 3 x = x / 3
%= x %= 3 x = x % 3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
&= x &= 3 x = x & 3
|= x |= 3 x = x | 3
^= x ^= 3 x = x ^ 3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3

Relational or Comparison Operators

Operator Name Example
== Equal x == y
!= Not equal x != y
> Greater than x > y
< Less than x < y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y

Bitwise Operators

Operator Name Description
& AND Sets each bit to 1 if both bits are 1
| OR Sets each bit to 1 if one of two bits is 1
^ XOR Sets each bit to 1 if only one of two bits is 1
~ NOT Inverts all the bits
<< Zero fill left shift Shift left by pushing zeros in from the right and let the leftmost bits fall off
>> Signed right shift Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off

3. Data Structures in Python

1. What is data structure? Which data structure used by Python?

2. How to define and access the elements of list?

3. What is list? How to create list?

4. What are the different operation that can be performed on a list? Explain with examples

5. Explain any two methods under lists in Python with examples.

append()

extend()

6. Write a python program to describe different ways of deleting an element form the given List.

remove() - is used to remove an element form the list.

.python
li = ["Hello", "World"]
li.remove("Hello")
print(li)

O/P

World

7. What is tuple in Python? How to create and access it?

8. What are mutable and immutable types?

9. Is tuple mutable? Demonstrate any two methods of tuple.

10. Write in brief about Tuple in Python. Write operations with suitable examples

Tuple Operations

O/P

(1, 2, 3, 4)
(1, 2, 1, 2)
True
1
2

11. Write in brief about Set in Python. Write operations with suitable example.

12. Explain the properties of dictionary keys.

13. Explain directory methods in Python.

14. How to create directory in Python? Give example.

15. Write in brief about Dictionary in Python. Write operation with suitable examples.

Operation of Dictionary

.python
d = { "brand": "Ford", "model": "Mustang", "year": 1264 }
print("brand" in d)

for i in d:
  print(i, d[i])

O/P

True
brand Ford
model Mustang
year 1264

16. What is the significant difference between list and dictionary?

List

Dictionary

17. Compare List and Tuple.

List

Tuple

19. How append() and extend() are different with reference to list in Python?

append()

extend()

20. Write a program to input any two tuples and interchange the tuple variable.

.python
a = 1
b = 2
(a, b) = (b, a)
print("a =", a, "b =", b)

O/P

a = 2 b = 1

21. Write a Python program to multiply two matrices

22. Write a Python code to get the following dictionary as output: {1:1, 3:9, 5:25, 7:49, 9:81}

.python
di = {1:1, 3:9, 5:25, 7:49, 9:81}
print(di)

O/P

{1:1, 3:9, 5:25, 7:49, 9:81}

23. Write the output for the following:

>>>a=[1,2,3]
>>>b=[4,5,6]
>>>c=a+b
[1, 2, 3, 4, 5, 6]
>>>[1,2,3]*3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
>>>t=['a', 'b', 'c', 'd', 'e', 'f']
>>>t[1:3]=['x', 'y']
>>>print(t)
['a', 'x', 'y', 'd', 'e', 'f']

24. Give the output of Python code:

Str="Maharashtra State Board of Technical Education'
print(x[15::1])
print(x[-10:-1:2])

O/P

te Board of Technical Education
 dcto

25. Give the output of following Python code:

t=(1,2,3, (4,), [5,6])
print(t[3])
t[4][0]=7
print(t)

O/P

(4,)
(1, 2, 3, (4,), [7, 6])

26. Write the output for the following if the variable fruit="banana":

>>>fruit[:3]    o/p='ban'
>>>fruit[3:]    o/p='ana'
>>>fruit[3:3]   o/p=' '
>>>fruit[:]     o/p='banana'

27. What is string? How to create it? Enlist various operations on strings.

O/P

H
True
ello World
True

5. Object Oriented Programming in Python

1. What is OOP?

2. List the features and explain about different Object Oriented features supported by Python.

3. List and explain built in class attributes with example.

4. Design a class that store the information of student and display the same.

5. What are basic overloading methods?

6. What is method overriding? Write an example.

7. Explain class inheritance in Python with an example.

8. How to declare a constructor method in python? Explain.

9. How operator overloading can be implemented in Python? Give an example.

10. Write a Python program to implement the concept of inheritance.

11. Create a class employee with data members: name, department and salary. Create suitable methods for reading and printing employee information.

12. What is data abstraction? Explain in detail. 13. Define the following terms:

(1) Object

(ii) Class

(iii) Inheritance

(iv) Data abstraction.

14. Describe the term composition classes with example.

15. Explain customization via inheritance specializing inherited methods.

6. File I/O Handling and Exception Handling

1. What is file? Enlist types of files in Python programming.

Text Files

Binary Files

2. What is exception?

An exception is also called as runtime error that can halt the execution of the program.

3. Explain the term exception handling in detail.

4. Explain different modes of opening a file.

Mode Description
r Opens a file for reading.
w Opens a file for writing.
x Opens a file for exclusive creation. If the file already exists, the operation fails.
a Opens a file for appending at the end of the file without truncating it. Creates a new file if it does not exist.
t Opens in text mode.
b Opens in binary mode.
+ Opens a file for updating (reading and writing)

5. Write the syntax of fopen() with example.

O/P

  Hello World

6. What are various modes of file object? Explain any five as them.

Mode Description
r Opens a file for reading.
w Opens a file for writing.
x Opens a file for exclusive creation. If the file already exists, the operation fails.

7. Explain exception handling with example using try, except, raise keywords.

O/P

Enter your age: 16
You are not 18

Python practical question bank solved

1) WAP to create 3x3 matrix with 1 at the border and zero inside.

.python
import numpy as n
a=n.ones((3, 3))
a[1:-1,1:-1]=0
print(a)

Output

[[1. 1. 1.]
 [1. 0. 1.]
 [1. 1. 1.]]

2) WAP to calculate area of circle and area of rectangle using abstract class.

.python
from abc import ABC, abstractmethod
class test(ABC):
    @abstractmethod
    def area(self):
        pass
class Rec(test):
    def area(self):
        self. l=4
        self. b=2
        print(self.l*self.b)
class Cir(test):
    def area(self):
        self.r=5
        print(3.14*self.r*self.r)
R=Rec()
R. area()
C=Cir()
C. area()

Output

8
78.5

3) WAP to create dictionary where key is 1 to 10 and value is square of 1 to 10.

.python
a=dict()
for i in range(1,11):
    a[i]=i**2
print(a)

Output {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100}

4) WAP to display result using inheritance.

.python
class Student:
    def accept(self):
        self. name=input("Name:")
class Test:
    def marks(self):
        self. m1=int(input("M1:"))
        self. m2=int(input("M2:"))
class Result(Student, Test):
    def total(self):
        self. t=self.m1+self.m2
    def disp(self):
        print(self.name)
        print(self.t)
r=Result()
r. accept()
r. marks()
r. total()
r. disp()

Output

Name:ramesh
M1:80
M2:70
ramesh
150

5) WAP to remove duplicates from dictionary.

.python
d={1:20, 1:20, 2:30}
res={}
for x, y in d. items() :
    if y not in d. items() :
        res[x]=y
print(res)

Output {1: 20, 2: 30}

6) WAP to print sum of entered no. using function with arbitrary argument arguments.

.python
def sum(*x):
    n=0
    for i in x:
        n+=i
    print(n)
sum(1, 2,3,4,5)

Output 15

fibonacci.py

.python
def fib(n):
  n1, n2= 0,1
  for i in range(n):
    print(n1)
    nth=n1+n2
    n1=n2
    n2=nth

fib.py

.python
import fibonacci
print(fibonacci.fib(5))

To run the code, run fib.py file.

8) WAP to print following pattern.

***
**
*
.python
for i in range(4, 0, -1):
    for j in range(0, i-1):
        print(β€œ*”, end= β€˜ ’)
    print(" ")

9) WAP to print distinction, first class, second, third class and fail using if else.

.python
s1=int(input("English:"))
s2=int(input("Hindi:"))
s3=int(input("Marathi:"))
s4=int(input("Maths:"))
s5=int(input("Science:"))
a=(s1+s2+s3+s4+s5)/5
if a>=90:
    print("Distinction")
elif a>=75 and a<90:
    print("First class")
elif a>=45 and a<75:
    print("Second class")
elif a>=35 and a<45:
    print("Third class")
else:
    print("Failed")

Output

English:70
Hindi:80
Marathi:90
Maths:80
Science:70
First class

10) WAP to calculate area of circle and rectangle using method overriding.

.python
class Rec:
    def area(self):
        self. l=4
        self. b=2
        print("Area of rectangle=",self.l*self.b)
class Cir:
    def area(self):
        self. r=3.5
        print("Area of circle=",3.14*self.r*self.r)
r=Rec()
r. area()
c=Cir()
c. area()

Output

Area of rectangle= 8
Area of circle= 38.465

11) Check entered password is correct or not using user defined exception.

.python
class WrongPasswordException(Exception):
  pass
p=input("Enter password:")
try:
  if p!='abc12':
    raise WrongPasswordException
except WrongPasswordException:
  print("Incorrect password!")
else:
  print("Correct password!")

Output

Enter password:abc12
Correct password!

12) Create list and perform following operations.

  1. print elements using for loop
  2. del elements 3,4
  3. del 4 and add 'o','n' 'a'
  4. acces element 'd' from orignal list
  5. find len of list

1.print elements using for loop

.python=
li = ['a','n','a','c',['o','n','d'],'a']
for i in li:
    print(i)

Output

a
n
a
c
['o', 'n', 'd']
a

2. del elements 3,4

3. del 4 and add 'o','n' 'a'

4. acces element 'd' from orignal list

5. find len of list

.python=
li = ['a','n','a','c',['o','n','d'],'a']
print("The length of list is: ", len(li))

Output The length of list is: 6

13) WAP using numpy to generate six random integers between 20-30.

.python=
import numpy as n
a=n.random.randint(20,30,6)
print(a)

Output [24 27 29 25 22 22]

14) WAP to concatenate dictionaries to create new one.

.python
d1={1:10}
d2={2:20}
d3={3:30}
d4={}
for i in d1, d2, d3:
    d4. update(i)
print(d4)

Output {1: 10, 2: 20, 3: 30}

15) WAP to print unique values of following dict.

.python
d={1:10, 2:20, 3:30, 4:30}
d={1:10, 2:20, 3:30, 4:30}
u=set()
for i in d:
    for val in d.values() :
        u. add(val)
print(u)

Output {10, 20, 30}

16) Create 3x4 matrix filled with 10-21.

.python
import numpy as n
a=n.arange(10,22).reshape((3,4))
print(a)

Output

[[10 11 12 13]
 [14 15 16 17]
 [18 19 20 21]]

17) WAP to create class Emp having data members name, salary use constructor to accept values and display information.

.python
class Emp:
    def __init__(self, name, salary):
        self. name=name
        self. salary=salary
    def disp(self):
        print("Name:",self.name)
        print("Salary:",self.salary)
e=Emp("Abc",10000)
e. disp()

Output

Name: Abc
Salary: 10000

Q1 Any FIVE

a. Name different modes of Python.

Python has two basic modes:

  1. Script mode (or Normal mode)
    • The mode where the scripted and finished .py files are in the Python Interpreter.
  2. Interactive mode
    • A command line shell which gives immediate feedback for each statement, while running previously fed statements in active memory.

b. List identity Operators

Operator Description Example
is Returns True if both variables are sames object x is y
is not Returns False if both variables are sames object x is not y

c. Describe Dictionary

d. State use of namespace in Python

e. List different object oriented features supported by Python.

f. Write steps involved in creation of a user defined exception?

g. Describe Python Interpreter

h. List features of Python

Q2 Any THREE

a. Explain two Membership and two logical operators in python with appropriate examples.

Membership Operators

b. Describe any four methods of lists in Python

Output:

['apple', 'banana', 'cherry', 'orange']
['apple', 'cherry', 'orange']
['apple', 'cherry', 'orange']

c. Comparing between local and global variable

Local Global
It is declare inside a function It is declared outside the function
It is created when the function starts execution and lost when the function terminate. It is created before the program's global execution starts and lost when the program terminates.
Local variables can be accessed with the help of statements, inside a function in which they are declared. You can access global variables by any statement in the program.
Parameters passing is required for local variables to access the value in other function. Parameters passing is not necessary for a global variable as it is visible throughout the program

d. Write a Python program to print Fibonacci series up to n terms

Example:

.python
term = int(input("Enter the term: "))

n1, n2 = 0, 1

if term < 0:
	print("Invalid term")
else:
	for i in range(term):
		print(n1)
		nth = n1 + n2
		n1 = n2
		n2 = nth

Output:

Enter the term: 7
0
1
1
2
3
5
8

Q3 Any THREE

a. Write a program to input any two and interchange the tuple variable.

Example:

a = (1, 2, 3, 4, 5)
b = (13, 23, 36, 47, 75)

a,b = b,a

print(a)
print(b)

Output:

(13, 23, 36, 47, 75)
(1, 2, 3, 4, 5)

b. Explain different loops available in python with suitable examples.

while

A while loop executes a target statement as long as given condition is true.

Syntax:

while expression: statement(s)

Example:

.python
count = 0

while(count < 5):
	print(count)
	count += 1

print("over")

Output:

0
1
2
3
4
over

for loop

It has the ability to iterate over the items of any sequence, such as a list or a string.

Syntax:

for iterating in sequence: statements(s)

Example:

.python
fruits = ['banana', 'apple', 'mango']

for fruit in fruits:
	print(fruit)

print("over")

Output:

banana
apple
mango
over

Nested loops

Python programming language allows to use one loop inside another loop.

Syntax:

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

Example:

.python
nums = [1, 2, 3]
words = ["hello", "hi", "bye"]

for num in nums:
	print(num)

	for word in words:
		print(word)

Output:

1
hello
hi
bye
2
hello
hi
bye
3
hello
hi
bye

c. Describe various modes of file object? Explain any two in detail.

There are four different methods modes for opening a file:

In addition, the file should be handled as binary or text mode:

Read a file

The read() method and r mode is used to read files. Before read a file, the file must open using open() function.

text.txt file content:

.txt
Hello World

Program:

.python
f = open("text.txt", "r")
print(f.read())

Output:

Hello world

Write a file

The write() method and a or w modes is used to write files.

Program:

.python
f = open("text.txt", "w")
f.write("Hello World")
f.close()

text.txt file content:

Hello World

d. Illustrate the use of method overriding? Explain with example

If a class inherits a method from its superclass, then there is a chance to override the method provided. Example:

.python
class Parent:
	def echo(self):
		print('I am from Parent class.')

class Child(Parent):
	def echo(self):
		print('I am from Child class.')

p = Parent()
c = Child()

p.echo()
c.echo()

Output:

I am from Parent class.
I am from Child class.

Q4 Any THREE

a. Use of any four methods of tuple in Python?

Example:

.python
t = (12, 45, 43, 8, 35, 12)
print(len(t))
print(max(t))
print(min(t))
print(t1.count(12))

Output:

6
45
8
2

b. Write a python Program to read contents of first.txt and write same content in second.txt file

first.txt file content:

Hello World

Program:

.python
with open('first.txt', 'r') as firstfile, open('second.txt', 'a') as secondfile:

	for line in firstfile:
		secondfile.write(line)

second.txt file content:

Hello world

c. Show how try...except block is used for exception handling in Python with example.

d. Write the output for the following if the variable fruit = "banana"

>>> fruit[:3]
>>> fruit[3:]
>>> fruit[3:3]
>>> fruit[:]

Output:

>>> fruit = "banana"
>>> fruit[:3]
'ban'
>>> fruit[3:]
'ana'
>>> fruit[3:3]
''
>>> fruit[:]
'banana'

Q5 Any TWO

a. Determine various data types available in Python with example.

Numbers

String

List

Tuple

Set

Dictionary

b. Write a python program to calculate factorial of given number using function.

Example:

.python
n = int(input("Enter the number: "))
f = 1

for i in range(1, n + 1):
	f = f * 1

print(f)

Output:

Enter the number: 6
720

c. Show the output for the following:

>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = a + b
>>> print(c)
[1, 2, 3, 4, 5, 6]
>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> t[1:3] = ['x', 'y']
>>> print(t)
['a', 'x', 'y', 'd', 'e', 'f']

Q6 Any TWO

a. Describe Set in python with suitable examples.

Creating a set

Set can be created using curly braces {} or using set() method.

.python
fruits = {'apple', 'banana', 'cherry'}
fruits = set(['apple', 'banana', 'cherry'])

Adding items to the set

Item can added using add() method.

Example:

.python
fruits = {'apple', 'banana', 'cherry'}
fruits.add('orange')
print(fruits)

Output:

{'apple', 'banana', 'cherry', 'orange'}

Removing items from the set

There three methods to remove sets:

Example:

.python
fruits = {'apple', 'banana', 'cherry', 'orange'}
fruits.discard("apple")
fruits.remove("banana")
fruits.pop()
print(fruits)

Output:

{'cherry'}

Comparison of set

Output:

{'apple', 'banana', 'cherry', 'orange', 'pineapple', 'apple'}
{'apple'}
{'banana', 'cherry', 'orange', 'pineapple'}
False
False
True

b. Illustrate class inheritance in Python with an example

Simple Inheritance

In inheritance, the child class acquires the properties and access all the data members and function defined in the parent class.

Illustration:

 ┏━━━━━━━━━━┓
 ┃Base Class┃
 ┗━━━━━━━━━━┛
      ⇑
┏━━━━━━━━━━━━┓
┃Deived Class┃
┗━━━━━━━━━━━━┛

Syntax:

.python
class Base:
	# Body of base class
class Derived(Base):
	# Body of derived class

Example:

.python
class Parent:
	parentname = ""
	childname = ""
	def show_parent(self):
		print(self.parentname)

class Child(Parent):
	def show_child(self):
		print(self.childname)

c = Child()
c.parentname = "Arati"
c.childname = "Purva"
c.show_parent()
c.show_child()

Output:

Arati
Purva

Multiple inheritance

Multiple inheritace means that you're inheriting the property of multiple classes into one.

Illustration:

┏━━━━━━━━━━━━┓┏━━━━━━━━━━━━┓┏━━━━━━━━━━━━┓
┃Base Class 1┃┃Base Class 2┃┃Base Class 3┃
┗━━━━━━━━━━━━┛┗━━━━━━━━━━━━┛┗━━━━━━━━━━━━┛
     ┃              ┃             ┃
     ┗━━━━━━━━━━━━━━╋━━━━━━━━━━━━━┛
              ┏━━━━━━━━━━━━┓
              ┃Deived Class┃
              ┗━━━━━━━━━━━━┛

Syntax:

.python
class A:
	# variable of class A
class B:
	# variable of class B
class C(A, B):
	# variable of class C

Example:

.python
class Parent1:
	def echo(self):
		print("Parent class 1")

class Parent2:
	def echo2(self):
		print("Parent class 2")

class Child(Parent1, Parent2):
	def show(self):
		print("Child class")

c = Child()
c.echo()
c.echo2()
c.show()

Output:

Parent class 1
Parent class 2
Child class

c. Design a class Employee with data members: name, department and salary. Create suitable methods for reading and printing employee information

Example:

.python
class Employee:
	name = ""
	department = ""
	salary = 0

	def setData(self):
		self.name = input("Enter Name: ")
		self.department = input("Enter Department: ")
		self.salary = int(input("Enter Salary: "))

	def showData(self):
		print("Name:", self.name)
		print("Department:", self.department)
		print("Salary:", self.salary)

e = Employee()
e.setData()
e.showData()

Output:

Enter Name: Jonney
Enter Department: Testing
Enter Salary: 20000
Name: Jonney
Department: Testing
Salary: 20000
Table of Content