0% found this document useful (0 votes)
3 views

Python Unit 2

The document contains lecture notes on Python programming, covering various topics such as string methods, data structures (lists, tuples, dictionaries, sets), exception handling, and object-oriented programming concepts. It includes definitions, code examples, and explanations of key functions and features in Python. The notes are prepared by multiple authors and serve as a study guide for students in the Computer Science and Engineering department.

Uploaded by

amalamargret.cse
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Python Unit 2

The document contains lecture notes on Python programming, covering various topics such as string methods, data structures (lists, tuples, dictionaries, sets), exception handling, and object-oriented programming concepts. It includes definitions, code examples, and explanations of key functions and features in Python. The notes are prepared by multiple authors and serve as a study guide for students in the Computer Science and Engineering department.

Uploaded by

amalamargret.cse
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

Programming in Python (U23ADTC01)

Lecture Notes
Unit II
Prepared By:
Dr. M. Shanmugam
Mr. D. Rajesh.
Mrs. S. Deeba
Mrs. M. Hemalatha
Ms. A. Amala Margret

Verified By Approved By
---------------------------------------------------------------------------------------------------------------------
2 marks Questions and Answers

1. Differentiate the split() and join() methods in Python strings.


The split() method in Python is used to split a string into a list of substrings based on a
specified separator.
Conversely, the join() method is used to concatenate a sequence of strings with a
specified separator.

2. Write a Python program to count the occurrences of a particular character in a given


string.
string = "hello world"
char = "o"
print(string.count(char))
# Output: 2

3. How can you check if a string contains only numeric characters in Python?
isdigit() method is used to check if a string contains only numeric characters. This
method returns True if all characters in the string are digits, otherwise False.

4. Differentiate tuples and lists in Python.


Tuples are immutable sequences, meaning their elements cannot be changed once they
are defined, whereas lists are mutable. Tuples are defined using parentheses (), while lists are
defined using square brackets [].

5. Write a Python program to concatenate two tuples.


tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
print(tuple1 + tuple2)
# Output: (1, 2, 3, 4, 5, 6)

Department of Computer Science and Engineering


Programming in Python (U23ADTC01)

6. How can you unpack a tuple in Python?


To unpack a tuple in Python, we can assign its elements to multiple variables
simultaneously. For example:
tuple1 = (1, 2, 3)
a, b, c = tuple1

7. How do you add a new key-value pair to a dictionary in Python?


A new key-value pair can be added to a dictionary by simply assigning a value to a new
key, like this: my_dict[new_key] = value.

8. Write a Python program to iterate over a dictionary and print keys and their
corresponding values.
my_dict = {'a': 1, 'b': 2, 'c': 3}
for key, value in dictionary.items():
print(key, ":", value)

9. How do you remove an element from a set in Python?


An element can be removed from a set using the remove() or discard() method. The
remove() method raises a KeyError if the element is not present, while the discard() method does
not.

10. Write a Python program to perform set intersection.


set1 = {1, 2, 3}
set2 = {2, 3, 4}
print(set1.intersection(set2))
# Output: {2, 3}

11. Differentiate between sets and lists in Python.


Sets are unordered collections of unique elements, meaning they do not allow duplicate
values. Lists, however, are ordered collections that can contain duplicate elements.

12. Write about the keys() method in Python dictionaries.


The keys() method in Python dictionaries returns a view object that displays a list of all
the keys in the dictionary.

13. Write a Python program to create a class named Car with attributes make and model.
class Car:
def __init__(self, make, model):
self.make = make
self.model = model

# Example usage
car1 = Car("Toyota", "Corolla")
print(car1.make, car1.model)
# Output: Toyota Corolla

Department of Computer Science and Engineering


Programming in Python (U23ADTC01)

14. Write about the Encapsulation in object-oriented programming.


Encapsulation is the bundling of data and methods that operate on the data into a single
unit (class). It hides the internal state of an object and only exposes the necessary functionalities
through methods.

15. Define Dictionary?


* Dictionary are used to store data values in key value pairs.
*A Dictionary is a collection which is ordered changeable and do not allow
duplicate.
Example:
Dict={1:’Greeks’ 2:’for’}
Print(Dict)

16. Is Dictionary mutable or immutable? How?


* Dictionaries are mutable.
* Because you can change their content after they are created . We can add,
remove or modify key value pair within a dictionary.

17. Take a Dictionary and add a new element into it ?


#program
my_dictionary={“apple”: “a fruit that grows on tree”, “banana”: “a long curved fruit that
grows in clusters.”}
my_dictionary[“grape”]=”A small,sweet fruit that grows in bunches.”
Print(my_dictionary)

18. Take dictionary and delete an element and delete the dictionary?
#program
my_dictionary ={“apple”: “a fruit that grows on tree”, “banana”: “a long curved
fruit that grows in clusters.”}
del my_dictionary[“banana”]
Print(“dictionary after deleting banana”,my_dictionary)
del my_dictionary #If you print the delted dictionary it will return a name error.

18. Can the keys of a dictionary be duplicate ? Justify.


No, in python the keys of a dictionary must be unique .if you try to assign a value to a key
that already exists in the dictionary, it will overwrite the existing value associated with that key .

19. Write a program in python to get 5 elements from using and add into a dictionary ?
my_dictionay={}
for _in range(5):
key=input(“Enter a key:”)
Value=input(“Enter a value”)
my_dictionary[key]=value
Print(“dictionary:”,my_dictionary)

Department of Computer Science and Engineering


Programming in Python (U23ADTC01)

20. What is the use of update() function in dictionary()?


* in python the update() function is used to update or merge the contents of one
dictionary with another dictionary or with an iterable of key value pairs.
* theupdate() function provide a flexible and efficient way to modify the content of a
dictionary, making it a valuable tool in python dictionary.

21. Define Exception?


An exception is something that is left out or not done on purpose. An exception to a rule
does not follow that rule. This word is used for all sorts of things that are not usual or usually
allowed.Exceptions are used to handle unexpected situations that may arise during the program's
runtime. They allow developers to gracefully manage errors and prevent programs from
crashing.

22. What are the various blocks in Exception handling in python ?


In Python, the various blocks used in exception handling are:
1. try: This block contains the code that might raise an exception.
2. except: This block is used to handle specific exceptions that occur in the try block.
3. else: This block is executed if no exceptions are raised in the try block.
4. finally: This block is always executed, regardless of whether an exception occurred
or not, and is typically used for cleanup actions (e.g., closing files or releasing
resources).

23. What is the use of else block in Exception handling?


