Programming Assignments:TY B.sc(computer application)

TY B.sc(computer application)

Control Statements and Loops

1) Write a Python Program to Check if a Number is Positive, Negative or Zero

				
					def check_number(num):
    if num > 0:
        print("The number is positive.")
    elif num < 0:
        print("The number is negative.")
    else:
        print("The number is zero.")

# Test the program with different numbers
check_number(10)    # Output: The number is positive.
check_number(-5)    # Output: The number is negative.
check_number(0)     # Output: The number is zero.


				
			

output

				
					The number is positive.
The number is negative.
The number is zero.

				
			

2) Write a Python Program to Check Leap Years

				
					def is_leap_year(year):
    if year % 4 == 0:
        if year % 100 == 0:
            if year % 400 == 0:
                print(f"{year} is a leap year.")
            else:
                print(f"{year} is not a leap year.")
        else:
            print(f"{year} is a leap year.")
    else:
        print(f"{year} is not a leap year.")

# Test the program with different years
is_leap_year(2020)    # Output: 2020 is a leap year.
is_leap_year(2021)    # Output: 2021 is not a leap year.
is_leap_year(2000)    # Output: 2000 is a leap year.
is_leap_year(1900)    # Output: 1900 is not a leap year.

				
			

output

				
					2020 is a leap year.
2021 is not a leap year.
2000 is a leap year.
1900 is not a leap year.

				
			

 

3) Write a Python Program to Print all Prime Numbers in an Interval

				
					def print_prime_numbers(start, end):
    prime_numbers = []
    for num in range(start, end + 1):
        if num > 1:
            is_prime = True
            for i in range(2, int(num ** 0.5) + 1):
                if num % i == 0:
                    is_prime = False
                    break
            if is_prime:
                prime_numbers.append(num)
    
    print("Prime numbers between", start, "and", end, "are:")
    for prime in prime_numbers:
        print(prime)

# Test the program with different intervals
print_prime_numbers(10, 50)
print_prime_numbers(1, 100)
print_prime_numbers(100, 200)


				
			

output

				
					Prime numbers between 10 and 50 are:
11
13
17
19
23
29
31
37
41
43
47
Prime numbers between 1 and 100 are:
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97
Prime numbers between 100 and 200 are:
101
103
107
109
113
127
131
137
139
149
151
157
163
167
173
179
181
191
193
197
199

				
			

4)Write a Python Program to Print the Fibonacci sequence

				
					def fibonacci_sequence(n):
    sequence = [0, 1]  # Initialize the sequence with the first two Fibonacci numbers

    # Generate Fibonacci numbers
    for i in range(2, n):
        next_number = sequence[i - 1] + sequence[i - 2]
        sequence.append(next_number)

    return sequence

# Test the program
n = int(input("Enter the number of Fibonacci numbers to generate: "))

fib_sequence = fibonacci_sequence(n)
print("The Fibonacci sequence:")
for num in fib_sequence:
    print(num)

				
			

output

				
					Enter the number of Fibonacci numbers to generate: 33
The Fibonacci sequence:
0
1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
1597
2584
4181
6765
10946
17711
28657
46368
75025
121393
196418
317811
514229
832040
1346269
2178309


				
			

5) Write a Python Program to Check Armstrong Number

				
					s_armstrong_number(num):
    # Calculate the number of digits in the number
    num_digits = len(str(num))

    # Calculate the sum of the digits raised to the power of the number of digits
    armstrong_sum = 0
    temp = num
    while temp > 0:
        digit = temp % 10
        armstrong_sum += digit ** num_digits
        temp //= 10

    # Check if the sum is equal to the original number
    if armstrong_sum == num:
        return True
    else:
        return False

# Test the program
number = int(input("Enter a number: "))

if is_armstrong_number(number):
    print(number, "is an Armstrong number.")
else:
    print(number, "is not an Armstrong number.")


				
			

output

				
					Enter a number: 33
33 is not an Armstrong number.


				
			

6)  Write a Python Program to Find the Sum of Natural Numbers

				
					def sum_of_natural_numbers(n):
    sum = 0
    for i in range(1, n + 1):
        sum += i
    return sum

# Test the program
number = int(input("Enter a positive integer: "))

if number <= 0:
    print("Please enter a positive integer.")
else:
    result = sum_of_natural_numbers(number)
    print("The sum of natural numbers up to", number, "is:", result)


				
			

output

				
					Enter a positive integer: 34
The sum of natural numbers up to 34 is: 595

				
			

 

7) Write a Python Program to Find the Factorial of a Number 

				
					def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n - 1)

# Test the program
number = int(input("Enter a non-negative integer: "))

if number < 0:
    print("Please enter a non-negative integer.")
else:
    result = factorial(number)
    print("The factorial of", number, "is:", result)


				
			

output

				
					Enter a non-negative integer: 34
The factorial of 34 is: 295232799039604140847618609643520000000


				
			

Arrays

1) Write a Python program to create an array of 5 integers and display the array items. 

