0% found this document useful (0 votes)
18 views23 pages

PWP 22616 AnswerBank Unit Test I

The document is an answer bank for a Unit Test in Programming with Python, covering various topics such as Python syntax, data types, control flow structures, and programming examples. It includes explanations of key concepts like indentation, comments, variables, and operators, along with sample code snippets for practical understanding. Additionally, it provides programming exercises and examples to illustrate the application of Python programming principles.

Uploaded by

xjarveco
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)
18 views23 pages

PWP 22616 AnswerBank Unit Test I

The document is an answer bank for a Unit Test in Programming with Python, covering various topics such as Python syntax, data types, control flow structures, and programming examples. It includes explanations of key concepts like indentation, comments, variables, and operators, along with sample code snippets for practical understanding. Additionally, it provides programming exercises and examples to illustrate the application of Python programming principles.

Uploaded by

xjarveco
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/ 23

BHARATI VIDYAPEETH COLLEGE OF ENGINEERING

(DIPLOMA ENGINEERING)

ANSWER BANK

Unit Test-I
Program: - Computer Engineering Group Program Code:- CO
Course Title: Programming with Python Semester: - Sixth
Course Code:-PWP (22616) Scheme: I
--------------------------------------------------------------------------------------------------

1. Introduction and Syntax of Python program (08 MARKS)


2 Marks

1. Enlist applications for python programming.


• 3D Software
• Web development
• GUI-based desktop application.
• Image Processing
• Games
• Scientific and computational applications
2. Describe the Role of indentation in python.
Indentation in Python is crucial as it defines the structure and flow of the code. Unlike other
programming languages that use braces {} to define code blocks, Python uses indentation to
group statements.
Example:
def fun():
print("Hi")
if True:
print("true")
else:
print("false")

print("Done")

3. Name different modes of python.


• Script Mode
• Interactive Mode

4. How to give single and multiline comment in python.


Note: AI Can Make Mistakes
Single Line Comments: In Python for single line comments use # sign to comment out
everything following it on that line.
Multiple Lines Comments: Multiple lines comments are slightly different. Simply use 3
single quotes before and after the part you want to be commented.
Example:
#This is comment
#print("Statement will not be executed")
print("Statement will be excuted")
'''print("Multiple line comment")
print("Multiple line comment")
print("Multiple line comment")'''

5. List features of Python.


• Simple
• Easy to Learn
• Versatile
• Free and Open Source
• High-level Language
• Interactive
• Portable
• Object Oriented
• Interpreted
• Dynamic
• Extensible

6. List Data types used in python.


• Text Type: String
• Numeric Type: int, float, complex
• Sequence Type: list, tuple, range
• Mapping Type: dict
• Set Type: set
• Boolean Type: bool

7. List building blocks of python.


• Identifiers
• Keywords
• Indention
• Variables
• Comments

Note: AI Can Make Mistakes


4 Marks

1. Explain building blocks of python.


Python Keywords:
• Keywords are predefined, reserved words used in Python programming that have special meanings to
the compiler.
• We cannot use a keyword as a variable name, function name, or any other identifier. They are used
to define the syntax and structure of the Python language.
Python Variables:
• A variable is a name given to a memory location where data is stored. It allows programmers to
store, retrieve, and manipulate data efficiently.
• In Python, you do not need to specify the data type while declaring a variable. It is dynamically
assigned based on the value.
name = "John" # String variable
age = 25 # Integer variable
height = 5.8 # Float variable
is_student = True # Boolean variable
• Rules for Naming Variables
Can contain letters, digits, and underscores (e.g., student_name).
Cannot start with a number (e.g., 1name is invalid).
Case-sensitive (Age and age are different).
Cannot use reserved keywords (e.g., if, else, for).

Keywords:
• Keywords are predefined, reserved words used in Python programming that have special meanings
to the compiler.
• We cannot use a keyword as a variable name, function name, or any other identifier. They are used
to define the syntax and structure of the Python language.

Indention:
• Indentation in Python is crucial as it defines the structure and flow of the code. Unlike other
programming languages that use braces {} to define code blocks, Python uses indentation to group
statements.
Example:
def fun():
print("Hi")
Note: AI Can Make Mistakes
if True:
print("true")
else:
print("false")

print("Done")