• The else block in exception handling in Python is used to execute code that should run
only if no exceptions were raised in the corresponding try block.
• It allows you to separate the code that may raise exceptions from the code that should
execute if everything in the try block runs successfully without any errors.

24. Can we have multiple except blocks? how?


Yes, we can have multiple except blocks in Python. Each except block can handle a
specific type of exception or multiple types of exceptions using tuple syntax.This method allows
you to handle different exception types in different ways, making it ideal when you need to
perform specific actions for each type of exception.

25. Can we raise the built-exception? how?


User code can raise built-in exceptions. This can be used to test an exception handler or
to report an error condition “just like” the situation in which the interpreter raises the same
exception; but beware that there is nothing to prevent user code from raising an inappropriate
error.
Syntax:
raise ExceptionType("Error message")

26. How will you create your own exception?

Department of Computer Science and Engineering


Programming in Python (U23ADTC01)

In order to create a custom exception, we need to extend the Exception class that belongs
to java. lang package.To create your own exception in Python, you can define a new class that
inherits from the built-in Exception class.
Syntax:
class CustomError(Exception)
...
pass
try:
...
except CustomError:
...

27. Differentiate between List and the tuple.

LIST TUPLES
• Lists are mutable. • Tuples are immutable.
• List are enclosed within square • Tuples are enclosed within parenthesis ().
brackets [ ]. Lists • The implication of iterations is
• The implication of iterations is comparatively Faster.
Time-consuming. • A tuple data type is appropriate for
• The list is better for performing accessing the elements.
operations, such as insertion • Tuple consumes less memory.
and deletion. • Tuple does not have many build-in
• List consumes more memory. methods.
• List have several build-in • Example for Tuples:(10,30,6)
methods.
• Example for List: [10,30,50]

28. How will you traverse a tuple using for loop?


We can use a for loop to iterate through the tuple with an index.
EXAMPLE:
my_tuple=(1,2,3,4,5)
for i in range(len(my_tuple))
print(my_tuple[i])
29. Write a python program to convert a string into a tuple of words.
def string_to_tuple(string):
words = string.split()
word_tuple = tuple(words)
return word_tuple
input_string="Welcome to learn python programming"
result_tuple=string_to_tuple(input_string)
print("String:",input_string)
print("Tuple:",result_tuple)

30. Can we delete an element from a tuple? Why?

Department of Computer Science and Engineering


Programming in Python (U23ADTC01)

No, we can’t delete an element from the tuple because it is an immutable.

31. How will you find a max and min element from a tuple?
We can find the maximum and minimum elements from a tuple using the max() and
min() functions in Python.
PROGRAM
my_tuple= (3, 7, 1, 9, 5)
max_element = max(my_tuple)
min_element = min(my_tuple)
print("Maximum element:", max_element)
print("Minimum element:", min_element)
Output:
Maximum element: 9
Minimum element: 1

32. What is a string?


String is a data type in python to handle array of characters that may be a combination of
letters,numbers,or special symbols enclosed within single,double or even triple quotes. They are
immutable.

33. Write about the indexing and slicing on string.


Indexing:
Indexing refers to accessing individual characters within a string by their position. In
Python, strings are zero-indexed, meaning the first character is at index 0, the second character is
at index 1, and so on. Negative indices count from the end of the string, with -1 representing the
last character, -2 representing the second to last character, and so forth.
Slicing:
Slicing allows you to extract a substring from a string by specifying a range of indices.
The syntax for slicing:
[start_index:end_index:step].

34. Can we concatenate two strings in python? How?


Yes , we can concatenate string in python by using the + operator,
str1= ”Python”
str2= ”Programming”
str3=str1+str2
print(str3)

35. Apply membership operators on strings.


Membership operators in Python (in and not in) are used to test whether a value exists
within a sequence (like a string, list, tuple, etc.). When applied to strings, they check for the
presence or absence of substrings within the string.

Eg:

Department of Computer Science and Engineering


Programming in Python (U23ADTC01)

My_string = “Hello, World!”


print(“Hello” in my_string) # Output: True
print(“Python” in my_string) # Output: False
print(“Java” not in my_string) # Output: True
print(“World” not in my_string)
# Output: False

36. Write any five '%' operators and their meaning:


1. %d: Used for formatting integers.
2. %f: Used for formatting floating-point numbers.
3. %s: Used for formatting strings.
4. %x: Used for formatting integers as hexadecimal numbers.
5. %c: Used for formatting characters.
For example:
Age = 25
Name = “John”
Print(“My name is %s and I am %d years old.” % (name, age))

37. Diff between index() and find() function in python strings

index() find()
• Returns an exception if substring • Returns -1 if substring isn’t
isn’t found found.
• It shouldn’t be used if you are not • It is the correct function to use
sure about the presence of the when you are not sure about
substring. the presence of a substring.
• This can be applied to strings, lists • This can only be applied to
and tuples. strings.
• It cannot be used with conditional • It can be used with conditional
statement statement to execute a
statement if a substring is
found as well if it is not.

38. What is the use of swapcase() function in python strings.


The swapcase() function in Python strings is used to swap the case of each character in the
string. It converts uppercase characters to lowercase and lowercase characters to uppercase.
For example:
String = “Hello World”
Swapped_string = string.swapcase()
Print(swapped_string)
# Output: hELLOwORLD

39. What are the features of Object Oriented Progamming?

Department of Computer Science and Engineering


Programming in Python (U23ADTC01)

• Classes and Objects


• Encapsulation
• Inheritance
• Polymorphism
• Abstraction

40. Define a class.


A class is a user-defined data type that contains both the data itself and the methods that
may be used to manipulate it. Classes serve as a template to create objects.
They provide the characteristics and operations that the objects will employ.
Syntax
class ClassName:
#statement_suite

41. What is an object?


An object in programming refers to a concrete instance of a class, embodying both the
data structure and the behavior defined by the class.
Objects are created based on the blueprint provided by the class, and they can interact
with each other and perform tasks according to the methods defined within the class.
Syntax:
object_name = ClassName()

42. Which is important either class or object? why?


Both classes and objects are important in object-oriented programming:
• Class: Provide blueprints for creating objects, encapsulate data and behavior.
• Object: Instances of classes, represent tangible entities with unique characteristics,
facilitate interaction and functionality in a program.

43. Differentiate class variable and instance variable.

Parameter Class variables Instance variables


Class variables are Instance variables are
defined within the class defined within class
Definition
but outside of any class methods, typically the
methods. constructor.
Changes made to the Changes made to the
Scope class variable affect all instance variable does not
instances. affect all instances.
Class variables can be Instance variables are
initialized either inside typically initialized in the
Initialization the class definition or constructor of the class.
outside the class
definition.
Class variables are Instance variables are
Access accessed using the class accessed using the
name, followed by the instance name, followed