Access individual element through indexes

				
					import array as arr

# Create an array of 5 integers
numbers = arr.array('i', [10, 20, 30, 40, 50])

# Display the array items
print("Array items:", numbers)

# Access individual elements through indexes
print("Element at index 0:", numbers[0])
print("Element at index 1:", numbers[1])
print("Element at index 2:", numbers[2])
print("Element at index 3:", numbers[3])
print("Element at index 4:", numbers[4])

				
			

output

				
					Array items: array('i', [10, 20, 30, 40, 50])
Element at index 0: 10
Element at index 1: 20
Element at index 2: 30
Element at index 3: 40
Element at index 4: 50

				
			

2) Write a Python program to append a new item to the end of the array

				
					import array as arr

# Create an array of integers
numbers = arr.array('i', [10, 20, 30, 40, 50])

# Append a new item to the end of the array
new_item = 60
numbers.append(new_item)

# Display the updated array
print("Updated array:", numbers)


				
			

output

				
					Updated array: array('i', [10, 20, 30, 40, 50, 60])

				
			

3) Write a Python program to append items from a specified list.

				
					import array as arr

# Create an array of integers
numbers = arr.array('i', [10, 20, 30, 40, 50])

# Create a list of numbers to append
new_items = [60, 70, 80]

# Append items from the list to the array
numbers.extend(new_items)

# Display the updated array
print("Updated array:", numbers)


				
			

output

				
					Updated array: array('i', [10, 20, 30, 40, 50, 60, 70, 80])
				
			

4) Write a Python program to insert a new item before the second element in an existing
array.

				
					import array as arr

# Create an array of integers
numbers = arr.array('i', [10, 20, 30, 40, 50])

# Define the new item to be inserted
new_item = 15

# Insert the new item before the second element
numbers.insert(1, new_item)

# Display the updated array
print("Updated array:", numbers)

				
			

output

				
					Updated array: array('i', [10, 15, 20, 30, 40, 50])
				
			

5) Write a Python program to reverse the order of the items in the array.

				
					import array as arr

# Create an array of integers
numbers = arr.array('i', [10, 20, 30, 40, 50])

# Reverse the order of items in the array
numbers.reverse()

# Display the reversed array
print("Reversed array:", numbers)


				
			

output

				
					Reversed array: array('i', [50, 40, 30, 20, 10])

				
			

6) Write a Python program to get the number of occurrences of a specified element in an 

array. 

				
					import array as arr

# Create an array of integers
numbers = arr.array('i', [10, 20, 30, 20, 40, 20, 50])

# Specify the element to count
specified_element = 20

# Count the number of occurrences of the specified element
count = numbers.count(specified_element)

# Display the count
print("Number of occurrences of", specified_element, "in the array:", count)


				
			

output

				
					Number of occurrences of 20 in the array: 3
				
			

7) Write a Python program to remove the first occurrence of a specified element from an 

array.

				
					import array as arr

# Create an array of integers
numbers = arr.array('i', [10, 20, 30, 20, 40, 20, 50])

# Specify the element to remove
specified_element = 20

# Remove the first occurrence of the specified element
numbers.remove(specified_element)

# Display the updated array
print("Updated array:", numbers)



				
			

output

				
					Number of occurrences of 20 in the array: 3
				
			

Strings

1) Write a python program to check whether the string is Symmetrical or Palindrome

				
					def is_symmetrical(string):
    # Check if the string is symmetrical
    if string == string[::-1]:
        return True
    else:
        return False

# Test the program
word = input("Enter a word: ")

if is_symmetrical(word):
    print("The string is symmetrical.")
else:
    print("The string is not symmetrical.")

				
			

output

				
					Enter a word: coding
The string is not symmetrical.

				
			

2) Write a python program to Reverse words in a given String

				
					def reverse_words(string):
    # Split the string into words
    words = string.split()

    # Reverse the order of words
    reversed_words = words[::-1]

    # Join the reversed words back into a string
    reversed_string = ' '.join(reversed_words)

    return reversed_string

# Test the program
sentence = input("Enter a sentence: ")

reversed_sentence = reverse_words(sentence)
print("Reversed words in the string:", reversed_sentence)


				
			

output

				
					Enter a sentence: coding is good
Reversed words in the string: good is coding



				
			

3) Write a python program to remove i’th character from string in different ways

				
					
def word_frequency(string):
    words = string.split()
    word_counts = Counter(words)
    return word_counts

# Test the program
sentence = input("Enter a sentence: ")

frequency = word_frequency(sentence)
print("Word Frequency:")
print("\n".join(f"{word}: {count}" for word, count in frequency.items()))


				
			

output

				
					Enter a sentence: goku love coding and goku love games
Word Frequency:
goku: 2
love: 2
coding: 1
and: 1
games: 1

				
			

4) Write a python program Convert Snake case to Pascal case

				
					def snake_to_pascal(snake_case):
    words = snake_case.split('_')
    pascal_case = ''.join(word.capitalize() for word in words)
    return pascal_case