Comments:
• Comments are the non-executable statements in a program. They are just added to describe the
statements in the program code. Comments make the program easily readable and understandable
by the programmer as well as other users who are seeing the code. The interpreter simply ignores
the comments.
• Single Line Comments: In Python for single line comments use # sign to comment out everything
following it on that line.
• Multiple Lines Comments: Multiple lines comments are slightly different. Simply use 3 single
quotes before and after the part you want to be commented.
Example:
#This is comment
#print("Statement will not be executed")
print("Statement will be excuted")
'''print("Multiple line comment")
print("Multiple line comment")
print("Multiple line comment")'''

2. List data types used in python. Explain any two with example.
Text Type: String
Numeric Type: int, float, complex
Sequence Type: list, tuple, range
Mapping Type: dict
Set Type: set
Boolean Type: bool
Example of List:
fruits = ["Apple", "Banana", "Cherry"]
print(fruits) # Output: ['Apple', 'Banana', 'Cherry']
fruits.append("Mango") # Adding an element
print(fruits) # Output: ['Apple', 'Banana', 'Cherry', 'Mango']
Example of Dictionary:
student = {"name": "John", "age": 21, "course": "Python"}
print(student["name"]) # Output: John
student["age"] = 22 # Modifying value
print(student) # Output: {'name': 'John', 'age': 22, 'course': 'Python'}

Note: AI Can Make Mistakes


3. Explain with example: i) Indentation ii) Variables
Indentation: Indentation refers to spaces or tabs used at the beginning of a line to
define code blocks. Unlike other programming languages that use {} (curly braces),
Python relies on indentation to determine the structure of the code.
Example:
if 5 > 2:
print("5 is greater than 2") # This line is indented properly
Variables: A variable is a name used to store data in memory. It holds different types of
values, such as numbers, strings, or lists.
Example:
name = "Alice" # String variable
age = 25 # Integer variable
height = 5.6 # Float variable

print(name) # Output: Alice


print(age) # Output: 25
print(height) # Output: 5.6
4. Write a simple python program to display message using script mode.
a = int(input("Enter a Number:"))
print(a)

5. Write a python program to calculate area of square and rectangle.


side = float(input("Enter Side:"))
length = float(input("Enter Length:"))
width = float(input("Enter Width:"))
print("Area of Squeare:",side*side)
print("Area of rectangle:",length*width)

6. Write a python program to calculate rate_of_interest (i/p: Gross_salary, Basic_salary,


interest)
gross_salary = float(input("Enter Gross Salary:"))
basic_salary = float(input("Enter Basic Salary:"))
interest = float(input("Enter Interest:"))
print("Rate Of Interest:",(interest/basic_salary)*100)

7. Differentiate between Interactive mode and Script mode of python.

Note: AI Can Make Mistakes


2. Python operators and control flow structures (10 MARKS)

2 Marks

1. List identity operators in python.


• is
• is not

2. Describe membership operators in python.


Membership operators are used to check if a value exists in a sequence such as a string, list,
tuple, or dictionary. Python provides two membership operators:

1. in Operator
Returns True if the specified value exists in the sequence.
Otherwise, returns False.

2. not in Operator
Returns True if the specified value does not exist in the sequence.
Otherwise, returns False.

Example:
# Using 'in' operator
fruits = ["apple", "banana", "mango"]
print("apple" in fruits) # True
print("grape" in fruits) # False
Note: AI Can Make Mistakes
# Using 'not in' operator
text = "Hello Python"
print("Python" in text) # True
print("Java" not in text) # True

3. List comparison operators in Python.

4. Write the use of elif keyword in python.

The elif (short for "else if") keyword is used in conditional statements when multiple
conditions need to be checked one after another.It helps avoid multiple if statements,
making the code cleaner and more readable.

if condition1:

# Code executes if condition1 is True

elif condition2:

# Code executes if condition2 is True

elif condition3:

# Code executes if condition3 is True

else:

# Code executes if none of the conditions are True

5. Explain use of pass statement.


• In Python programming, the pass statement is a null statement. The difference between
a comment and a pass statement in Python is that while the interpreter ignores a
comment entirely, pass is not ignored.
• However, nothing happens when the pass is executed. It results in no operation (NOP)
• Suppose we have a loop or a function that is not implemented yet, but we want to
implement it in the future. They cannot have an empty body. The interpreter would
give an error. So, we use the pass statement to construct a body that does nothing.
• Example:

Note: AI Can Make Mistakes


def function(args):
pass
• Example:
class abc:
pass

6. Explain the term: a) continue b) break


continue Statement
• The continue statement skips the current iteration of the loop and moves to the next
iteration.
• The loop does not stop, it just skips the remaining code for the current iteration
Example:
for num in range(1, 6):
if num == 3:
continue # Skips when num is 3
print(num)