Department of Computer Science and Engineering


Programming in Python (U23ADTC01)

variable name. by the variable name.

44. What is a constructor? Write about the feature of the constructor in python.
A constructor is a special method in object-oriented programming that is
automatically called when an object of a class is created.
• Automatic Invocation: The init constructor method in Python is
automatically called when an object of the class is created, eliminating the
need for explicit invocation.
• Attribute Initialization: Python's constructor allows for the initialization of
object attributes, providing a convenient means to set initial values for object
properties during object creation.

45. What is 'self' keyword used for?


The 'self' keyword in Python:
• References the current instance of the class.
• Enables access to instance variables and methods within the class scope.
class MyClass:
def my_method(self):
# Access instance variables using self
self.attribute = value
# Call other methods of the same object using self
self.another_method()

46. Differentiate getter and setter methods with ordinary member methods.

getter() setter()
Getters are the methods that are used in The setter is a method that is used to set
Object-Oriented Programming (OOPS) the property's value
to access a class's private attributes.
The setattr() function in Python It is very useful in object-oriented
corresponds to the getattr() function in programming to set the value of private
Python. It alters an object's attributes in a class.
attribute values.

47. Can we overload a method in python? How?


Python does not support method overloading by default. This means that you
cannot have two methods with the same name in the same class that take different numbers or
types of parameters. However, there are a few ways to achieve the desired behavior of method
overloading in Python. One way is to use default argument values

48. Define - Inheritance.

Department of Computer Science and Engineering


Programming in Python (U23ADTC01)

• Inheritance in python programming is the concept of deriving a new class from an


existing class.
• Using the concept of inheritance we can inherit the properties of the existing class to our
new class.
• The new derived class is called the child class and the existing class is called
the parent class.
Syntax:
Class BaseClass:
{Body}
Class DerivedClass(BaseClass):
{Body}

49. What are the types of inheritances?


There are five types of inheritances
• Single Inheritance
• Multiple Inheritance
• Multilevel Inheritance
• Hierarchical Inheritance
• Hybrid Inheritance

50. Differentiate a class from an abstract class.

CLASS ABSTRACT CLASS


A class is a blueprint for creating objects An abstract class is a class that cannot be
that encapsulates data for the object and instantiated on its own and typically
methods to operate on that data. contains one or more abstract methods. It
is meant to be subclassed, providing a
common interface for its subclasses.
Objects can be directly instantiated from a Abstract classes cannot be instantiated
class using the new keyword. directly; they serve as templates for other
classes to inherit from.
A class may or may not have abstract An abstract class often contains one or
methods. All methods can have more abstract methods, which are declared
implementations. but not implemented in the abstract class.
These methods must be implemented by
concrete subclasses.

51. Write about the Regular expressions in python.


• A RegEx, or Regular Expression, is a sequence of characters that forms a search pattern.
• RegEx can be used to check if a string contains the specified search pattern.
Eg:
import re
txt = "The rain in Spain"
x = re.search("^The.*Spain$", txt)

Department of Computer Science and Engineering


Programming in Python (U23ADTC01)

52. What are the speciality of the sets in python?


• Sets in Python are unordered collections of unique elements.
• They are mutable, meaning you can add or remove elements from a set.
• Sets are iterable, allowing you to iterate over the elements.
• Sets support various mathematical operations like union, intersection, difference, and
symmetric difference.
• Sets are implemented using hash tables, which make membership testing and
insertion/deletion operations very efficient.

53. How will you create a set in python?


Sets can be created using curly braces {} or the set() constructor.
For example:
my_set = {1, 2, 3} # Using curly braces
(OR)
my_set = set([1, 2, 3]) # Using set() constructor
print(my_set) #Output : {1,2,3)

54. Differentiate add() and update() functions in set.

S. No Add() Update()
Use add() function to add a single use update() function to add multiple
1 element. elements to the set.

2 add() is faster than update(). Update() is slower than add().


add () accepts immutable Whereas update() accepts iterable
3 parameters only sequences

4 add() accepts a single parameter update() can accept multiple sequences

55. Differentiate remove() and discard() function in set.


• The remove() method removes the specified element from the set. This method is
different from the discard() method because the remove() method will raise an error if the
specified item does not exist, and the discard() method will not.
• In Python, the discard() function removes a specified element from a Set. The remove()
in python also removes an element from a set.
• However, there is a difference between remove() and discard(). When the specified
element does not exist in the given set, the remove() function raises an error.

56. What is meant by symmetric difference?


Python Set symmetric_difference() method is used to get the elements present in either of
the two sets, but not common to both sets. In this article, we are going to learn about the Python
Set symmetric_difference() function.

Example:

Department of Computer Science and Engineering


Programming in Python (U23ADTC01)

Input: set_A = {1, 2, 3, 4, 5}, set_B = {6, 7, 3, 9, 4}


Output: {1, 2, 5, 6, 7, 9}
Explanation: Output is the set of numbers that are present in either of the sets but not in
both the sets.

57. Write about subset and superset in set.


• Set A is a subset of a set B if each element of the set A belongs to set B as well.
• Set A is a superset of a set B if set A contains all elements of set B (but it may also
contain other elements).
Example 1:
We can use issubset() to find out if all Kate’s movies are also included in Alan’s
favorites:
Alan_fav_movies = {‘A Star Is Born’, ‘Halloween’, ‘Harry Potter’, ‘Hocus Pocus’, ‘The
Lion King’}
Kate_fav_movies.issubset(alan_fav_movies)
This returns True because this list of Alan’s favorite movies contains all of Kate’s
favorite movies.
Example 2:
So, is the reverse true? Are Alan’s movies the superset for Kate’s? Let’s find out:
Kate_fav_movies = {‘Halloween’, ‘A Star Is Born’, ‘Hocus Pocus’}
Alan_fav_movies = {‘A Star Is Born’, ‘Halloween’, ‘Harry Potter’, ‘Hocus Pocus’, ‘The
Lion King’}
Alan_fav_movies.issuperset(kate_fav_movies)

58. What is meant by frozen set in python?


Frozen set is just an immutable version of a Python set object. While elements of a set can
be modified at any time, elements of the frozen set remain the same after creation.
• The syntax of frozenset() function is:
Frozenset([iterable])
• The frozenset() function takes a single parameter:
Iterable (Optional) – the iterable which contains elements to infrozen setthe frozenset
with.
Iterable can be set, dictionary, tuple, etc.
• The frozenset() function returns an immutable frozenset initialized with elements from
the given iterable.
If no parameter functions passed, it returns Python frozenset.