# Test the program
snake_case_string = input("Enter a string in snake case: ")

pascal_case_string = snake_to_pascal(snake_case_string)
print("Pascal case string:", pascal_case_string)


				
			

output

				
					Enter a string in snake case: 34
Pascal case string: 34

				
			

5) Write a python program to print even length words in a string

				
					def print_even_length_words(input_string):
    words = input_string.split()
    even_length_words = [word for word in words if len(word) % 2 == 0]
    
    for word in even_length_words:
        print(word)

if __name__ == "__main__":
    input_string = input("Enter a string: ")
    print("Even length words in the string:")
    print_even_length_words(input_string)

				
			

output

 

				
					Enter a string: 33
Even length words in the string:
33
				
			

6) Write a python program to accept the strings which contains all vowels

				
					def contains_all_vowels(string):
    vowels = ['a', 'e', 'i', 'o', 'u']
    for vowel in vowels:
        if vowel not in string.lower():
            return False
    return True

# Test the program
word = input("Enter a word: ")

if contains_all_vowels(word):
    print("The word contains all vowels.")
else:
    print("The word does not contain all vowels.")


				
			

output

 

				
					Enter a word: lucifer
The word does not contain all vowels.

				
			

Functions

1) Write a Python function to find the Max of three numbers

				
					def find_max(a, b, c):
    return max(a, b, c)

# Test the function
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
num3 = int(input("Enter the third number: "))

maximum = find_max(num1, num2, num3)
print("The maximum of the three numbers is:", maximum)


				
			

output

				
					Enter the first number: 3
Enter the second number: 4
Enter the third number: 1
The maximum of the three numbers is: 4

				
			

2) Write a Python program to reverse a string.

				
					def reverse_string(string):
    return string[::-1]

# Test the function
sentence = input("Enter a string: ")

reversed_sentence = reverse_string(sentence)
print("Reversed string:", reversed_sentence)


				
			

output

				
					Enter a string: 34
Reversed string: 43

				
			

3) Write a Python function to calculate the factorial of a number (a non-negative
integer). The function accepts the number as an argument.

				
					 def factorial(num):
    if num == 0:
        return 1
    else:
        return num * factorial(num - 1)

# Test the function
number = int(input("Enter a non-negative integer: "))

if number < 0:
    print("Please enter a non-negative integer.")
else:
    result = factorial(number)
    print("Factorial of", number, "is:", result)


				
			

output

				
					Enter a non-negative integer: 34
Factorial of 34 is: 295232799039604140847618609643520000000


				
			

4) Write a Python function that accepts a string and calculate the number of upper case
letters and lower case letters.

				
					def count_letters(string):
    uppercase_count = 0
    lowercase_count = 0

    for char in string:
        if char.isupper():
            uppercase_count += 1
        elif char.islower():
            lowercase_count += 1

    return uppercase_count, lowercase_count

# Test the function
sentence = input("Enter a string: ")

uppercase, lowercase = count_letters(sentence)
print("Number of uppercase letters:", uppercase)
print("Number of lowercase letters:", lowercase)


				
			

output

				
					Enter a string: 23
Number of uppercase letters: 0
Number of lowercase letters: 0

				
			

5) Write a Python function that checks whether a passed string is palindrome or not.

				
					def is_palindrome(string):
    reversed_string = string[::-1]
    return string == reversed_string

# Test the function
word = input("Enter a word: ")

if is_palindrome(word):
    print("The word is a palindrome.")
else:
    print("The word is not a palindrome.")

				
			

output

				
					Enter a word: goke
The word is not a palindrome.

				
			

6) Write a Python program to access a function inside a function

				
					def outer_function():
    print("This is the outer function.")

    def inner_function():
        print("This is the inner function.")

    inner_function()

# Call the outer function
outer_function()

				
			

output

				
					This is the outer function.
This is the inner function.

				
			

7) Write a Python program to detect the number of local variables declared in a function.

				
					def example_function():
    variable1 = 10
    variable2 = "Hello"
    variable3 = True

    local_variables = locals()
    count = len(local_variables)

    return count

# Test the function
result = example_function()
print("Number of local variables:", result)


				
			

output

				
					
Number of local variables: 3

				
			

List

1) Write a Python program to sum all the items in a list.

				
					def sum_list(numbers):
    total = sum(numbers)
    return total

# Test the program
num_list = [1, 2, 3, 4, 5]

result = sum_list(num_list)
print("Sum of the list:", result)

				
			

output

				
					Sum of the list: 15 
				
			

2) Write a Python program to multiplies all the items in a list

				
					def multiply_list(numbers):
    product = 1
    for num in numbers:
        product *= num
    return product

# Test the program
num_list = [1, 2, 3, 4, 5]

result = multiply_list(num_list)
print("Product of the list:", result)


				
			

output

				
					Product of the list: 120
				
			

3) Write a Python program to get the largest number from a list.

				
					def get_largest(numbers):
    largest = max(numbers)
    return largest

