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

python-practicals (6)

The document outlines three practical programming exercises in Python: removing elements from data structures, working with odd and even numbers, and demonstrating classes with inheritance and polymorphism. Each section includes function definitions and example outputs, showcasing methods for list, dictionary, and set manipulations, as well as operations on odd and even numbers. The classes section illustrates object-oriented programming concepts with examples of an Animal class and its subclasses, Dog and Cat.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

python-practicals (6)

The document outlines three practical programming exercises in Python: removing elements from data structures, working with odd and even numbers, and demonstrating classes with inheritance and polymorphism. Each section includes function definitions and example outputs, showcasing methods for list, dictionary, and set manipulations, as well as operations on odd and even numbers. The classes section illustrates object-oriented programming concepts with examples of an Animal class and its subclasses, Dog and Cat.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Practical 17: Remove Method Program

Practical Name: Remove Method Program Objective: To demonstrate var-


ious ways of removing elements from different data structures in Python.
def demonstrate_remove_methods():
# List removal methods
def demonstrate_list_removal():
numbers = [1, 2, 3, 2, 4, 2, 5]
print("Original list:", numbers)

# Remove first occurrence of value


numbers.remove(2)
print("After removing first 2:", numbers)

# Pop by index
popped = numbers.pop(1)
print(f"Popped element {popped} from index 1:", numbers)

# Delete by index
del numbers[0]
print("After deleting first element:", numbers)

# Clear all elements


numbers.clear()
print("After clearing:", numbers)

# Dictionary removal methods


def demonstrate_dict_removal():
student = {
'name': 'John',
'age': 20,
'grade': 'A',
'city': 'New York'
}
print("\nOriginal dictionary:", student)

# Remove by key
removed_age = student.pop('age')
print(f"Removed age ({removed_age}):", student)

# Remove and get with default


grade = student.pop('grade', 'Not found')
print(f"Removed grade ({grade}):", student)

# Delete by key

1
del student['city']
print("After deleting city:", student)

# Set removal methods


def demonstrate_set_removal():
numbers = {1, 2, 3, 4, 5}
print("\nOriginal set:", numbers)

# Remove element
numbers.remove(3)
print("After removing 3:", numbers)

# Discard element (no error if not found)


numbers.discard(5)
print("After discarding 5:", numbers)

# Pop random element


popped = numbers.pop()
print(f"After popping {popped}:", numbers)

print("List Removal Methods:")


demonstrate_list_removal()

print("\nDictionary Removal Methods:")


demonstrate_dict_removal()

print("\nSet Removal Methods:")


demonstrate_set_removal()

demonstrate_remove_methods()
Output:
List Removal Methods:
Original list: [1, 2, 3, 2, 4, 2, 5]
After removing first 2: [1, 3, 2, 4, 2, 5]
Popped element 3 from index 1: [1, 2, 4, 2, 5]
After deleting first element: [2, 4, 2, 5]
After clearing: []

Dictionary Removal Methods:


Original dictionary: {'name': 'John', 'age': 20, 'grade': 'A', 'city': 'New York'}
Removed age (20): {'name': 'John', 'grade': 'A', 'city': 'New York'}
Removed grade (A): {'name': 'John', 'city': 'New York'}
After deleting city: {'name': 'John'}

Set Removal Methods:

2
Original set: {1, 2, 3, 4, 5}
After removing 3: {1, 2, 4, 5}
After discarding 5: {1, 2, 4}
After popping 1: {2, 4}

Practical 18: Odd Even Number Program


Practical Name: Odd Even Number Program Objective: To demonstrate
different methods of working with odd and even numbers in Python.
def demonstrate_odd_even():
def is_even(num):
return num % 2 == 0

def separate_odd_even(numbers):
evens = [num for num in numbers if is_even(num)]
odds = [num for num in numbers if not is_even(num)]
return evens, odds

def sum_odd_even(numbers):
even_sum = sum(num for num in numbers if is_even(num))
odd_sum = sum(num for num in numbers if not is_even(num))
return even_sum, odd_sum

def count_odd_even(numbers):
even_count = sum(1 for num in numbers if is_even(num))
return even_count, len(numbers) - even_count

# Test with a range of numbers


numbers = list(range(1, 11))
print("Original numbers:", numbers)

# Separate odd and even


evens, odds = separate_odd_even(numbers)
print("\nSeparated numbers:")
print("Even numbers:", evens)
print("Odd numbers:", odds)

# Sum of odd and even


even_sum, odd_sum = sum_odd_even(numbers)
print("\nSums:")
print(f"Sum of even numbers: {even_sum}")
print(f"Sum of odd numbers: {odd_sum}")

# Count odd and even


even_count, odd_count = count_odd_even(numbers)

3
print("\nCounts:")
print(f"Count of even numbers: {even_count}")
print(f"Count of odd numbers: {odd_count}")

# Generate first n even and odd numbers


n = 5
first_evens = [2 * i for i in range(1, n + 1)]
first_odds = [2 * i - 1 for i in range(1, n + 1)]
print(f"\nFirst {n} even numbers:", first_evens)
print(f"First {n} odd numbers:", first_odds)

demonstrate_odd_even()
Output:
Original numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Separated numbers:
Even numbers: [2, 4, 6, 8, 10]
Odd numbers: [1, 3, 5, 7, 9]

Sums:
Sum of even numbers: 30
Sum of odd numbers: 25

Counts:
Count of even numbers: 5
Count of odd numbers: 5

First 5 even numbers: [2, 4, 6, 8, 10]


First 5 odd numbers: [1, 3, 5, 7, 9]

Practical 19: Classes Program


Practical Name: Classes Program Objective: To demonstrate class creation,
inheritance, and polymorphism in Python.
def demonstrate_classes():
class Animal:
def __init__(self, name, species):
self.name = name
self.species = species

def make_sound(self):
return "Some generic sound"

def get_info(self):

4
return f"{self.name} is a {self.species}"

class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name, "Dog")
self.breed = breed

def make_sound(self):
return "Woof!"

def get_info(self):
return f"{super().get_info()} of breed {self.breed}"

class Cat(Animal):
def __init__(self, name, color):
super().__init__(name, "Cat")
self.color = color

def make_sound(self):
return "Meow!"

def get_info(self):
return f"{super().get_info()} with {self.color} fur"

# Create instances
dog = Dog("Buddy", "Golden Retriever")
cat = Cat("Whiskers", "orange")

# Demonstrate inheritance and polymorphism


animals = [dog, cat]
print("Animal Information:")
for animal in animals:
print(f"\n{animal.get_info()}")
print(f"Sound: {animal.make_sound()}")

# Demonstrate isinstance and type checking


print("\nType checking:")
print(f"Is dog an Animal? {isinstance(dog, Animal)}")
print(f"Is cat a Dog? {isinstance(cat, Dog)}")
print(f"Is dog a Dog? {isinstance(dog, Dog)}")

demonstrate_classes()
Output:
Animal Information:

5
Buddy is a Dog of breed Golden Retriever
Sound: Woof!

Whiskers is a Cat with orange fur


Sound: Meow!

Type checking:
Is dog an Animal? True
Is cat a Dog? False
Is dog a Dog? True
Would you like me to continue with the next set of practicals? We can cover
modules, file operations, and error handling next.

You might also like