Department of Computer Science and Engineering


Programming in Python (U23ADTC01)

5 MARKS
1. Program to get the values for dictionary and print the elements one by one.
#program
my_dictionary={ ‘a’: 1, ‘b’: 2, ‘c’: 3, ‘d’:4, }
for value in my_dict.values():
print(value)
Output:
1
2
3
4
2. Program to print the word count using dictionary?
Sentence=”my name is Praveen i am a good boy.”
Words=sentence.split()
Word_count={}
For word in words:
Word_count[word]=word_count.get(word,0)+1
For word_count in word_count.items():
print(f“ ‘{word}’ occurs {count} time(s).”)

3. Program to print the character count using dictionary?


my_string=”hello,world”
Char-count={}
for char in my_string:
Char_count[char] =char_count.get(char,0)+1
for char , count in char_count.items():
Print(f “ ‘{char}’ occurs{count} time(s).”}
Output
‘h’ occurs 1 time(s).
‘e’ occurs 1 time(s).
‘l’ occurs 3 time(s).
‘o’ occurs 2 time(s).
‘,’ occurs 1 time(s).
‘W’ occurs 1 time(s).
‘r’ occurs 1 time(s).
‘d’ occurs 1 time(s).

4. Explain the Try block and Except block with example ?


A try and except block is used for error handling in Python.
• Try: Helps to test the code. If the code inside the try block is error free it is executed.
Otherwise the error gets caught and control goes to the except block.
• Except: Except displays the error message.
• Else: Executes if there is no error in the code in the try block.
• Finally: Executes independently of the try-except block results.

Department of Computer Science and Engineering


Programming in Python (U23ADTC01)

The Else and Finally block are optional but it is considered a good programming practice to
include them.
Type of error messages
There are two types of error that can occur:
• Syntax Error/Parsing Error: When the Python parser is unable to understand a line of
code.
• Exception: When the error is detected during execution, e.g.,ZeroDivisionError.
Some of the common Exception Errors are:
• IOError: if the file can’t be opened
• KeyboardInterrupt: when an unrequired key is pressed by the user
• ValueError: when the built-in function receives a wrong argument
• EOFError: if End-Of-File is hit without reading any data
• ImportError: if it is unable to find the module

Try.. Except in Python


Try and Except statement is used to handle these errors within our code in Python. The try block
is used to check some code for errors i.e the code inside the try block will execute when there is
no error in the program. Whereas the code inside the except block will execute whenever the
program encounters some error in the preceding try block.
Syntax:
try:
statement1 #test code
except:
statement2 #error message
finally:
statement3 #must execute
How does try() work?
First, the try clause is executed i.e. the code between try.
• If there is no exception, then only the try clause will run, except clause is finished.
• If any exception occurs, the try clause will be skipped and except clause will run.
• If any exception occurs, but the except clause within the code doesn’t handle it, it is
passed on to the outer try statements. If the exception is left unhandled, then the
execution stops.
• A try statement can have more than one except clause
Example:
def divide(x, y):
try:
# Floor Division : Gives only Fractional Part as Answer
result = x // y
print("Yeah ! Your answer is :", result)
exceptZeroDivisionError:
print("Sorry ! You are dividing by zero ")
# Look at parameters and note the working of Program
divide(3, 2)
Output :
Yeah ! Your answer is : 1

Department of Computer Science and Engineering


Programming in Python (U23ADTC01)

5. What are the uses of finally block? Explain with examples?


• The finally keyword is used in try...except blocks. It defines a block of code to run when the
try...except...else block is final.
• The finally block will be executed no matter if the try block raises an error or not.
• This can be useful to close objects and clean up resources.
• The finally code block is also a part of exception handling. When we handle exception using
the try and except, we can include a finally block at the end.
• The finally block is always executed, so it is generally used for doing the concluding tasks
like closing file resources or closing database connection or may be ending the program
execution with a delightful message.
The finally block in Python's exception handling is used to define cleanup actions that should
always be executed, regardless of whether an exception occurred or not in the corresponding try
block. It is commonly used for releasing resources, closing files, or performing other cleanup
tasks that need to be done regardless of the program's flow.
Syntax :
try:
print("try block")
except:
print("except block")
finally:
print("finally block")
Importance :

The finally block in Python's exception handling mechanism is important for several reasons:
1. Resource Management: It ensures that critical resources, such as file handles, database
connections, or network connections, are properly released and closed, preventing
resource leaks and improving system stability.
2. Cleanup Actions: It allows you to define cleanup actions that should always be
performed, such as logging, resetting variables, or releasing locks, regardless of whether
an exception occurred or not. This promotes clean and maintainable code.
3. Error Handling: It complements the try and except blocks by providing a way to
execute cleanup code even if an exception occurs, ensuring that your program can
gracefully handle errors and recover from exceptional situations.
4. Predictable Behavior: The finally block guarantees that certain actions are always
executed, improving the predictability and reliability of your code, especially in complex
applications where error handling and resource management are crucial.

Example Program1:
def divide(a, b):
try:
result = a / b
print(f"Result: {result}")
except ZeroDivisionError:
print("Error: Division by zero.")
finally:
print("Cleanup: Resetting variables.")

Department of Computer Science and Engineering


Programming in Python (U23ADTC01)

a=0
b=0
divide(10, 2)
divide(10, 0)

Example Program 2:
try:
file = open("example.txt", "w")
file.write("Hello, world!")
except FileNotFoundError:
print("File not found.")
finally:
file.close()
print("File closed successfully.")

6. Write a program in python to write content into a file and reading the same from the file.
If the file is not present raise your own exception 'FNF' exception and handle?
Algorithm:
1. Start by defining a function write_and_read_file that takes a file name and content as
parameters.
2. Attempt to open the file in write mode ("w").
• If successful, write the content to the file and close it.
• If the file is not found (FileNotFoundError), raise a custom "FNF" exception.
3. Define a function main to call write_and_read_file with a file name and content.
4. Call the main function to execute the program.
Program:
# Define a custom exception for File Not Found
class FNFException(Exception):
pass
# Function to write content to a file and read it
def write_and_read_file(file_name, content):
try:
# Attempt to open the file in write mode
with open(file_name, 'w') as file:
file.write(content)
print("Content written to the file successfully.")
except FileNotFoundError:
# Raise custom "FNF" exception if file is not found
raise FNFException("File Not Found.")

# Attempt to read the content from the file


try:
with open(file_name, 'r') as file:
file_content = file.read()
print("Content read from the file:")
print(file_content)

Department of Computer Science and Engineering