# Test the program
num_list = [10, 5, 20, 15, 30]

result = get_largest(num_list)
print("Largest number:", result)

				
			

output

				
					Largest number: 30
				
			

4) Write a Python program to get the smallest number from a list

				
					def get_smallest(numbers):
    smallest = min(numbers)
    return smallest

# Test the program
num_list = [10, 5, 20, 15, 30]

result = get_smallest(num_list)
print("Smallest number:", result)

				
			

output

				
					Smallest number: 5
				
			

5) Write a Python program to count the number of strings where the string length is 2 or
more and the first and last character are same from a given list of strings.

				
					def count_strings(strings):
    count = 0
    for string in strings:
        if len(string) >= 2 and string[0] == string[-1]:
            count += 1
    return count

# Test the program
string_list = ["wow", "hello", "python", "level", "radar"]

result = count_strings(string_list)
print("Count of strings:", result)


				
			

output

 

				
					Count of strings: 3
				
			

6) Write a Python program to get a list, sorted in increasing order by the last element in
each tuple from a given list of non-empty tuples

				
					def sort_tuples(tuples):
    sorted_list = sorted(tuples, key=lambda x: x[-1])
    return sorted_list

# Test the program
tuple_list = [(2, 4), (1, 3), (5, 1), (3, 2)]

result = sort_tuples(tuple_list)
print("Sorted list:", result)

				
			

output

				
					Sorted list: [(5, 1), (3, 2), (1, 3), (2, 4)]
				
			

7) Write a Python program to remove duplicates from a list.

				
					def remove_duplicates(numbers):
    unique_list = list(set(numbers))
    return unique_list

# Test the program
num_list = [1, 2, 3, 2, 4, 5, 3, 1]

result = remove_duplicates(num_list)
print("List with duplicates removed:", result)


				
			

output

				
					Sorted list: [(5, 1), (3, 2), (1, 3), (2, 4)]
				
			

File Handling

1) Write a Python program to read an entire text file.

				
					def read_file(file_path):
    try:
        with open(file_path, 'r') as file:
            content = file.read()
            return content
    except FileNotFoundError:
        return "File not found."

# Test the program
file_path = input("Enter the file path: ")

file_content = read_file(file_path)
print("File content:")
print(file_content)

				
			

output

				
					Enter the file path: goku:
Lucifer

				
			

2) Write a Python program to read first or last n lines of a file.

				
					def read_lines(file_path, n, from_start=True):
    try:
        with open(file_path, 'r') as file:
            lines = file.readlines()
            if from_start:
                selected_lines = lines[:n]
            else:
                selected_lines = lines[-n:]
            return selected_lines
    except FileNotFoundError:
        return "File not found."

# Test the program
file_path = input("Enter the file path: ")
n = int(input("Enter the number of lines to read: "))
from_start = input("Read from start? (y/n): ").lower() == 'y'

lines = read_lines(file_path, n, from_start)
print("Selected lines:")
for line in lines:
    print(line.strip())

				
			

output

				
					Enter the file path: goku
Enter the number of lines to read: 1
Read from start? (y/n): y
Selected lines:
lucifer

				
			

3) Write a Python program to append text to a file and display the text

				
					def append_to_file(file_path, text):
    try:
        with open(file_path, 'a') as file:
            file.write(text)
        return "Text appended successfully."
    except FileNotFoundError:
        return "File not found."

# Test the program
file_path = input("Enter the file path: ")
text = input("Enter the text to append: ")

result = append_to_file(file_path, text)
print(result)

				
			

output

				
					Enter the file path: goku
Enter the number of lines to read: 1
Read from start? (y/n): y
Selected lines:
lucifer

				
			

4) Write a Python program to read a file line by line and store it into a list.

				
					def read_file_lines(file_path):
    try:
        with open(file_path, 'r') as file:
            lines = file.readlines()
            return lines
    except FileNotFoundError:
        return "File not found."

# Test the program
file_path = input("Enter the file path: ")

lines = read_file_lines(file_path)
print("Lines stored in a list:")
for line in lines:
    print(line.strip())


				
			

output

				
					Enter the file path: goku
Lines stored in a list:
lucifer

				
			

5) Write a Python program to read a file line by line store it into a variable

				
					def read_file_into_variable(file_path):
    try:
        with open(file_path, 'r') as file:
            content = file.read()
            return content
    except FileNotFoundError:
        return "File not found."

# Test the program
file_path = input("Enter the file path: ")

file_content = read_file_into_variable(file_path)
print("File content stored in a variable:")
print(file_content)


				
			

output

				
					Enter the file path: tech
File content stored in a variable:
lucifer

				
			

6) Write a Python program to count the number of lines in a text file

				
					def count_lines(file_path):
    try:
        with open(file_path, 'r') as file:
            lines = file.readlines()
            return len(lines)
    except FileNotFoundError:
        return "File not found."

# Test the program
file_path = input("Enter the file path: ")