break Statement
• The break statement terminates the loop completely when a certain condition is met.
• The loop stops executing immediately.
Example:
for num in range(1, 6):
if num == 3:
break # Stops the loop when num is 3
print(num)

4 Marks

1. Write python program to display output like.

4 6 8

10 12 14 16 18
num = 2
rows = 3 # Number of rows

for i in range(1, rows + 1): # Loop for rows


for j in range(2 * i - 1): # Loop for elements in each row
print(num, end=" ")
num += 2 # Increment by 2 to get even numbers
print() # Move to the next line
Note: AI Can Make Mistakes
2. Explain use of Pass and Else keyword with for loops in python.
pass Keyword in for Loop
The pass statement does nothing and acts as a placeholder.
It is used when a block of code is required syntactically but no action is needed.
This is useful when writing code that you plan to implement later.
Example:
for num in range(1, 6):
if num == 3:
pass # Placeholder, does nothing
else:
print(num)
else Keyword in for Loop
The else block executes after the loop completes successfully (without a break).
If the loop is terminated using break, the else block will not execute.
Example:
for num in range(1, 6):
print(num)
else:
print("Loop completed successfully!")

3. Describe bitwise operators in Python with example.


4. Write python program to illustrate if else ladder.
marks = int(input("Enter your marks: "))

if marks >= 90:


print("Grade: A+")
elif marks >= 80:
print("Grade: A")
elif marks >= 70:
print("Grade: B")
elif marks >= 60:
print("Grade: C")
elif marks >= 50:
print("Grade: D")
else:
print("Grade: Fail")

Note: AI Can Make Mistakes


5. Write Python code for finding greatest among four numbers.
# Taking four numbers as input from the user
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
num3 = int(input("Enter third number: "))
num4 = int(input("Enter fourth number: "))

# Finding the greatest number using if-else ladder


if num1 >= num2 and num1 >= num3 and num1 >= num4:
print("Greatest number is:", num1)
elif num2 >= num1 and num2 >= num3 and num2 >= num4:
print("Greatest number is:", num2)
elif num3 >= num1 and num3 >= num2 and num3 >= num4:
print("Greatest number is:", num3)
else:
print("Greatest number is:", num4)

6. Print the following pattern using loop:


1010101
10101
101
1
rows = 4 # Number of rows

# Outer loop for rows


for i in range(rows, 0, -1):
# Printing leading spaces
print(" " * (rows - i) * 2, end="")

# Printing 1 0 pattern
for j in range(2 * i - 1):
if j % 2 == 0:
print("1", end=" ")
else:
print("0", end=" ")

print() # Move to the next line

7. Write a python program that takes a number and checks whether it is a palindrome.

Note: AI Can Make Mistakes


num = int(input("Enter a number: ")) # User input
temp = num # Store original number
rev = 0

while temp > 0:


digit = temp % 10 # Extract last digit
rev = rev * 10 + digit # Form reversed number
temp //= 10 # Remove last digit

if num == rev: # Check if original and reversed numbers are same


print(num, "is a Palindrome")
else:
print(num, "is not a Palindrome")

8. Write a python program takes in a number and find the sum of digits in a number.
num = int(input("Enter a number: ")) # User input
sum_digits = 0

while num > 0:


sum_digits += num % 10 # Extract last digit and add to sum
num //= 10 # Remove last digit

print("Sum of digits:", sum_digits)

9. Write a Python program to find the factorial of a number provided by the user.
num = int(input("Enter a number: ")) # User input
fact = 1

for i in range(1, num + 1): # Loop from 1 to num


fact *= i # Multiply fact by i

print("Factorial of", num, "is", fact)

10. Write a Python Program to check if a string is palindrome or not.


# Take input from the user
text = input("Enter a string: ")

# Convert string to a list (because reverse() works on lists)


char_list = list(text)

# Reverse the list using reverse() function


char_list.reverse()

# Convert the reversed list back to a string

Note: AI Can Make Mistakes


reversed_text = ''.join(char_list)

# Check if the original string is equal to the reversed string


if text == reversed_text:
print("The string is a palindrome.")
else:
print("The string is not a palindrome.")

11. Explain decision making statements If - else, if - elif - else with example.
if-else Statement: The if-else statement is used when we want to execute one block of code if
a condition is true and another block if the condition is false.
Syntax:
if condition:
# Code to execute if the condition is true
else:
# Code to execute if the condition is false
Example:
num = int(input("Enter a number: "))