Programming in Python (U23ADTC01)

except FileNotFoundError:
print("File not found while reading.")

# Main function to call write_and_read_file


def main():
file_name = "example.txt"
content = "Hello, world!"

try:
write_and_read_file(file_name, content)
except FNFException as e:
print(f"Custom exception caught: {e}")

# Call the main function to execute the program


if __name__ == "__main__":
main()
Output :
Content written to the file successfully.
Content read from the file:
Hello, world!

7. Write any five built in functions in tuple and explain.


These functions work for tuples of any comparable elements, such as numbers, strings, etc…
LEN ()
len(): Returns the number of elements in a tuple
EXAMPLE PROGRAM
my_tuple = (1, 2, 3, 4, 5)
print(len(my_tuple))
Output: 5
COUNT()
count(): Returns the number of occurrences of a specified value in the tuple.
EXAMPLE PROGRAM
my_tuple = (1, 2, 2, 3, 4, 2)
print(my_tuple.count(2))
Output: 3 (since 2 appears three times so it printed 3)
INDEX()
EXAMPLE PROGRAM
index(): Returns the index of the first occurrence of a specified value in the tuple.
my_tuple = ('a', 'b', 'c', 'a', 'd')
print(my_tuple.index('a'))
Output: 0 (index of first 'a')
SORTED()
sorted(): Returns a new sorted list from the elements of the tuple (does not modify the
original tuple).

Department of Computer Science and Engineering


Programming in Python (U23ADTC01)

EXAMPLE PROGRAM
my_tuple = (5, 3, 1, 4, 2)
sorted_tuple = sorted(my_tuple)
print(sorted_tuple)
Output: [1, 2, 3, 4, 5]
TUPLE()
tuple(): Converts an iterable (such as a list) into a tuple.
EXAMPLE PROGRAM
my_list = [1, 2, 3, 4, 5]
converted_tuple = tuple(my_list)
print(converted_tuple)
Output: (1, 2, 3, 4, 5)
MIN()
min(): Returns the smallest element in the tuple.
EXAMPLE PROGRAM
my_tuple = (10, 5, 20, 8, 15)
print(min(my_tuple))
Output: 5
MAX()
max(): Returns the largest element in the tuple.
EXAMPLE PROGRAM
my_tuple = (10, 5, 20, 8, 15)
print(max(my_tuple))
Output: 20

8. Explain about Classes and Objects with examples.


Class:
➢ A class is a user-defined blueprint or prototype from which objects are created.
➢ Classes provide a means of bundling data and functionality together.
➢ Creating a new class creates a new type of object, allowing new instances of that type to
be made.
➢ Syntax: Class Definition
class ClassName:
# Statement
➢ Classes are created by keyword class.
➢ Attributes are the variables that belong to a class.
➢ Attributes are always public and can be accessed using the dot (.) operator.
Eg.: My class.Myattribute
➢ Creating a Python Class
➢ Here, the class keyword indicates that you are creating a class followed by the name of
the class (Dog in this case).

class Dog:
sound = "bark"

Department of Computer Science and Engineering


Programming in Python (U23ADTC01)

Objects:
➢ An Object is an instance of a Class.
➢ Python Objects are basically an encapsulation of data variables and methods acting on
that data into a single entity.
➢ Syntax: Object Definition
obj = ClassName()
print(obj.atrr)

➢ Instance defining represent memory allocation necessary for storing the actual data of
variables.
➢ Each time when you create an object of class a copy of each data variable defined in
that class is created.
➢ An object consists of:
o State: It is represented by the attributes of an object. It also reflects the properties
of an object.
o Behavior: It is represented by the methods of an object. It also reflects the
response of an object to other objects.
o Identity: It gives a unique name to an object and enables one object to interact
with other objects.
# Python3 program to
# demonstrate instantiating
# a class
class Dog:

# A simple class
# attribute
attr1 = "mammal"
attr2 = "dog"

# A sample method
def fun(self):
print("I'm a", self.attr1)
print("I'm a", self.attr2)

# Driver code
# Object instantiation
Rodger = Dog()

# Accessing class attributes


# and method through objects
print(Rodger.attr1)
Rodger.fun()
Output:
mammal
I'm a mammal
I'm a dog

Department of Computer Science and Engineering


Programming in Python (U23ADTC01)

9. Write a python program to do arithmetic operations using classes and objects.


Python Arithmetic Operators are used to perform mathematical operations like addition,
subtraction, multiplication, and division.

Operator Description Syntax

+ Addition: adds two operands x+y


– Subtraction: subtracts two operands x–y
* Multiplication: multiplies two operands x*y
/ Division (float): divides the first operand by the second x/y
// Division (floor): divides the first operand by the second x // y
Modulus: returns the remainder when the first operand is
% divided by the second x%y
** Power (Exponent): Returns first raised to power second x ** y

EXAMPLE:
a=7
b=2

# addition
print ('Sum: ', a + b)

# subtraction
print ('Subtraction: ', a - b)

# multiplication
print ('Multiplication: ', a * b)

# division
print ('Division: ', a / b)