line_count = count_lines(file_path)
print("Number of lines in the file:", line_count)

				
			

output

				
					Enter the file path: tech
Number of lines in the file: 1

				
			

7) Write a Python program to copy the contents of a file to another file .

				
					def copy_file(source_path, destination_path):
    try:
        with open(source_path, 'r') as source_file:
            content = source_file.read()
        with open(destination_path, 'w') as destination_file:
            destination_file.write(content)
        return "File copied successfully."
    except FileNotFoundError:
        return "File not found."

# Test the program
source_path = input("Enter the path of the source file: ")
destination_path = input("Enter the path of the destination file: ")

result = copy_file(source_path, destination_path)
print(result)

				
			

output

				
					
Enter the path of the source file: tech
Enter the path of the destination file: python
File copied successfully.

				
			

Classes and Objects (OOP)

1) Write a Python program to demonstrate working of classes and objects.

				
					class Car:
    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year

    def display_info(self):
        print(f"Car: {self.make} {self.model} {self.year}")

# Create an object of the Car class
my_car = Car("Toyota", "Corolla", 2022)

# Access and display object attributes
print("Car details:")
print("Make:", my_car.make)
print("Model:", my_car.model)
print("Year:", my_car.year)

# Call a method on the object
my_car.display_info()

				
			

output

				
					Car details:
Make: Toyota
Model: Corolla
Year: 2022
Car: Toyota Corolla 2022

				
			

2) Write a Python program to demonstrate class method & static method. 

				
					class MathUtils:
    @classmethod
    def add(cls, x, y):
        return x + y

    @staticmethod
    def multiply(x, y):
        return x * y

# Call the class method directly
result1 = MathUtils.add(5, 3)
print("Class method result:", result1)

# Call the static method directly
result2 = MathUtils.multiply(5, 3)
print("Static method result:", result2)


				
			

output

				
					Class method result: 8
Static method result: 15

				
			

3) Write a Python program to demonstrate constructors

				
					class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def display_info(self):
        print(f"Person: {self.name} ({self.age} years old)")

# Create objects of the Person class
person1 = Person("Alice", 25)
person2 = Person("Bob", 30)

# Call the method on each object
person1.display_info()
person2.display_info()


				
			

output

				
					Person: Alice (25 years old)
Person: Bob (30 years old)

				
			

4) Write a Python program to import built-in array module and display the namespace of
the said module.

				
					import array

# Display the namespace of the array module
print("Namespace of the array module:")
print(dir(array))




				
			

output

				
					
Namespace of the array module:
['ArrayType', '__doc__', '__loader__', '__name__', '__package__', '__spec__', '_array_reconstructor', 'array', 'typecodes']



				
			

5) Write a Python program to demonstrate inheritance

				
					class Animal:
    def __init__(self, name):
        self.name = name

    def make_sound(self):
        pass

class Dog(Animal):
    def make_sound(self):
        print(f"{self.name} barks")

class Cat(Animal):
    def make_sound(self):
        print(f"{self.name} meows")

# Create objects of the derived classes
dog = Dog("Buddy")
cat = Cat("Whiskers")

# Call the method on each object
dog.make_sound()
cat.make_sound()

				
			

output

				
					Buddy barks
Whiskers meows

				
			

6) Write a Python program to demonstrate aggregation/compositions

				
					class Engine:
    def start(self):
        print("Engine started")

class Car:
    def __init__(self):
        self.engine = Engine()

    def start_car(self):
        self.engine.start()

# Create an object of the Car class
my_car = Car()

# Start the car
my_car.start_car()

				
			

output

				
					Engine started

				
			

7) Write a Python function student_data () which will print the id of a student
(student_id). If the user passes an argument student_name or student_class the
function will print the student name and class.

				
					def student_data(student_id, student_name=None, student_class=None):
    print("Student ID:", student_id)
    if student_name:
        print("Student Name:", student_name)
    if student_class:
        print("Student Class:", student_class)

# Call the function with different arguments
student_data(123)
student_data(456, "Alice")
student_data(789, "Bob", "Grade 10")

				
			

output

				
					Student ID: 123
Student ID: 456
Student Name: Alice
Student ID: 789
Student Name: Bob
Student Class: Grade 10

				
			

8) Write a Python class named Rectangle constructed by a length and width and a
method which will compute the area of a rectangle.

				
					class Rectangle:
    def __init__(self, length, width):
        self.length = length
        self.width = width

    def compute_area(self):
        return self.length * self.width

# Create an object of the Rectangle class
rectangle = Rectangle(5, 3)

# Compute and display the area
area = rectangle.compute_area()
print("Area of the rectangle:", area)


				
			

output

				
					Area of the rectangle: 15
				
			

9) Write a Python class named Circle constructed by a radius and two methods which
will compute the area and the perimeter of a circle.

				
					import math

class Circle:
    def __init__(self, radius):
        self.radius = radius

    def compute_area(self):
        return math.pi * self.radius ** 2

    def compute_perimeter(self):
        return 2 * math.pi * self.radius