if num % 2 == 0:
print("The number is even.")
else:
print("The number is odd.")

if-elif-else Statement: The if-elif-else statement is used when there are multiple conditions to
check.
Syntax:
if condition1:
# Code if condition1 is true
elif condition2:
# Code if condition2 is true
elif condition3:
# Code if condition3 is true
else:
# Code if none of the above conditions are true
Example:
marks = int(input("Enter your marks: "))

Note: AI Can Make Mistakes


if marks >= 90:
print("Grade: A")
elif marks >= 75:
print("Grade: B")
elif marks >= 60:
print("Grade: C")
elif marks >= 40:
print("Grade: D")
else:
print("Grade: Fail")

3. Data Structures in python (14 Marks)


2 Marks
1. Give two differences between list and tuple.

2. Write syntax for a method to sort a list.


numbers = [5, 2, 8, 1, 3]
numbers.sort()
print(numbers)
3. What is dictionary?
A dictionary in Python is a collection of key-value pairs. It is used to store data in an
unordered, changeable, and indexed way, where each key is unique and maps to a value.
4. Describe Tuples in Python.
A tuple is an immutable (unchangeable) and ordered collection in Python that allows storing
multiple values in a single variable. It is similar to a list but cannot be modified after creation.
fruits = ("apple", "banana", "cherry")
Note: AI Can Make Mistakes
print(fruits)
5. Explain two ways to add objects / elements to list.
1. Using append()
• The append() method adds a single element to the end of the list.
numbers = [1, 2, 3]
numbers.append(4)
print(numbers) # Output: [1, 2, 3, 4]
2. Using extend()
• The extend() method adds multiple elements from another list (or iterable) to the existing list.
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
print(list1) # Output: [1, 2, 3, 4, 5, 6]

6. List different operations that can be performed on tuple.


Concatenation (+) → Combines two tuples.
t1 = (1, 2)
t2 = (3, 4)
result = t1 + t2
print(result) # Output: (1, 2, 3, 4)
Repetition (*) → Repeats a tuple multiple times.
t = (1, 2)
print(t * 3) # Output: (1, 2, 1, 2, 1, 2)
Indexing ([]) → Accesses elements using their position.
t = (10, 20, 30)
print(t[1]) # Output: 20
Slicing ([:]) → Extracts a portion of the tuple.
t = (10, 20, 30, 40, 50)
print(t[1:4]) # Output: (20, 30, 40)
Length (len()) → Finds the number of elements in the tuple.
t = (10, 20, 30)
print(len(t)) # Output: 3
Membership (in / not in) → Checks if an element is in the tuple.
t = (10, 20, 30)
print(20 in t) # Output: True

Note: AI Can Make Mistakes


print(50 not in t) # Output: True

7. List features of set.

A set in Python is an unordered collection of unique elements.

Unordered → Elements are stored in random order.


Unique Elements → Duplicates are not allowed.
Mutable → Can add or remove elements.
Supports Set Operations → Union, Intersection, Difference.
Uses {} Syntax → Example: {1, 2, 3}

s = {1, 2, 3, 4, 4, 5} # Duplicates will be removed

print(s) # Output: {1, 2, 3, 4, 5}

8. List operations that can be performed on dictionary.

A dictionary in Python is a collection of key-value pairs, and several operations can be


performed on it:

Accessing Values (dict[key] or get()) → Retrieve values using keys.


Adding New Key-Value Pairs (dict[key] = value) → Insert new data.
Updating Values (dict[key] = new_value) → Modify existing values.
Removing Elements (pop(), del, popitem(), clear()) → Delete key-value pairs.
Checking Membership (in / not in) → Verify if a key exists.
Looping Through Keys and Values (for loop) → Iterate through dictionary items.
Finding the Number of Items (len(dict)) → Count total key-value pairs.
Merging Dictionaries (update()) → Combine two dictionaries.

9. Explain any two methods of dictionary.


1. get() Method
The get() method is used to retrieve a value for a given key. If the key doesn’t exist, it returns
None instead of an error.
Syntax:
dictionary.get(key, default_value)
Example:
student = {"name": "AI", "age": 20}
Note: AI Can Make Mistakes
print(student.get("name")) # Output: AI
print(student.get("city", "Not Found")) # Output: Not Found