# floor division
print ('Floor Division: ', a // b)

# modulo
print ('Modulo: ', a % b)

# a to the power b
print ('Power: ', a ** b)

Department of Computer Science and Engineering


Programming in Python (U23ADTC01)

OUTPUT:
Sum: 9
Subtraction: 5
Multiplication: 14
Division: 3.5
Floor Division: 3
Modulo: 1
Power: 49

10. Explain about the Method Overloading in python.


Method Overloading:
➢ Two or more methods have the same name but different numbers of parameters or
different types of parameters, or both. These methods are called overloaded methods and
this is called method overloading.
➢ Like other languages (for example, method overloading in C++) do, python does not
support method overloading by default.
➢ But there are different ways to achieve method overloading in Python.
➢ The problem with method overloading in Python is that we may overload the methods
but can only use the latest defined method.
EXAMPLE:
# First product method.
# Takes two argument and print their
# product
def product(a, b):
p=a*b
print(p)

# Second product method


# Takes three argument and print their
# product
def product(a, b, c):
p = a * b*c
print(p)
# Uncommenting the below line shows an error
# product(4, 5)
# This line will call the second product method
product(4, 5, 5)

OUTPUT:100
➢ We may define many methods of the same name and different arguments, but we can
only use the latest defined method. Calling the other method will produce an error.
➢ Like here calling product(4,5) will produce an error as the latest defined product method
takes three arguments.
To simulate method overloading, we can use a workaround by defining default value to
method arguments as None, so that it can be used with one, two or three arguments.

Department of Computer Science and Engineering


Programming in Python (U23ADTC01)

EXAMPLE:
class example:
def add(self, a = None, b = None, c = None):
x=0
if a !=None and b != None and c != None:
x = a+b+c
elifa !=None and b != None and c == None:
x = a+b
return x
obj = example()
print (obj.add(10,20,30))
print (obj.add(10,20))

OUTPUT:
60
30
By Using Multiple Dispatch Decorator :
➢ In Backend, Dispatcher creates an object which stores different implementation and
on runtime, it selects the appropriate method as the type and number of parameters
passed.frommultipledispatch import dispatch
EXAMPLE:
# passing one parameter
@dispatch(int, int)
def product(first, second):
result = first*second
print(result)

# passing two parameters


@dispatch(int, int, int)
def product(first, second, third):
result = first * second * third
print(result)

# you can also pass data type of any value as per requirement
@dispatch(float, float, float)
def product(first, second, third):
result = first * second * third
print(result)

# calling product method with 2 arguments


product(2, 3) # this will give output of 6

# calling product method with 3 arguments but all int


product(2, 3, 2) # this will give output of 12
# calling product method with 3 arguments but all float
product(2.2, 3.4, 2.3) # this will give output of 17.985999999999997

Department of Computer Science and Engineering


Programming in Python (U23ADTC01)

OUTPUT:
6
12
17.985999999999997

11. Explain about the Single inheritance with examples in python.


Inheritance:
➢ It is a mechanism that allows you to create a hierarchy of classes that share a set of
properties and methods by deriving a class from another class.
➢ Inheritance is the capability of one class to derive or inherit the properties from
another class.
The benefits of Inheritance in Python are as follows:
➢ It represents real-world relationships well.
➢ It provides the reusability of a code. We don’t have to write the same code again and
again. Also, it allows us to add more features to a class without modifying it.
➢ It is transitive in nature, which means that if class B inherits from another class A,
then all the subclasses of B would automatically inherit from class A.
➢ Inheritance offers a simple, understandable model structure.
➢ Less development and maintenance expenses result from an inheritance.
Python Inheritance Syntax
➢ The syntax of simple inheritance in Python is as follows:
Class BaseClass:
{Body}
Class DerivedClass(BaseClass):
{Body}
Single Inheritance:
➢ Single inheritance enables a derived class to inherit properties from a single parent
class, thus enabling code reusability and the addition of new features to existing code.

EXAMPLE:
# Python program to demonstrate single inheritance

# Base class
class Parent:
def func1(self):
print("This function is in parent class.")

Department of Computer Science and Engineering


Programming in Python (U23ADTC01)

# Derived class
class Child(Parent):
def func2(self):
print("This function is in child class.")

# Driver's code
object = Child()
object.func1()
object.func2()

OUTPUT:
This function is in parent class.
This function is in child class.

12. Explain about the Multiple inheritance with examples in python.

Multiple Inheritance:
➢ When a class can be derived from more than one base class this type of inheritance is
called multiple inheritances.
➢ In multiple inheritances, all the features of the base classes are inherited into the
derived class.
➢ The syntax of multiple inheritance in Python is as follows:
class BaseClass1:
{Body}
class BaseClass2:
{Body}
class DerivedClass(BaseClass1,BaseClass2):
{Body}

EXAMPLE:
# Python program to demonstrate multiple inheritance

# Base class1
class Mother:
mothername = ""

Department of Computer Science and Engineering


Programming in Python (U23ADTC01)

def mother(self):
print(self.mothername)

# Base class2
class Father:
fathername = ""

def father(self):
print(self.fathername)

# Derived class
class Son(Mother, Father):
def parents(self):
print("Father :", self.fathername)
print("Mother :", self.mothername)
# Driver's code
s1 = Son()
s1.fathername = "RAM"
s1.mothername = "SITA"
s1.parents()

OUTPUT:
Father : RAM
Mother : SITA

13. Explain about the Multilevel inheritance with examples in python.

Multilevel Inheritance:
➢ In multilevel inheritance, features of the base class and the derived class are further
inherited into the new derived class. This is similar to a relationship representing a
child and a grandfather.
➢ The syntax of multilevel inheritance in Python is as follows:
class BaseClass1:
{Body}
class DerivedClass1(BaseClass1):
{Body}
class DerivedClass2(DerivedClass1):
{Body}

Department of Computer Science and Engineering


Programming in Python (U23ADTC01)

EXAMPLE:
# Python program to demonstrate multilevel inheritance

# Base class
class Grandfather:
def __init__(self, grandfathername):
self.grandfathername = grandfathername

# Intermediate class
class Father(Grandfather):
def __init__(self, fathername, grandfathername):
self.fathername = fathername

# invoking constructor of Grandfather class


Grandfather.__init__(self, grandfathername)

# Derived class
class Son(Father):
def __init__(self, sonname, fathername, grandfathername):
self.sonname = sonname

# invoking constructor of Father class


Father.__init__(self, fathername, grandfathername)

def print_name(self):
print('Grandfather name :', self.grandfathername)
print("Father name :", self.fathername)
print("Son name :", self.sonname)

# Driver code
s1 = Son('Prince', 'Rampal', 'Lal mani')
print(s1.grandfathername)
s1.print_name()

OUTPUT:
Lal manis
Grandfather name : Lal mani
Father name : Rampal
Son name : Prince

Department of Computer Science and Engineering


Programming in Python (U23ADTC01)

14. Explain about the Hierarchical inheritance with examples in python.

Hierarchical Inheritance:
➢ When more than one derived class are created from a single base this type of
inheritance is called hierarchical inheritance. In this program, we have a parent
(base) class and two child (derived) classes.
➢ The syntax of hierarchical inheritance in Python is as follows:
class BaseClass1:
{Body}
class DerivedClass1(BaseClass1):
{Body}
class DerivedClass2(BaseClass1):
{Body}
class DerivedClass3(BaseClass1):
{Body}
EXAMPLE:
# Python program to demonstrate Hierarchical inheritance
# Base class
class Parent:
def func1(self):
print("This function is in parent class.")
# Derived class1
class Child1(Parent):
def func2(self):
print("This function is in child 1.")

# Derived class2
class Child2(Parent):
def func3(self):
print("This function is in child 2.")

# Driver's code
object1 = Child1()
object2 = Child2()
object1.func1()
object1.func2()
object2.func1()
object2.func3()

Department of Computer Science and Engineering


Programming in Python (U23ADTC01)

OUTPUT:
This function is in parent class.
This function is in child 1.
This function is in parent class.
This function is in child 2.

15. Explain about the Hybrid inheritance with examples in python.

Hybrid Inheritance:
➢ Inheritance consisting of multiple types of inheritance is called hybrid inheritance.
EXAMPLE:
# Python program to demonstrate hybrid inheritance
class School:
def func1(self):
print("This function is in school.")

class Student1(School):
def func2(self):
print("This function is in student 1. ")

class Student2(School):
def func3(self):
print("This function is in student 2.")
class Student3(Student1, School):
def func4(self):
print("This function is in student 3.")

# Driver's code
object = Student3()
object.func1()
object.func2()
OUTPUT:
This function is in school.
This function is in student 1.

Department of Computer Science and Engineering


Programming in Python (U23ADTC01)

16. Explain about the Abstract class in python.


Abstraction in Python:
➢ Abstraction is used to hide the internal functionality of the function from the users.
➢ The users only interact with the basic implementation of the function, but inner
working is hidden.
➢ User is familiar with that "what function does" but they don't know "how it does."
Why Abstraction is Important?
➢ In Python, an abstraction is used to hide the irrelevant data/class in order to reduce
the complexity. It also enhances the application efficiency.
Abstraction classes in Python
➢ In Python, abstraction can be achieved by using abstract classes and interfaces.
➢ A class that consists of one or more abstract method is called the abstract class.
➢ Abstract methods do not contain their implementation.
➢ Abstract class can be inherited by the subclass and abstract method gets its
definition in the subclass.
➢ Abstraction classes are meant to be the blueprint of the other class.
➢ An abstract class can be useful when we are designing large functions.
➢ An abstract class is also helpful to provide the standard interface for different
implementations of components.
➢ Python provides the abc module to use the abstraction in the Python program.
SYNTAX
from abc import ABC
class ClassName(ABC):

We import the ABC class from the abc module.


Abstract Base Classes
➢ An abstract base class is the common application program of the interface for a set of
subclasses.
➢ It can be used by the third-party, which will provide the implementations such as with
plugins.
➢ It is also beneficial when we work with the large code-base hard to remember all the
classes.
Working of the Abstract Classes
➢ Unlike the other high-level language, Python doesn't provide the abstract class itself. We
need to import the abc module, which provides the base for defining Abstract Base
classes (ABC).
➢ The ABC works by decorating methods of the base class as abstract.
➢ It registers concrete classes as the implementation of the abstract base.
➢ We use the @abstractmethod decorator to define an abstract method or if we don't
provide the definition to the method, it automatically becomes the abstract method.
EXAMPLE -
# Python program demonstrate
# abstract base class work
from abc import ABC, abstractmethod

Department of Computer Science and Engineering


Programming in Python (U23ADTC01)

class Car(ABC):
def mileage(self):
pass

class Tesla(Car):
def mileage(self):
print("The mileage is 30kmph")
class Suzuki(Car):
def mileage(self):
print("The mileage is 25kmph ")
class Duster(Car):
def mileage(self):
print("The mileage is 24kmph ")
class Renault(Car):
def mileage(self):
print("The mileage is 27kmph ")

# Driver code
t= Tesla ()
t.mileage()
r = Renault()
r.mileage()
s = Suzuki()
s.mileage()
d = Duster()
d.mileage()

OUTPUT:
The mileage is 30kmph
The mileage is 27kmph
The mileage is 25kmph
The mileage is 24kmph

17. Explain about the Method overriding with examples in python.


Method Overriding in Python
➢ Any object-oriented programming language can allow a subclass or child class to offer a
customized implementation of a method already supplied by one of its superclasses or
parent classes. This capability is known as method overriding.
➢ The term "override" refers to a method in a subclass that replaces a method in a
superclass when both methods share the same name, parameters, signature, and return
type (or sub-type).

Department of Computer Science and Engineering


Programming in Python (U23ADTC01)

EXAMPLE:
# program to determine the method overriding
# Defining a parent class
class Parent():
# producer
def __init__(self):
self.value = "Inside Parent"
# showing a parents method
def show(self):
print(self.value)
# Defining a child class
class Child(Parent):
# Constructor
def __init__(self):
self.value = "Inside Child"
# showing the child's method
def show(self):
print(self.value)
# Chauffeur's code
obj1 = Parent()
obj2 = Child()
obj1.show()
obj2.show()
OUTPUT:
Inside Parent
Inside Child
➢ The overridden methods may also invoke methods from the parent class. There are
typically two ways to accomplish this.

Department of Computer Science and Engineering


Programming in Python (U23ADTC01)

a) Using Class name: Inside the overridden method, use the Parent classname-method to invoke
methods from the Parent's class.
EXAMPLE:
# program to determine calling the Parent's class method In the overridden method
class Parent ():
def show(self):
print ("Inside Parent")
class Child (Parent):
def show(self):
# child's class method is called
Parent.show(self)
Print ("Inside Child")
obj = Child ()
obj. show ()
OUTPUT:
Inside Parent
Inside Child
b) Using Super (): The Super () function in Python allows us to refer to the parent class
explicitly. It comes in handy when we need to call superclass functions. It gives us the proxy
object to use "super" to refer to the parent class.