# Create an object of the Circle class
circle = Circle(5)

# Compute and display the area and perimeter
area = circle.compute_area()
perimeter = circle.compute_perimeter()
print("Area of the circle:", area)
print("Perimeter of the circle:", perimeter)

				
			

output

				
					Area of the circle: 78.53981633974483
Perimeter of the circle: 31.41592653589793

				
			

10) Write a Python class named Student with two attributes student_id, student_name.
Add a new attribute student_class. Create a function to display the entire attribute and
their values in Student class

				
					class Student:
    def __init__(self, student_id, student_name):
        self.student_id = student_id
        self.student_name = student_name
        self.student_class = ""

    def display_attributes(self):
        print("Student ID:", self.student_id)
        print("Student Name:", self.student_name)
        print("Student Class:", self.student_class)

# Create an object of the Student class
student = Student(123, "Alice")

# Set the class attribute
student.student_class = "Grade 10"

# Call the method to display the attributes
student.display_attributes()

				
			

output

				
					Student ID: 123
Student Name: Alice
Student Class: Grade 10

				
			

Exception handling

1) Assertions in Python

				
					# Example 1: Simple assertion
x = 5
assert x > 0, "x should be positive"

# Example 2: Assertion with error message and multiple conditions
y = 10
assert y % 2 == 0, "y should be an even number"
assert y > 0 and y < 100, "y should be in the range (0, 100)"


				
			

output

				
					Process finished with exit code 0

				
			

2) The except Clause with No Exceptions

				
					try:
    # Some code that may raise an exception
    result = 10 / 0
except:
    # Exception handling code
    print("An error occurred")

				
			

output

				
					An error occurred

				
			

3) The except Clause with Multiple Exceptions

				
					try:
    # Some code that may raise exceptions
    result = int("abc") + 10
except ValueError:
    # Exception handling for ValueError
    print("Invalid value")
except ZeroDivisionError:
    # Exception handling for ZeroDivisionError
    print("Cannot divide by zero")
except Exception:
    # Generic exception handling
    print("An error occurred")

				
			

output

				
					Invalid value
				
			

5) Argument of an Exception

				
					try:
    # Some code that may raise an exception
    age = int(input("Enter your age: "))
    if age < 0:
        raise ValueError("Age cannot be negative")
except ValueError as error:
    # Exception handling with the error message
    print("Error:", str(error))

				
			

output

				
					Enter your age: -22
Error: Age cannot be negative


				
			

6) User-Defined Exceptions

				
					class CustomException(Exception):
    def __init__(self, message):
        self.message = message

try:
    # Some code that may raise a custom exception
    raise CustomException("This is a custom exception")
except CustomException as error:
    # Handling the custom exception
    print("Custom Exception:", str(error))

				
			

output

				
					Custom Exception: This is a custom exception

				
			

7) Raising Exception

				
					def divide(x, y):
    if y == 0:
        raise ZeroDivisionError("Cannot divide by zero")
    return x / y

try:
    # Some code that may raise an exception
    result = divide(10, 0)
except ZeroDivisionError as error:
    # Handling the raised exception
    print("Error:", str(error))

				
			

output

				
					Error: Cannot divide by zero
				
			

Regular expression

1) Write a python program to Check if String Contain Only Defined Characters using
Regex

				
					import re

def contains_only_defined_chars(string, defined_chars):
    pattern = f'^[{defined_chars}]+$'
    if re.match(pattern, string):
        return True
    return False

# Test the program
string = input("Enter a string: ")
defined_chars = input("Enter the defined characters: ")

if contains_only_defined_chars(string, defined_chars):
    print("String contains only defined characters.")
else:
    print("String contains other characters as well.")


				
			

output

				
					Enter a string: 334
Enter the defined characters: 134
String contains only defined characters.

				
			

2) Write a python program to find the most occurring number in a string using Regex

				
					import re
from collections import Counter

def most_occurring_number(string):
    numbers = re.findall(r'\d+', string)
    if numbers:
        count = Counter(numbers)
        most_common = count.most_common(1)
        return most_common[0][0]
    return "No numbers found in the string."

# Test the program
string = input("Enter a string: ")

result = most_occurring_number(string)
print("Most occurring number:", result)

				
			

output

				
					Enter a string: peter1 peter2 
Most occurring number: 1
				
			

3) Write a python Regex to extract maximum numeric value from a string

				
					import re

def extract_max_numeric_value(string):
    numbers = re.findall(r'\d+', string)
    if numbers:
        max_number = max(map(int, numbers))
        return max_number
    return "No numbers found in the string."

# Test the program
string = input("Enter a string: ")

result = extract_max_numeric_value(string)
print("Maximum numeric value:", result)


				
			

output

				
					Enter a string: peter parker 1
Maximum numeric value: 1

				
			

4) Write a python to Check whether a string starts and ends with the same character or
not

				
					import re