2. pop() Method
The pop() method removes a key-value pair from the dictionary and returns the value.
Syntax:
dictionary.pop(key, default_value)
Example:
student = {"name": "AI", "age": 20, "city": "Pune"}
age = student.pop("age") # Removes "age" and returns its value
print(age) # Output: 20
print(student) # Output: {'name': AI, 'city': 'Pune'}

4 Marks
1. Compare list and tuple.

2. Explain four Buit-in tuple functions python with example.


1. len() – Finding Length of Tuple: The len() function returns the total number of
elements in a tuple.
Example:
numbers = (10, 20, 30, 40, 50)
print(len(numbers)) # Output: 5

2. count() – Counting Occurrences of an Element: The count() function returns the


number of times a specific value appears in a tuple
Example:
fruits = ("apple", "banana", "apple", "mango", "apple")
print(fruits.count("apple")) # Output: 3

3. index() – Finding the Index of an Element: The index() function returns the first
position (index) where a given element is found in a tuple.
Example:
numbers = (5, 10, 15, 20, 25)

Note: AI Can Make Mistakes


print(numbers.index(15)) # Output: 2

4. max() & min() – Finding Maximum and Minimum Values: The max() function
returns the largest element, and min() returns the smallest element in a tuple.
Example:
values = (3, 8, 1, 6, 9)
print(max(values)) # Output: 9
print(min(values)) # Output: 1

3. Explain indexing and slicing in list with example.


1. Indexing in Lists
• Indexing is used to access individual elements in a list.
• Python uses zero-based indexing, meaning the first element is at index 0, the
second at 1, and so on.
• Negative indexing starts from the end (-1 for the last element, -2 for the second last,
etc.).
Example:
fruits = ["apple", "banana", "cherry", "mango"]

print(fruits[0]) # Output: apple (First element)


print(fruits[2]) # Output: cherry (Third element)
print(fruits[-1]) # Output: mango (Last element)

2. Slicing in Lists
Slicing is used to extract multiple elements from a list.
The syntax for slicing is:
list[start:end:step]
start: The index where slicing begins (inclusive).
end: The index where slicing stops (exclusive).
step: Defines how many elements to skip (optional).
Example:
numbers = [10, 20, 30, 40, 50, 60, 70]

print(numbers[1:4]) # Output: [20, 30, 40] (Elements from index 1 to 3)


print(numbers[:3]) # Output: [10, 20, 30] (First 3 elements)
print(numbers[3:]) # Output: [40, 50, 60, 70] (Elements from index 3 to end)
print(numbers[::2]) # Output: [10, 30, 50, 70] (Every 2nd element)
print(numbers[::-1]) # Output: [70, 60, 50, 40, 30, 20, 10] (Reversing list)
4. Write the output of the following :
i) >>> a = [ 2, 5, 1, 3, 6, 9, 7 ]
>>> a [ 2 : 6 ] = [ 2, 4, 9, 0 ]
>>> print (a)
Note: AI Can Make Mistakes
output: [2, 5, 2, 4, 9, 0, 7]
ii) >>> b = [ “Hello”, “Good” ]
>>> b. append ( “python” )
>>> print (b)
Output: ['Hello', 'Good', 'python']
iii) >>> t1 = [ 3, 5, 6, 7 ]
>>> print ( t1 [2] )
Output: 6
>>> print ( t1 [–1] )
Output: 7
>>> print ( t1 [2 :] )
Output: [6,7]
>>> print ( t1 [ : ] )
Output: [3, 5, 6, 7]
5. Explain creating Dictionary and accessing Dictionary Elements with example.
A dictionary in Python is an unordered collection of key-value pairs.
Each key must be unique and immutable (like strings, numbers, or tuples).
Values can be of any data type.
Defined using curly braces {}.
1. Creating a Dictionary
student = {
"name": "AI",
"age": 20,
"course": "Computer Science"
}
print(student)
2. Accessing Dictionary Elements
You can access values using square brackets [] with the key.
print(student["name"]) # Output: AI
print(student["age"]) # Output: 20

6. Write a python program to input any two tuples and interchange the tuple variables.
# Input two tuples from the user

Note: AI Can Make Mistakes