EXAMPLE:

# Program to determine the Super () function used


# In multiple inheritances
class JTP1:
def __init__(self):
print ('HEY !!!!!! jtpI am initialized (Class JSP1)')
def sub_JTP (self, b):
print ('Printing from class JTP1:', b)
# inheritance of JTP2 to JTP1 occurs
class JTP2(JTP1):
def __init__(self):
print ('HEY !!!!!! JTP I am initialized (Class JSP2)')
super().__init__()

def sub_JTP (self, b):


print ('Printing from class JTP2:', b)
super (). sub_JTP (b + 1)
# inheritance of both JTP2 and JTP1 is done by JTP3
class JTP3(JTP2):
def __init__(self):
print ('HEY !!!!!! JTP I am initialized (Class JSP3)')
super().__init__()
def sub_JTP (self, b):
print ('Printing from class JTP3:', b)

Department of Computer Science and Engineering


Programming in Python (U23ADTC01)

super ().sub_JTP(b + 1)
# function main
if __name__ == '__main__':
jtp = JTP3()
jtp.sub_JTP(10)

OUTPUT:

HEY !!!!!! JTP I am initialized (Class JSP3)


HEY !!!!!! JTP I am initialized (Class JSP2)
HEY !!!!!! JTP I am initialized (Class JSP1)
Printing from class JTP3: 10
Printing from class JTP3: 11
Printing from class JTP3: 12

18. What are the uses of Regular Expressions? Explain.