def starts_ends_same_char(string):
    pattern = r'^(.).*\1$'
    if re.match(pattern, string):
        return True
    return False

# Test the program
string = input("Enter a string: ")

if starts_ends_same_char(string):
    print("String starts and ends with the same character.")
else:
    print("String does not start and end with the same character.")

				
			

output

				
					Enter a string: peter p
String starts and ends with the same character.
				
			

5) Write a python Program to check if a string starts with a substring using regex

				
					import re

def starts_with_substring(string, substring):
    pattern = f'^{re.escape(substring)}'
    if re.match(pattern, string):
        return True
    return False

# Test the program
string = input("Enter a string: ")
substring = input("Enter the substring to check: ")

if starts_with_substring(string, substring):
    print("String starts with the substring.")
else:
    print("String does not start with the substring.")


				
			

output

				
					Enter a string: 54
Enter the substring to check: 23
String does not start with the substring.

				
			

6) Write a python Program to Check if an URL is valid or not using Regular Expression

				
					import re

def is_valid_url(url):
    pattern = r'^(http|https)://[^\s/$.?#].[^\s]*$'
    if re.match(pattern, url):
        return True
    return False

# Test the program
url = input("Enter a URL: ")

if is_valid_url(url):
    print("URL is valid.")
else:
    print("URL is not valid.")

				
			

output

				
					Enter a URL: http:goku
URL is not valid.

				
			

7) Write a python Program to Parsing and Processing URL using Python – Regex

				
					import re

def parse_and_process_url(url):
    pattern = r'^(?Phttp|https)://(?P[^\s/$.?#].[^\s]*)/(?P[^\s]*)\?(?P[^\s]*)#(?P[^\s]*)$'
    match = re.match(pattern, url)
    if match:
        groups = match.groupdict()
        print("Parsed URL:")
        print("Protocol:", groups['protocol'])
        print("Domain:", groups['domain'])
        print("Path:", groups['path'])
        print("Query:", groups['query'])
        print("Fragment:", groups['fragment'])
    else:
        print("Invalid URL format.")

# Test the program
url = input("Enter a URL: ")

parse_and_process_url(url)

				
			

output

 

				
					Enter a URL: https://docs.google.com/document/d/1Zw285RtO5X58UnjpubQw-8O28ZmwdGbo8wqFJoMfnvk/edit
Invalid URL format.

				
			

Date-Time

1) Write a python program to get Current Time

				
					import datetime

current_time = datetime.datetime.now().time()
print("Current time:", current_time)




				
			

output

				
					
Current time: 12:22:26.073195
2) Get Current Date and Time using Python
				
			

2) Get Current Date and Time using Python

				
					import datetime

current_datetime = datetime.datetime.now()
print("Current date and time:", current_datetime)


				
			

output

				
					Current date and time: 2023-07-14 12:23:01.597904
				
			

3) Write a python to Find yesterday’s, today’s and tomorrow’s date

				
					import datetime

today = datetime.date.today()
yesterday = today - datetime.timedelta(days=1)
tomorrow = today + datetime.timedelta(days=1)

print("Yesterday's date:", yesterday)
print("Today's date:", today)
print("Tomorrow's date:", tomo

				
			

output

				
					Yesterday's date: 2023-07-13
Today's date: 2023-07-14
Tomorrow's date: 2023-07-15

				
			

4) Write a python program to convert time from 12 hour to 24 hour format

				
					import datetime

time_12hour = input("Enter the time in 12-hour format (HH:MM AM/PM): ")
time_24hour = datetime.datetime.strptime(time_12hour, "%I:%M %p").strftime("%H:%M")

print("Time in 24-hour format:", time_24hour)


				
			

output

				
					Enter the time in 12-hour format (HH:MM AM/PM): 03:43 pm
Time in 24-hour format: 15:43

				
			

5) Write a python program to find difference between current time and given time

				
					import datetime

current_time = datetime.datetime.now().time()
given_time_str = input("Enter a time (HH:MM): ")
given_time = datetime.datetime.strptime(given_time_str, "%H:%M").time()

time_diff = datetime.datetime.combine(datetime.date.today(), current_time) - datetime.datetime.combine(datetime.date.today(), given_time)
print("Time difference:", time_diff)

				
			

output

				
					Enter a time (HH:MM): 03:34
Time difference: 8:52:46.451583

				
			

6) Write a python Program to Create a Lap Timer

				
					import time

def lap_timer():
    start_time = time.time()
    while True:
        input("Press Enter to lap.")
        lap_time = time.time() - start_time
        print("Lap time:", lap_time)
        start_time = time.time()

# Start the lap timer
lap_timer()


				
			

output

				
					Press Enter to lap.
Lap time: 4.239608287811279
Press Enter to lap.


				
			

7) Find number of times every day occurs in a Year

				
					import datetime
import calendar