tuple1 = tuple(input("Enter first tuple elements separated by space:
").split())
tuple2 = tuple(input("Enter second tuple elements separated by space:
").split())

# Swapping tuples
tuple1, tuple2 = tuple2, tuple1

# Display the result


print("\nAfter Swapping:")
print("First Tuple:", tuple1)
print("Second Tuple:", tuple2)

7. Explain any six set function with example.


1. add()
• Adds an element to the set.
• Syntax: set.add(element)
Example:
s = {1, 2, 3}
s.add(4)
print(s) # Output: {1, 2, 3, 4}

2. remove()
• Removes a specific element from the set.
• Raises an error if the element is not found.
• Syntax: set.remove(element)
Example:
s = {1, 2, 3, 4}
s.remove(3)
print(s) # Output: {1, 2, 4}

3. discard()
• Removes an element from the set if it exists.
• Does not raise an error if the element is missing.
• Syntax: set.discard(element)
Example:
Note: AI Can Make Mistakes
s = {1, 2, 3, 4}
s.discard(3)
print(s) # Output: {1, 2, 4}
s.discard(10) # No error even though 10 is not in the set

4. union()
• Returns a new set containing all elements from both sets.
• Syntax: set1.union(set2)
Example:
s1 = {1, 2, 3}
s2 = {3, 4, 5}
result = s1.union(s2)
print(result) # Output: {1, 2, 3, 4, 5}

5. intersection()
• Returns a new set with common elements of both sets.
• Syntax: set1.intersection(set2)
Example:
s1 = {1, 2, 3}
s2 = {2, 3, 4}
result = s1.intersection(s2)
print(result) # Output: {2, 3}

6. difference()
• Returns a new set with elements only in the first set, not in the second.
• Syntax: set1.difference(set2)
Example:
s1 = {1, 2, 3, 4}
s2 = {3, 4, 5}
result = s1.difference(s2)
print(result) # Output: {1, 2}

8. Write the output for the following if the variable


Note: AI Can Make Mistakes
course = “Python”
>>> course [ : 3 ]
Output: Pyt
>>> course [ 3 : ]
Output: hon
>>> course [ 2 : 2 ]
This means extract characters starting from index 2 up to index 2 (excluding 2).
Since the start and end index are the same, it returns an empty string.
Output: "" (empty string)
>>> course [ : ]
Output: "Python"
9. Explain mutable and immutable data structures.
1. Mutable Data Structures
Definition: Mutable objects can be modified after creation (elements can be changed,
added, or removed).
Examples:
Lists (list)
Dictionaries (dict)
Sets (set)
Byte Arrays (bytearray)
Example of Mutable Data Structure (List)
# Creating a list
numbers = [1, 2, 3, 4]
numbers[1] = 10 # Modifying an element
numbers.append(5) # Adding an element
print(numbers)

2. Immutable Data Structures


Definition: Immutable objects cannot be changed after creation. Any modification
results in the creation of a new object.
Examples:
Tuples (tuple)
Strings (str)
Integers (int)
Floats (float)
Booleans (bool)
Frozen sets (frozenset)
Example of Immutable Data Structure (Tuple)
# Creating a tuple
numbers = (1, 2, 3, 4)
numbers[1] = 10 # This will cause an error!
Note: AI Can Make Mistakes
10. List and explain any four built-in functions on set.
1. add()
• Adds an element to the set.
• Syntax: set.add(element)
Example:
s = {1, 2, 3}
s.add(4)
print(s) # Output: {1, 2, 3, 4}

2. remove()
• Removes a specific element from the set.
• Raises an error if the element is not found.
• Syntax: set.remove(element)
Example:
s = {1, 2, 3, 4}
s.remove(3)
print(s) # Output: {1, 2, 4}

3. discard()
• Removes an element from the set if it exists.
• Does not raise an error if the element is missing.
• Syntax: set.discard(element)
Example:
s = {1, 2, 3, 4}
s.discard(3)
print(s) # Output: {1, 2, 4}
s.discard(10) # No error even though 10 is not in the set

4. union()
• Returns a new set containing all elements from both sets.
• Syntax: set1.union(set2)
Example:
s1 = {1, 2, 3}

Note: AI Can Make Mistakes


s2 = {3, 4, 5}
result = s1.union(s2)
print(result) # Output: {1, 2, 3, 4, 5}

5. intersection()
• Returns a new set with common elements of both sets.
• Syntax: set1.intersection(set2)
Example:
s1 = {1, 2, 3}
s2 = {2, 3, 4}
result = s1.intersection(s2)
print(result) # Output: {2, 3}

6. difference()
• Returns a new set with elements only in the first set, not in the second.
• Syntax: set1.difference(set2)
Example:
s1 = {1, 2, 3, 4}
s2 = {3, 4, 5}
result = s1.difference(s2)
print(result) # Output: {1, 2}

Note: AI Can Make Mistakes

You might also like