➢ A RegEx, or Regular Expression, is a sequence of characters that forms a search pattern.
➢ RegEx can be used to check if a string contains the specified search pattern.
RegEx Module
➢ Python has a built-in package called re, which can be used to work with Regular
Expressions.
Import the re module:
import re
a) The findall() Function:
➢ The findall() function returns a list containing all matches.

Example: Print a list of all matches:


import re

txt = "The rain in Spain"


x = re.findall("ai", txt)
print(x)

b) The search() Function:


➢ The search() function searches the string for a match, and returns a Match object if there
is a match.
➢ If there is more than one match, only the first occurrence of the match will be returned:
➢ If no matches are found, the value None is returned
EXAMPLE :Search for the first white-space character in the string:

import re
txt = "The rain in Spain"
x = re.search("\s", txt)
print("The first white-space character is located in position:", x.start())

Department of Computer Science and Engineering


Programming in Python (U23ADTC01)

c) The split() Function


The split() function returns a list where the string has been split at each match:

EXAMPLE: Split at each white-space character:


import re
txt = "The rain in Spain"
x = re.split("\s", txt)
print(x)

d) The sub() Function


➢ The sub() function replaces the matches with the text of your choice
EXAMPLE :Replace every white-space character with the number 9:
import re
txt = "The rain in Spain"
x = re.sub("\s", "9", txt)
print(x)

e) Match Object
➢ A Match Object is an object containing information about the search and the result.
➢ Note: If there is no match, the value None will be returned, instead of the Match Object.

EXAMPLE: Do a search that will return a Match Object:

import re
txt = "The rain in Spain"
x = re.search("ai", txt)
print(x) #this will print an object

19. Create a set and apply the union, intersection, difference and symmetric difference.
Let us define two sets:
Set A: {1, 2, 3, 4, 5}
Set B: {4, 5, 6, 7, 8}
Operations performed on Set:
Union: The union of two sets contains all unique elements from both sets.
Intersection: The intersection of two sets contains only the elements that are common to
both sets.
Difference: The difference between two sets contains elements that are in the first set but
not in the second set.
Symmetric Difference: The symmetric difference contains elements that are in either of
the sets but not in both.
EXAMPLE PROGRAM:
# Define the two sets
set_A = {1, 2, 3, 4, 5}
set_B = {4, 5, 6, 7, 8}
# Union
union_set = set_A.union(set_B)

Department of Computer Science and Engineering


Programming in Python (U23ADTC01)

print("Union:", union_set)
# Intersection
intersection_set = set_A.intersection(set_B)
print("Intersection:", intersection_set)
# Difference
difference_set_A = set_A.difference(set_B)
print("Difference (A - B):", difference_set_A)
difference_set_B = set_B.difference(set_A)
print("Difference (B - A):", difference_set_B)
# Symmetric Difference
symmetric_difference_set = set_A.symmetric_difference(set_B)
print("Symmetric Difference:", symmetric_difference_set)

OUTPUT:
Union: {1, 2, 3, 4, 5, 6, 7, 8}
Intersection: {4, 5}
Difference (A - B): {1, 2, 3}
Difference (B - A): {8, 6, 7}
Symmetric Difference: {1, 2, 3, 6, 7, 8}

20. Write any five built-in function related to sets in python and explain.
1. add()
• Syntax: set.add(element)
• This function adds a single element to the set. If the element is already present in
the set, the set remains unchanged.
• EXAMPLE:
my_set = {1, 2, 3}
my_set.add(4)
print(my_set) # Output: {1, 2, 3, 4}

2. remove()
• Syntax: set.remove(element)
• This function removes a specified element from the set. If the element is not
present, it raises a KeyError.
• EXAMPLE:
my_set = {1, 2, 3}
my_set.remove(2)
print(my_set) # Output: {1, 3}

3. pop()
• Syntax: set.pop()
• This function removes and returns an arbitrary element from the set. If the set is
empty, it raises a KeyError.
• EXAMPLE:
my_set = {1, 2, 3}
popped_element = my_set.pop()

Department of Computer Science and Engineering


Programming in Python (U23ADTC01)

print(popped_element) # Output: 1
print(my_set) # Output: {2, 3}

4. clear()
• Syntax: set.clear()
• This function removes all elements from the set, making it empty.
• EXAMPLE:
my_set = {1, 2, 3}
my_set.clear()
print(my_set) # Output: set()

5. copy()
• Syntax: set.copy()
• This function returns a shallow copy of the set. Modifications to the copy do not
affect the original set, but modifications to the elements inside the set are reflected
in both sets if they are mutable objects.
• EXAMPLE:
my_set = {1, 2, 3}
copied_set = my_set.copy()
copied_set.add(4)
print(my_set) # Output: {1, 2, 3}
print(copied_set) # Output: {1, 2, 3, 4}

21. Write a program in python to eliminate the duplicate values with and without using set.
# METHOD 1: USING SETS
PROGRAM 1:
def remove_duplicates_with_set(input_list):
# Convert the list to a set to remove duplicates
unique_set = set(input_list)
# Convert the set back to a list to preserve the original order
result_list = list(unique_set)
return result_list
# Example usage:
input_list = [1, 2, 3, 3, 4, 5, 5, 6]
result = remove_duplicates_with_set(input_list)
print("Without Duplicates (using set):", result)
OUTPUT:
Without Duplicates (using set): [1, 2, 3, 4, 5, 6]

# METHOD 2: WITHOUT USING SETS


PROGRAM 2:
my_list = [10, 20, 20, 30, 40, 50]
i=0
while i < len(my_list):
if my_list.count(my_list[i]) > 1:
my_list.remove(my_list[i])

Department of Computer Science and Engineering


Programming in Python (U23ADTC01)

else:
i += 1
print("List with duplicates removed:", my_list)
OUTPUT:
List with duplicates removed: [10, 20, 30, 40, 50]

22. Write about map in python.


In Python, map() is a built-in function that applies a specified function to each item in an
iterable (such as a list, tuple, or set) and returns an iterator that yields the results.
The map() function takes two arguments: the function to apply and the iterable containing the
elements to process.
Syntax:
map(function, iterable)
Parameters:
• function: The function to apply to each element in the iterable. It can be a built-in
function, a user-defined function, or a lambda function.
• iterable: An iterable object (such as a list, tuple, or set) containing the elements to
process.
Return Value:
• The map() function returns an iterator that yields the results of applying the specified
function to each element in the iterable.

EXAMPLE PROGRAM:
# Example with multiple iterables
def add(x, y):
return x + y
numbers1 = [1, 2, 3]
numbers2 = [4, 5, 6]
result = map(add, numbers1, numbers2)
print(list(result)) # Output: [5, 7, 9]

Department of Computer Science and Engineering

You might also like