def count_days_in_year(year):
    days_count = {}
    for month in range(1, 13):
        for day in range(1, calendar.monthrange(year, month)[1] + 1):
            date = datetime.date(year, month, day)
            day_name = date.strftime("%A")
            if day_name in days_count:
                days_count[day_name] += 1
            else:
                days_count[day_name] = 1
    return days_count

# Test the program
year = int(input("Enter a year: "))

days_count = count_days_in_year(year)
print("Occurrences of each day in the year:")
for day, count in days_count.items():
    print(day + ":", count)

				
			

output

				
					Enter a year: 2002
Occurrences of each day in the year:
Tuesday: 53
Wednesday: 52
Thursday: 52
Friday: 52
Saturday: 52
Sunday: 52
Monday: 52

				
			

Tuples

1) Write a Python program to create a tuple.

				
					my_tuple = ()
print("Empty tuple:", my_tuple)

my_tuple = (1, 2, 3)
print("Tuple with elements:", my_tuple)

				
			

output

				
					Empty tuple: ()
Tuple with elements: (1, 2, 3)

				
			

2) Write a Python program to create a tuple with different data types.

				
					my_tuple = (1, "Hello", 3.14, True)
print("Tuple with different data types:", my_tuple)


				
			

output

				
					Tuple with different data types: (1, 'Hello', 3.14, True)

				
			

3) Write a Python program to convert a tuple to a string.

				
					my_tuple = ("H", "e", "l", "l", "o")
string = "".join(my_tuple)
print("Tuple converted to string:", string)

				
			

output

				
					Tuple converted to string: Hello

				
			

4) Write a Python program to convert a list to a tuple.

				
					my_list = [1, 2, 3, 4, 5]
my_tuple = tuple(my_list)
print("List converted to tuple:", my_tuple)


				
			

output

				
					List converted to tuple: (1, 2, 3, 4, 5)
				
			

5) Write a Python program to remove an item from a tuple.

				
					my_tuple = (1, 2, 3, 4, 5)
element_to_remove = 3

if element_to_remove in my_tuple:
    new_tuple = tuple(element for element in my_tuple if element != element_to_remove)
    print("Tuple with the item removed:", new_tuple)
else:
    print("Item not found in the tuple.")


				
			

output

				
					Tuple with the item removed: (1, 2, 4, 5) 

				
			

6) Write a Python program to slice a tuple

				
					my_tuple = (1, 2, 3, 4, 5)
start_index = 1
end_index = 4

sliced_tuple = my_tuple[start_index:end_index]
print("Sliced tuple:", sliced_tuple)

				
			

output

				
					Sliced tuple: (2, 3, 4)

				
			

7) Write a Python program to reverse a tuple.

				
					my_tuple = (1, 2, 3, 4, 5)
reversed_tuple = tuple(reversed(my_tuple))
print("Reversed tuple:", reversed_tuple)

				
			

output

				
					Reversed tuple: (5, 4, 3, 2, 1)
				
			

Sets

1) Write a Python program to create a set

				
					my_set = set()
print("Empty set:", my_set)

my_set = {1, 2, 3}
print("Set with elements:", my_set)


				
			

output

				
					Empty set: set()
Set with elements: {1, 2, 3}

				
			

2) Write a Python program to iterate over sets.

				
					my_set = {1, 2, 3, 4, 5}
print("Elements in the set:")
for element in my_set:
    print(element)

				
			

output

				
					Elements in the set:
1
2
3
4
5

				
			

3) Write a Python program to add and remove member(s) in a set.

				
					my_set = {1, 2, 3}
print("Initial set:", my_set)

my_set.add(4)
print("Set after adding 4:", my_set)

my_set.remove(2)
print("Set after removing 2:", my_set)

				
			

output

				
					Initial set: {1, 2, 3}
Set after adding 4: {1, 2, 3, 4}
Set after removing 2: {1, 3, 4}

				
			

4) Write a Python program to create an intersection of sets.

				
					set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}

intersection = set1.intersection(set2)
print("Intersection of set1 and set2:", intersection)

				
			

output

				
					Intersection of set1 and set2: {3, 4}
				
			

5) Write a Python program to create a union and difference of sets.

				
					set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}

union = set1.union(set2)
print("Union of set1 and set2:", union)

difference = set1.difference(set2)
print("Difference of set1 and set2:", difference)

				
			

output

				
					Union of set1 and set2: {1, 2, 3, 4, 5, 6}
Difference of set1 and set2: {1, 2}

				
			

6) Write a Python program to create a symmetric difference.

				
					set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}

symmetric_difference = set1.symmetric_difference(set2)
print("Symmetric difference of set1 and set2:", symmetric_difference)

				
			

output

				
					Symmetric difference of set1 and set2: {1, 2, 5, 6}

				
			

7) Write a Python program to check if a set is a subset of another set.

				
					set1 = {1, 2, 3, 4}
set2 = {1, 2}

if set2.issubset(set1):
    print("set2 is a subset of set1.")
else:
    print("set2 is not a subset of set1.")

				
			

output

				
					set2 is a subset of set1.

				
			
Tech Amplifier Final Logo