Python
a) Name different modes of Python.
Python has two basic modes:
- 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
- Lists are mutable.
- The list is better for performing operations.
- Lists consume more memory.
- More likely error will occur.
Tuple
- Tuples are immutable.
- The implication of iterations is faster.
- Tuple consume less memory.
- Less likely error will occur.
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
- Class is a blueprint for the object.
- We define a class by using the keyword class.
Class objects are used to access different attributes.
Object
Classes are the user-defined blueprints that help us create an βobjectβ.
Objects are the instances of a particular class.
Every other element in Python will be an object of some class, such as the string, dictionary, number(10,40), etc.
f) How to give single and multiline comment in python.
Single-Line
Add the hash (#) symbol before the comment:
.python# This is your comment
Multiline
-Python will ignore string literals that are not assigned to a variable, you can add a multiline string (triple quotes) in your code, and place your comment inside it:
.python""" This is a comment written in more than just one line """
g) List different modes of opening file in python.
There are four different methods modes for opening a file:
- r - Read - Opens a file for reading. Error if the file does not exist.
- w - Write - Opens a file for writing. Creates the file if it does not exist.
- x - Create - Creates the specified file. Error if file exist.
- a - Append - Opens a file for appending. Creates the if it does not exist.
In addition, the file should be handled as binary or text mode:
- t - Text - Default value - Text mode.
- b - Binary - Binary mode (e.g. images).
a) Write a program to print following:
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.
len()
- Returns the length of the tuple.max()
- Highest value will returned.min()
- Lowest value be returned.count()
- Returns the number of times a specified value occurs in tuple.
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.
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.
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
- String is a collection of group of characters.
- String are identified as a contiguous set of characters enclosed in single quotes(' ') or double quotes(" ").
String can also can be define with str() function.
Boolean
Boolean represents the two values namely False and True.
The true value is represented true as 1 and false as 0.
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.
- βIndexingβ means referring to an element of an iterable by its position within the iterable.
- βSlicingβ means getting a subset of elements from an iterable based on their indices.
d) Write a program for importing module for addition and substraction of two numbers.
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
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.
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.
txt = "I have {an:.2f} Ruppes!"
print(txt.format(an = 4))
Output:
I have 4.00 Ruppes!
d) Explain building blocks of python.
- The core data structures to learn in Python are List (list), Dictionary (dict), Tuple (tuple), and Set (set).
- To indicate a block of code in Python, you must indent each line of the block by the same amount.
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:
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
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.
overloading is the ability of a function or an operator to behave in different ways based on the parameters that are passed to the function, or the operands that the operator acts on.
.pythonclass A: def __init__(self, a): self.a = a # adding two objects def __add__(self, o): return self.a + o.a ob1 = A(1) ob2 = A(2) ob3 = A("Geeks") ob4 = A("For") print(ob1 + ob2) print(ob3 + ob4)
Write a program to open a file in write mode and some contents at the end of file.
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.
Numpy is a python package which stands for "Numerical Python".
.pythonimport 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.]]
6) Write a program to implement the concept of inheritance in 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.
- When an exception occurs, Python will normally stop and generate an error message.
- These exceptions can be handled using the try statement.
The except block lets you handle the error.
.pythontry: print(x) except NameError: print("Variable x is not defined")
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?
- Easy to learn and use
- Interpreted Language
- Interactive Mode
- Free and Open Source
- Cross Platform/Portable
- OOP Language
5. List any four editors used for Python programming.
- IDEA
- Sublime Text
- Vim
- Notepad++
6. 'Python programming language is interpreted an interactive' comment this sentence.
Python has two basic modes:
- Script mode
- Interactive mode
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
- Python keywords are reserved word with that have special meaning and function.
- Keywords should not be used as variable name, constant, function name, or identifier in the program code.
- Example:
and
,as
,assert
,break
and many more.
13. Write in brief about any five keywords in Python.
True
- is used as the Boolean true value in Python code.False
- is used as the Boolean false value in Python code.break
- is used to break the loop.def
- is used to define the function in Python.while
- is used to make while loop in Python.
15. What is the role of indentation in Python?
- A code block starts with indentation and ends with first unindented line.
- The amount of indention is up to us, but it must be consistent throughout that block.
16. How to comment specific line(s) in Python program?
- Comments are created by beginning a line with hash (#) character.
17. What is variable? What are the rules and conventions for declaring a variables?
- A variable is like a container that stores values that we can access or change.
Example:
.pythonname = "Jone Nuts"
Basic rules to declare variables:
- A variable name must start with a letter or the underscore character
- A variable name cannot start with a number
- A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
- Variable names are case-sensitive (age, Age and AGE are three different variables)
18. What are the various data types available in Python programming.
Numbers
- Number data types store numeric values.
- Python 3 types of number category:
- Integers
- Floating Point Numbers
- Complex Numbers
Integers(int)
- An int data type represents an integer number.
- An integer number is number without any decimal or fractional point.
Floating Point Numbers
- The float data types represents that floating point number.
- The floating point number is number that contains a decimal point.
- Example: 0.1, -3.443
Complex Number
- A complex number is a number that is written in the form of
a+bj
.
Boolean
- Boolean represents the two values namely
False
andTrue
. - The true value is represented true as 1 and false as 0.
String
- String is a collection of group of characters.
- String are identified as a contiguous set of characters enclosed in single quotes(' ') or double quotes(" ").
- String can also can be define with
str()
function.
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
- Number data types store numeric values.
- Python 3 types of number category:
- Integers
- Floating Point Numbers
- Complex Numbers
Integers(int)
- An int data type represents an integer number.
- An integer number is number without any decimal or fractional point.
Floating Point Numbers
- The float data types represents that floating point number.
- The floating point number is number that contains a decimal point.
- Example: 0.1, -3.443
Complex Number
- A complex number is a number that is written in the form of
a+bj
.
20. What is the difference between interactive mode and script mode of Python.
Python has two basic modes:
- Script mode
- Interactive mode
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
- A Python identifier is a name given to a function, class variable, module or other objects that is used in Python program.
- An identifier can a combination of uppercase letters, lowercase letters, underscores, and digits.
- Example:
Name
,myClass
,Emp_Salary
,var_1
,_Address
(ii) Literal
- A literal refers to the fixed value that directly appears in the program.
(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
- Tuple is an ordered sequence of items same as list.
- Tuple is immutable cannot be modified unlike list.
- It is defined within parentheses () where items are separated by commas (,).
Example:
.pythona = (10, 'abc', 32)
(v) List.
- List is an ordered sequence of items.
- In list items separated by commas (,) are enclosed within brackets [].
- List are mutable which means that value of element of a list can be altered by using index.
Example:
.pythonfirst = [10, 20, 30]
23. Explain dictionary data tune in detail
- Dictionary is an unordered collection of key-value pairs.
- Dictionary is collection which is ordered*, changeable and do not allow duplicates.
- Dictionary are written with curly brackets, and have keys and values.
Example:
.pythoncar = { "brand": "Ford", "model": "Mustang", "year": 1264 }
Sets
- Set items are unordered, unchangeable, and do not allow duplicate values.
- Set is defined by values separated by comma inside braces {}.
Example:
.pythona = {5, 2, 3, 1, 4}
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?
- An operator is a symbol which specifies a specifies a specific action.
- Operators are used to perform operations on variables and values.
- In python the operators can be unary operators or binary operator.
Unary Operators
- Unary operators perform mathematical operation only on one operand.
- The example of unary operators are
+
,-
,~
.
Binary Operators
- Binary operators are operators that require two operands to perform any mathematical operation.
- Example of Binary operators are
**
,/
,%
,+
,-
.
2. What is meant by control flow of a program?
- A program's control flow is the order in which the program's code executes.
- The control flow of a Python program is regulated by conditional statements, loops, and function calls.
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?
- There are 4 types of loops available in Python:
while
loopfor
loop- Nested
for
andwhile
loop do..while
loop
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:
if
if-else
nested-if
if-elif-else
12. What are the different nested loops available in Python?
There are two types of nested loop
while
andfor
loop..python# for loop for i in range(1, 5): for j in range(1, (i+1)): print(j, end=' ') print() # while loop i = 1 while i < 5: j = 1 while j < (i+1): print(j, end=' ') j = j + 1 i = i + 1 print()
13. What are the different loop control (manipulation) statements available in Python? Explain with suitable examples.
There three loop control statements available in Python:
break
continue
pass
.pythonfor i in range(1, 11): if i%2 == 0: pass if i%3 == 0; continue if i%4 == 0; break
14. Explain if-else statement with an example.
if
statements executes when the conditions following if is true and it does noting when the conedition isfalse
.The
if-else
statement takes care of atrue
as well asfalse
condition..pythoni = 20 if (i < 15): print("i is less then 15") else: print("i is greater then 15")
15. Explain continue statement with an example.
The continue statement in Python returns the control to the beginning of the while loop.
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.
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?
=
- if the values of operands are equal, then the condition becomes true.is
- return true, if the variables on either side of the operator point to same object.
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.
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.
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?
- A data structure is specialized format for organizing and storing data, so that various operations can be performed on it easily.
- Python use data structure like list, tuple, dictionary.
2. How to define and access the elements of list?
- A list is created by placing all the items inside a square brackets [], separated by commas.
Example of define the list:
.pythonli = ["Hello", 50]
To access values in lists, use the square brackets for slicing along with the index or indices to obtain value available at that index.
.pythonli = ["Hello", 50] print(li[1])
O/P
50
3. What is list? How to create list?
- List are used to store multiple items in single variable.
- List are created using square brackets.
Example:
.pythonli = ["Hello" , 50]
4. What are the different operation that can be performed on a list? Explain with examples
append()
- is used to add elements at the end of the list.extend()
- is used to add more then one element at the end of the list.insert()
- can add an element at a given position in the list.remove()
- is used to remove an element form the list.pop()
- can remove an element from any position in the list.reverse()
- is used to reverse the element of the list.len()
- returns the length of the list.min()
- returns the minimum value in the list.max()
- returns the maximum value in the list.count()
- returns the number of occurrence of given element in the list.index()
- returns the position of the first occurrence.sort()
- sorts the list.clear()
- erases all the elements.- slice - is used to print a section of the list.
- concatenate - is used to merge two lists and return a single list.
multiply - the list n times. Example:
.pythonli = ["Hello", "World"] li.append("Bye") li.extend(["World", "Forever"]) li.insert(0, "Bye") li.remove("World") li.pop(0) li.reverse() len(li) max(li) li.count("o") li.index("Forever") li.sort() li.clear()
O/P
['Hello', 'World'] ['Hello', 'World', 'Bye'] ['Hello', 'World', 'Bye', 'World', 'Forever'] ['Bye', 'Hello', 'World', 'Bye', 'World', 'Forever'] ['Bye', 'Hello', 'Bye', 'World', 'Forever'] ['Hello', 'Bye', 'World', 'Forever'] ['Forever', 'World', 'Bye', 'Hello'] 4 World 0 0 ['Bye', 'Forever', 'Hello', 'World'] []
5. Explain any two methods under lists in Python with examples.
append()
- Is used to add elements at the end of the list.
Syntax:
.pythonlist.append(item)
Example:
.pythonli = ["Hello", 30] li.append("World") print(li)
O/P
["Hello", 30, "World"]
extend()
- Is used to add more then one element at the end of the list.
Syntax:
.pythonlist.extend(list2)
Example:
.pythonli = ["Hello", "World"] li2 = ["What's", "Up"] li.extend(li2) print(li)
O/P
["Hello", "World", "What's", "Up"]
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.
li = ["Hello", "World"]
li.remove("Hello")
print(li)
O/P
World
7. What is tuple in Python? How to create and access it?
- Tuple is an ordered sequence of items same as list.
- Tuple is immutable cannot be modified unlike list.
- It is defined within parentheses () where items are separated by commas (,).
- To access values in tuple, use the square brackets[].
Example:
.pythona = (10, 'abc', 32) print(a[0])
O/P
10
8. What are mutable and immutable types?
- Mutable - is when something is changeable or has the ability to change.
- Immutable - when no change is possible over time.
9. Is tuple mutable? Demonstrate any two methods of tuple.
- Tuple is immutable that means it can't be changed or replace.
max()
- Returns item from the tuple with max value.min()
Return item from the tuple with min value..pythona = (10, 32, 3) max(a) min(a)
O/P
10 3
10. Write in brief about Tuple in Python. Write operations with suitable examples
- Tuple is an ordered sequence of items same as list.
- Tuple is immutable cannot be modified unlike list.
- It is defined within parentheses () where items are separated by commas (,).
- To access values in tuple, use the square brackets[].
Tuple Operations
- We can use + operator to combine two tuples.
- We can also repeat elements by using the * operator.
- We can test if an item exist in tuple or not.
Iteration over a tuple specifies the way.
.pythont1 = (1, 2) t2 = (3, 4) print(t1 + t2) print(t1 * 2) print(1 in t1) for t in t1: print(t)
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.
- Set items are unordered, unchangeable, and do not allow duplicate values.
- Set is defined by values separated by comma inside braces {}.
To access values in set, use the square brackets[].
.pythona = {5, 2, 3, 1, 4} a[1]
12. Explain the properties of dictionary keys.
- Dictionary values have no restrictions.
- They can be any arbitrary Python object, either standard objects or user-defined objects.
- However, same is not true for the keys, more then one entry per key not allowed.
13. Explain directory methods in Python.
clear()
- removes all the elements from the dictionary.copy()
- returns a copy of the dictionary.fromkeys()
- thefromkeys()
method creates a new dictionary with default value or all specified keys.gets()
- returns the value of the specified key.item()
- returns a list containing a tuple for each key value pair.keys()
- returns a list containing the dictionary's keys.pop()
- removes the element with the specified key.popitem()
- removes the last inserted key-value pair.setdefault()
- returns the value of the specified key.update()
- Updates the dictionary with the specified key.values()
- returns a list of all the values in the dictionary.
14. How to create directory in Python? Give example.
Dictionary are written with curly brackets, and have keys and values.
.pythond = { "name": "Jone", "age": 30 } print(d)
O/P
{ "name": "Jone", "age": 30 }
15. Write in brief about Dictionary in Python. Write operation with suitable examples.
- Dictionary is an unordered collection of key-value pairs.
- Dictionary is collection which is ordered*, changeable and do not allow duplicates.
- Dictionary are written with curly brackets, and have keys and values.
Example:
.pythoncar = { "brand": "Ford", "model": "Mustang", "year": 1264 }
Operation of Dictionary
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
- List is collection of index values pairs.
- List is created by placing elements in [] separated by commas ",".
- We can access the elements using the index value.
- List are mutable.
- List is created using
list()
function.
Dictionary
- Dictionary is collection of key-value pairs.
- All key-value go inside brackets{} separated by a comma.
- The keys in dictionary are of any given data type.
- We can access the elements using the keys.
- Dictionaries are mutable, but keys don't allow duplicates.
- Dictionary object is created using
dict()
function.
17. Compare List and Tuple.
List
- Lists are mutable.
- The list is better for performing operations.
- Lists consume more memory.
- More likely error will occur.
Tuple
- Tuples are immutable.
- The implication of iterations is faster.
- Tuple consume less memory.
- Less likely error will occur.
19. How append() and extend() are different with reference to list in Python?
append()
- Append uses
.append()
to add element at end of the list. Syntax:
.pythonlist.append("hello")
Example:
.pythonli = ["hello", "world"] li.append("bye") print(li)
O/P
["hello", "world", "bye"]
extend()
- Extend uses
.extend()
to add multiple elements to the list. Syntax:
.pythonlist.extend(["hello", "world"])
Example:
.pythonli = ["hello", "world"] li.extend(["bye", "world"] print(li)
O/P
["hello", "world", "bye", "world"]
20. Write a program to input any two tuples and interchange the tuple variable.
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}
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.
- String is a collection of group of characters.
- String are identified as a contiguous set of characters enclosed in single quotes(' ') or double quotes(" ").
String can also can be define with
str()
function..pythons1 = "Hello World" print(s1[0]) # String indices and accessing string print("Hello" in s1) # 'in' and 'not in' operator print(s1[1:]) # String slicing print(s1>"Hello") # String comparison
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.
- File is a named location on disk to store related information.
- It is used to permanently store data in a volatile memory.
- Files are divided into following two categories:
- Text Files
- Binary files
Text Files
- Text files are simple texts in human readable format.
- A text file is structured as sequence of lines of text.
Binary Files
- Binary files have binary data which is understood by the computer.
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.
- Python provides a Exception handling for handling any unreported errors in program.
- By handling the exception, we can provide a meaning full message to the user about the problem.
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.
Syntax:
.pythonf = open("filename", "modes")
Example:
.pythono = open("text.txt", "w") o.write("Hello World") o.close() o = open("text.txt", "r") print(o.read()) o.close()
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.
- Exception handling for handling any unreported errors in program.
By handling the exception, we can provide a meaningful message to the user about the problem rather then system generated error message.
.pythonage = int(input("Enter your age: ")) try: if age < 18: raise Exception; except Exception: print("You are not 18")
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.
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.
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.
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.
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.
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.
def sum(*x):
n=0
for i in x:
n+=i
print(n)
sum(1, 2,3,4,5)
Output
15
fibonacci.py
def fib(n):
n1, n2= 0,1
for i in range(n):
print(n1)
nth=n1+n2
n1=n2
n2=nth
fib.py
import fibonacci
print(fibonacci.fib(5))
To run the code, run fib.py
file.
8) WAP to print following pattern.
***
**
*
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.
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.
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.
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.
- print elements using for loop
- del elements 3,4
- del 4 and add 'o','n' 'a'
- acces element 'd' from orignal list
- find len of list
1.print elements using for loop
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
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.
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.
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.
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.
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.
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:
- 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. Describe Dictionary
- A dictionary is collection which is unordered, changeable and indexed.
- Dictionaries are written with curl brackets, and they have keys and values.
Example:
.pythoncompany = { "name": "Apple", "product": "IPhone" "model": "11" }
d. State use of namespace in Python
- A namespace is a simple system to control the names in a program.
- Python implements namespaces in the form of dictionaries.
- It maintains a name-to-object mapping where names act as keys and the objects as values.
e. List different object oriented features supported by Python.
- Python OPP Concepts
- Object
- Class
- Method
- Inheritance
- Polymorphism
- Data Abstraction
- Encapsulation
f. Write steps involved in creation of a user defined exception?
- Exception can be define by creating a new class.
- This exception class has to be derived, either directly or indirectly, from the built-in
Exception
. - When the programmer suspects the possibility of exception, he should raise his
own exception using
raise
. - The programmer can insert the code inside a
try
block. - Catch the exception using
except
block. Example:
.pythonclass Error(Exception): print("Value can't be 0.") number = 0 try: if number == 0: raise Error else: print("Value is more then 0.") except Error: pass
Output:
Value can't be 0.
g. Describe Python Interpreter
- Python interpreter converts the code written in Python language by users to language which computer hardware or system can understand.
- Python interpreter is a bytecode interpreter, its input is instruction set sets called bytecode.
h. List features of Python
- Easy to code
- High Level programming language
- Object-Oriented Language
- Portable language
- Use interpreter
- GUI Support
Q2 Any THREE
a. Explain two Membership and two logical operators in python with appropriate examples.
Membership Operators
- Membership operators are used to test whether a value is found within a sequence.
Example of
in
:.pythonx = 4 y = 8 list = [1, 2, 3, 4, 5] if (x in list): print("X is in list array") else: print("X is not in list array")
Output:
X is in list array
Example of
not in
:.pythonif (y not in list): print("Y is not in list array") else: print("Y is in list array")
Output:
Y is not in list array
Logical Operators
Logical operators are usedto perform locical operations on the values of variables. The value is either
true
orfalse
Example of
and
,or
andnot
..pythona = 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)
a and b is False a or b is True a not b is False
b. Describe any four methods of lists in Python
append()
- Adds an element at the end of the list.pop()
- Removes the element at the specified position.sort()
- Sorts the listclear()
- Removes all the elements from the list. Example:.pythonfruits = ['apple', 'banana', 'cherry'] fruits.append("orange") print(fruits) fruits.pop(1) print(fruits) fruits.sort() print(fruits) fruits.clear() print(fruits)
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:
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:
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:
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:
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:
- r - Read - Opens a file for reading. Error if the file does not exist.
- w - Write - Opens a file for writing. Creates the file if it does not exist.
- x - Create - Creates the specified file. Error if file exist.
- a - Append - Opens a file for appending. Creates the if it does not exist.
In addition, the file should be handled as binary or text mode:
- t - Text - Default value - Text mode.
- b - Binary - Binary mode (e.g. images).
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:
Hello World
Program:
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:
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:
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?
len()
- Returns the length of the tuple.max()
- Highest value will returned.min()
- Lowest value be returned.count()
- Returns the number of times a specified value occurs in tuple.
Example:
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:
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.
- When an exception occurs, Python will normally stop and generate an error message.
- These exceptions can be handled using the
try
statement. - The
except
block lets you handle the error. Syntax:
.pythontry: # Code except: # Code
Example:
.pythontry: print(x) except NameError: print("Variable x is not defined")
Output:
Variable x is not defined.
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
int
,float
and complex numbers fall under numbers category.Example:
.pythona = 5 a = 2.0 a = 1+2j
String
- String is sequence of Unicode characters.
- We can use single quotes or double quotes to represent strings.
- Multi-line string can be denoted using triple quotes
'''
or"""
. Example:
.pythons = "This is string" s = ''' A multi line string '''
List
- List is an ordered sequence of items.
- It is one of the most used datatype in Python.
- List is very flexible.
- All the items in a list don not need to be the same type.
Example:
.pythona = [1, 2.2, 'python']
Tuple
- Tuple is an ordered sequence of items same as a list.
- The only difference is that tuples are immutable.
- Tuples once created cannot be modified.
Example:
.pythont = (5, 'program', 1+3j)
Set
- Set is an unordered collection of unique items.
- Set is defined by values separated by comma inside braces { }.
- Items in a set are not ordered
Example:
.pythona = {5,2,3,1,4}
Dictionary
- Dictionary is an unordered collection of key-value pairs.
- It is generally used when we have a huge amount of data.
- Dictionaries are defined within braces
{}
. Example:
.pythond = {1:'value','key':2}
b. Write a python program to calculate factorial of given number using function.
Example:
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.
fruits = {'apple', 'banana', 'cherry'}
fruits = set(['apple', 'banana', 'cherry'])
Adding items to the set
Item can added using add()
method.
Example:
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:
discard()
- removes given items from set.remove()
- removes given item from set. If item is not avaliable it will give error.pop()
- removes list item from the set.
Example:
fruits = {'apple', 'banana', 'cherry', 'orange'}
fruits.discard("apple")
fruits.remove("banana")
fruits.pop()
print(fruits)
Output:
{'cherry'}
Comparison of set
|
- shows the union of two set.&
- shows the intersection of two set.-
- shows the difference of two set.<
,>
,<=
,>=
,==
- comparison operators can also be use in set..pythonfruits = {'apple', 'banana', 'cherry'} fruits2 = {'orange', 'pineapple', 'apple'} print(fruits|fruits2) print(fruits&fruits2) print(fruits-fruits2) print(fruits>fruits2) print(fruits<fruits2) print(fruits==fruits2)
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:
class Base:
# Body of base class
class Derived(Base):
# Body of derived class
Example:
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:
class A:
# variable of class A
class B:
# variable of class B
class C(A, B):
# variable of class C
Example:
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:
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