Skip to main content

PYTHON ASSIGNMENT 5 AND 6 SOLVED

 PYTHON 


ASSIGNMENT – 5

1>What is string concatenation? Explain different ways to concatenate strings.

ANS>>


String concatenation is the process of combining two or more strings into a single string. In programming, it is a commonly used operation for manipulating text data.

There are different ways to concatenate strings depending on the programming language or framework being used. Here are some examples:

  1. Using the plus (+) operator: In many programming languages, the simplest way to concatenate strings is by using the plus (+) operator. This is also known as the concatenation operator. Here's an example in Python:


string1 = "Hello"

string2 = "World"

result = string1 + " " + string2

print(result)



OUTPUT:

Hello World



2.Using the join() method: Another way to concatenate strings is by using the join() method. This method takes an iterable (such as a list or tuple) of strings as an argument and concatenates them with a separator string. Here's an example in JavaScript:


    var words = ["Hello", "World"];

var result = words.join(" ");

console.log(result);



OUTPUT:

Hello World



3.Using the format() method: In some programming languages, such as Python, the format() method can be used to concatenate strings. This method allows you to substitute placeholders in a string with values. Here's an example:



name = "John"

age = 25

result = "My name is {} and I am {} years old".format(name, age)

print(result)




OUTPUT

My name is John and I am 25 years ol



4.  Using template literals: In modern JavaScript, you can use template literals to concatenate strings. Template literals are enclosed in backticks (`) and allow you to embed variables directly into the string using ${}. Here's an example:


let name = "John";

let age = 25;

let result = `My name is ${name} and I am ${age} years old`;

console.log(result);



OUTPUT:

My name is John and I am 25 years old




2>>.Write a program to check if a string is palindrome.

ANS—>


To check if a string is palindrome, we need to check if the string is the same when read from left to right as it is when read from right to left. Here's a program in Python that checks if a string is palindrome:




def is_palindrome(s):

    """

    Checks if a string is palindrome.

    """

    # Convert the string to lowercase and remove spaces

    s = s.lower().replace(" ", "")

    # Check if the string is the same when read from left to right

    # as it is when read from right to left

    return s == s[::-1]


# Test the function

print(is_palindrome("racecar"))  # True

print(is_palindrome("hello"))  # False

print(is_palindrome("A man a plan a canal Panama"))  # True





Explanation:

  1. The is_palindrome() function takes a string s as input.
  2. The first line of the function converts the string to lowercase and removes spaces. This step is optional, but it makes the function case-insensitive and ignores spaces.
  3. The second line of the function uses slicing to check if the string is the same when read from left to right as it is when read from right to left. The syntax [::1] means to slice the string from the beginning to the end, with a step of -1, which means to read the string from right to left.
  4. The function returns True if the string is palindrome, and False otherwise.
  5. The last part of the program tests the function with some examples.




OUTPUT:



True

False

True





Note that the function ignores spaces and is case-insensitive. If you want to include spaces and be case-sensitive, you can remove the line that removes spaces and use s == s[::-1] instead of s.lower() == s.lower()[::-1].





3>>List the inbuilt method of strings. Explain any 4 of them with examples.

ANS——>



Python provides a number of built-in methods for strings. These methods can be used to perform various operations on strings, such as manipulating, formatting, and searching. Here are some of the most commonly used string methods:



1>len(): This method returns the length of the string. Here's an example:

s = "Hello, World!"

print(len(s))  # Output: 13



2>lower(): This method returns a copy of the string with all the characters converted to lowercase. Here's an example:

s = "Hello, World!"

print(s.lower())  # Output: hello, world!



3>upper(): This method returns a copy of the string with all the characters converted to uppercase. Here's an example

s = "Hello, World!"

print(s.upper())  # Output: HELLO, WORLD!




4>replace(): This method returns a copy of the string with all occurrences of a substring replaced with another substring. Here's an example:

s = "Hello, World!"

print(s.replace("Hello", "Hi"))  # Output: Hi, World!



5>strip(): This method returns a copy of the string with leading and trailing whitespace characters removed. Here's an example:

s = "   Hello, World!   "

print(s.strip())  # Output: Hello, World!


6> split(): This method returns a list of substrings separated by a specified delimiter. Here's an example:

s = "Hello, World!"

print(s.split(","))  # Output: ['Hello', ' World!']


7>join(): This method returns a string by joining the elements of an iterable with a specified separator. Here's an example

words = ["Hello", "World"]

separator = " "

s = separator.join(words)

print(s)  # Output: Hello World



8>startswith(): This method returns True if the string starts with a specified prefix, and False otherwise. Here's an example:

s = "Hello, World!"

print(s.startswith("Hello"))  # Output: True




9>endswith(): This method returns True if the string ends with a specified suffix, and False otherwise. Here's an example:

s = "Hello, World!"

print(s.endswith("World!"))  # Output: True




4>.What do you mean by Escape sequence?

ANS——>



In Python, an escape sequence is a combination of characters that represents a special character, such as a newline or a tab, that cannot be directly entered into a string. Escape sequences are used to represent characters that cannot be typed as literal characters in a string. They are composed of a backslash (\) followed by one or more characters.

Here are some common escape sequences in Python:

  • \n: newline
  • \t: tab
  • \\: backslash
  • \': single quote
  • \": double quote


For example, suppose we want to include a newline character in a string. We cannot simply press the Enter key to create a new line, because that would end the string. Instead, we can use the escape sequence \n to represent the newline character, like this:


s = "Hello,\nWorld!"

print(s)



OUTPUT:

Hello,

World!




The escape sequence \n represents a newline character, which causes the second part of the string to be printed on a new line.

Similarly, we can use the escape sequence \t to represent a tab character, like this:




s = "Name:\tJohn"

print(s)


OUTPUT:

Name:   John





The escape sequence \t represents a tab character, which causes the string "John" to be printed after a tab character.

Escape sequences are useful for formatting strings and making them more readable. They allow us to include special characters in strings that cannot be typed directly.



5>.Strings are immutable. Explain.

ANS——>



In Python, strings are immutable, which means that once a string object is created, its contents cannot be changed. Immutable objects are objects whose state cannot be modified after they are created. This means that any operation that modifies a string, such as concatenation or slicing, creates a new string object rather than modifying the original string object.

Here's an example to illustrate this:



s = "hello"

s[0] = "H"



OUTPUT:

TypeError: 'str' object does not support item assignment



In the above example, we tried to change the first character of the string s to "H" using the indexing operator, but we got a TypeError because strings are immutable.

Instead, we can create a new string that contains the modified version of the original string, like this:



s = "hello"

s = "H" + s[1:]

print(s)  # Output: "Hello"





In this example, we created a new string by concatenating the string "H" with a slice of the original string s. This creates a new string object that contains the modified version of the original string.

Immutable objects have several advantages, such as being thread-safe and cacheable. Because strings are immutable, they can be used as keys in dictionaries and elements in sets, because their value will never change. However, it also means that every time we need to modify a string, we need to create a new string object, which can be inefficient for large strings.





6>>.Explain any two methods of regular expression with examples.

ANS——>


Regular expressions (regex) are a powerful tool for working with text in Python. They allow you to search for and manipulate patterns in strings. Here are two methods of the re module in Python that are commonly used for working with regular expressions:


  1. re.search(): This method searches for a given pattern in a string and returns the first match it finds. Here's an example:


import re


s = "The quick brown fox jumps over the lazy dog."

match = re.search(r"fox", s)


if match:

    print("Found match:", match.group())

else:

    print("No match found.")




OUTPUT:

Found match: fox




In this example, we imported the re module and used the re.search() method to search for the pattern "fox" in the string s. The regular expression is enclosed in r"..." to indicate that it is a raw string that should not be interpreted. The search() method returns a match object if it finds a match, or None if it does not. We can then use the group() method to retrieve the matched substring.



  1. re.sub(): This method replaces all occurrences of a given pattern in a string with a new substring. Here's an example:


import re


s = "The quick brown fox jumps over the lazy dog."

new_s = re.sub(r"fox", "cat", s)


print(new_s)




OUTPUT:

The quick brown cat jumps over the lazy dog.



In this example, we used the re.sub() method to replace all occurrences of the pattern "fox" in the string s with the substring "cat". The first argument is the regular expression pattern to search for, and the second argument is the replacement string. The method returns a new string with all occurrences of the pattern replaced.

These are just two of the many methods available in the re module for working with regular expressions in Python. By using regular expressions, you can perform complex pattern matching and manipulation tasks with ease.



ASSIGNMENT – 6 




Q.1. Explain the concept of classes and objects in Python. How you can create and destroy objects in python? Explain with suitable examples.

ANS——>




Classes and objects are an essential part of object-oriented programming (OOP) in Python.

A class is a blueprint for creating objects that define a set of attributes and methods that the objects will have. An object is an instance of a class, which has its own set of values for the attributes defined in the class and can call the methods defined in the class.

To create a class in Python, we use the class keyword followed by the name of the class. For example:



class Dog:

    def __init__(self, name, age):

        self.name = name

        self.age = age


    def bark(self):

        print("Woof!")


dog1 = Dog("Buddy", 2)

print(dog1.name)  # Output: Buddy

dog1.bark()  # Output: Woof!




In this example, we defined a class Dog with two attributes (name and age) and one method (bark). We used the __init__ method (also known as the constructor) to initialize the attributes of the object when it is created. We then created an instance of the Dog class called dog1 with the name "Buddy" and age 2. We accessed the name attribute of dog1 using dot notation (dog1.name) and called its bark method using dot notation as well (dog1.bark()).

To destroy an object in Python, we can use the del keyword followed by the name of the object. For example:





del dog1




This will delete the dog1 object from memory.

We can also create multiple instances of a class:




dog2 = Dog("Max", 3)

dog3 = Dog("Rocky", 5)


print(dog2.name)  # Output: Max

print(dog3.age)  # Output: 5



In this example, we created two more instances of the Dog class called dog2 and dog3 with different names and ages.

When we create an object in Python, it is automatically created in memory. However, Python has a garbage collector that automatically deletes objects that are no longer being used. We can also explicitly delete an object using the del keyword, as shown earlier.

In summary, classes and objects are a fundamental part of object-oriented programming in Python, and they allow us to define and create custom data types with their own attributes and methods. We can create and destroy objects using the class and del keywords, respectively.





Q.2. What are access modifiers in Python? Give examples.

ANS——>




Access modifiers are keywords that define the level of access to class attributes and methods in object-oriented programming languages like Python. Python does not have strict access modifiers like some other languages, but it has some conventions that can be used to define access levels.

In Python, there are two types of access modifiers:

  1. Public: Attributes and methods that are not prefixed with an underscore are considered public and can be accessed from anywhere in the program. For example:




class MyClass:

    def __init__(self):

        self.public_attr = 10


    def public_method(self):

        print("This is a public method.")


obj = MyClass()

print(obj.public_attr)  # Output: 10

obj.public_method()  # Output: This is a public method.



In this example, public_attr and public_method are public attributes and methods of the MyClass class. They can be accessed from outside the class using dot notation (obj.public_attr and obj.public_method()).


  1. Private: Attributes and methods that are prefixed with an underscore are considered private and should not be accessed from outside the class. For example:


class MyClass:

    def __init__(self):

        self._private_attr = 20


    def _private_method(self):

        print("This is a private method.")


obj = MyClass()

print(obj._private_attr)  # Output: 20

obj._private_method()  # Output: This is a private method.




In this example, _private_attr and _private_method are private attributes and methods of the MyClass class. They can be accessed from outside the class using dot notation (obj._private_attr and obj._private_method()), but it is not recommended because they are intended to be used only within the class.

It's important to note that Python does not enforce private access modifiers like some other languages do, so the convention of using an underscore prefix is simply a way to indicate to other programmers that the attribute or method should be treated as private. However, in practice, it is considered good practice to follow these conventions to avoid unintentional access to private attributes and methods.




Q.3. Explain the concept of Inheritance and Polymorphism along with their types. Give  suitable examples.

ANS——>



Inheritance and Polymorphism are two fundamental concepts in object-oriented programming that allow for code reuse and flexibility.

  1. Inheritance:
  2. Inheritance is a mechanism that allows a class to inherit the properties and methods of another class. The class that inherits the properties and methods is called the derived class, and the class that provides the properties and methods is called the base class or parent class.

Inheritance is useful because it allows you to reuse code from an existing class, without having to write it again in a new class. In Python, you can create a subclass by specifying the base class in parentheses after the subclass name. For example:




class Animal:

    def __init__(self, name):

        self.name = name


    def speak(self):

        pass


class Dog(Animal):

    def speak(self):

        return "Woof!"


class Cat(Animal):

    def speak(self):

        return "Meow!"


dog = Dog("Rufus")

cat = Cat("Fluffy")


print(dog.speak())  # Output: Woof!

print(cat.speak())  # Output: Meow!





n this example, the Animal class is the base class, and the Dog and Cat classes are derived classes. They inherit the __init__ method from the Animal class, which sets the name attribute, and they provide their own implementation of the speak method. When we create instances of Dog and Cat and call their speak methods, we get the appropriate responses.

  1. Polymorphism:
  2. Polymorphism is the ability of objects to take on many forms. It allows you to write code that can work with objects of different classes, as long as they implement the same interface (i.e., they have the same methods).

There are two types of polymorphism in Python:



a) Duck typing: Duck typing is a dynamic typing technique in which the type of an object is determined by its behavior (i.e., the methods it has), rather than its class. For example:




class Dog:

    def speak(self):

        return "Woof!"


class Cat:

    def speak(self):

        return "Meow!"


def make_animal_speak(animal):

    print(animal.speak())


dog = Dog()

cat = Cat()


make_animal_speak(dog)  # Output: Woof!

make_animal_speak(cat)  # Output: Meow!






In this example, the Dog and Cat classes have a speak method, so they can be passed to the make_animal_speak function, which takes any object with a speak method and calls it.

In this example, the Dog and Cat classes have a speak method, so they can be passed to the make_animal_speak function, which takes any object with a speak method and calls it.

b) Method overloading: Method overloading is a technique that allows a class to have multiple methods with the same name, but different parameters. In Python, method overloading is achieved b



class Calculator:

    def add(self, a, b=None):

        if b is None:

            return a

        else:

            return a + b


calc = Calculator()


print(calc.add(1))  # Output: 1

print(calc.add(1, 2))  # Output: 3




In this example, the add method of the Calculator class has two versions: one that takes one argument (a) and returns it, and another that takes two arguments (a and b) and returns their sum. When we call calc.add(1), it uses the first version of the method, and when we call `calc.add(1, 2)






Q.4. Demonstrate the use of abstract classes in python with examples.

ANS——>




In Python, abstract classes are classes that cannot be instantiated, and are only meant to serve as a blueprint for other classes. Abstract classes are useful when you want to define a common interface for a group of classes, but you don't want to provide a concrete implementation for every method.

Python provides the abc module, which allows you to define abstract classes and methods. To define an abstract class, you need to use the ABCMeta metaclass, and decorate the abstract methods with the @abstractmethod decorator.

Here's an example:



from abc import ABCMeta, abstractmethod


class Shape(metaclass=ABCMeta):

    @abstractmethod

    def area(self):

        pass


    @abstractmethod

    def perimeter(self):

        pass


class Rectangle(Shape):

    def __init__(self, width, height):

        self.width = width

        self.height = height


    def area(self):

        return self.width * self.height


    def perimeter(self):

        return 2 * (self.width + self.height)


class Circle(Shape):

    def __init__(self, radius):

        self.radius = radius


    def area(self):

        return 3.14 * self.radius ** 2


    def perimeter(self):

        return 2 * 3.14 * self.radius


rect = Rectangle(5, 3)

print(rect.area())  # Output: 15

print(rect.perimeter())  # Output: 16


circle = Circle(2)

print(circle.area())  # Output: 12.56

print(circle.perimeter())  # Output: 12.56




In this example, we define an abstract class Shape with two abstract methods: area and perimeter. We then define two concrete classes Rectangle and Circle that inherit from Shape and implement the abstract methods.

Note that if we don't implement all the abstract methods in a concrete class, we will get an error when we try to instantiate the class:





class Square(Shape):

    def __init__(self, side):

        self.side = side


    def area(self):

        return self.side ** 2


# Will raise a TypeError because the 'perimeter' method is not implemented

square = Square(4)



Abstract classes are useful because they allow you to enforce a common interface for a group of classes, while still allowing each class to have its own implementation. This makes your code more flexible and maintainable, since you can easily add new classes that conform to the same interface without having to modify existing code.





Q.5. Write short note on 

Numpy

Pandas

Matplotlib

Pillow


ANS——>



  1. Numpy:

NumPy is a Python library used for scientific computing. It provides a multidimensional array object, various derived objects (such as masked arrays and matrices), and an assortment of routines for fast operations on arrays, including mathematical, logical, shape manipulation, sorting, selecting, I/O, discrete Fourier transforms, basic linear algebra, basic statistical operations, random simulation and much more.


  1. Pandas:

Pandas is a Python library used for data manipulation and analysis. It provides data structures for efficiently storing and manipulating large datasets, as well as tools for reading and writing data from a variety of formats (such as CSV, Excel, SQL databases, and more). Pandas allows you to easily filter, sort, group, aggregate, and pivot data, as well as perform time-series analysis and handle missing data.


  1. Matplotlib:

Matplotlib is a Python library used for data visualization. It provides a wide range of 2D and 3D plotting functions, including line plots, scatter plots, bar plots, histograms, pie charts, contour plots, surface plots, and more. Matplotlib is highly customizable, allowing you to adjust the style, color, and layout of your plots to suit your needs.


  1. Pillow:

Pillow is a Python library used for image processing and manipulation. It provides a wide range of image processing functions, including image filtering, resizing, cropping, rotating, and more. Pillow also allows you to create and modify images, add text and shapes, and convert images between different formats. It is a fork of the Python Imaging Library (PIL), which is no longer actively developed.



Q.6.write different frameworks in python. 

ANS——>


Python is a highly versatile language that can be used for a wide range of applications. It has a large number of frameworks available for different purposes, some of which are:

  1. Flask: Flask is a micro web framework for Python that is easy to use and lightweight. It is often used for developing small to medium sized web applications.
  2. Django: Django is a high-level web framework for Python that follows the model-view-controller (MVC) architectural pattern. It provides a lot of features out of the box, including an ORM, admin interface, and templating engine. It is often used for developing large-scale web applications.
  3. Pyramid: Pyramid is a web framework for Python that is highly flexible and adaptable. It can be used for developing web applications of any size, from small prototypes to large-scale applications.
  4. Scikit-learn: Scikit-learn is a machine learning library for Python that provides tools for data preprocessing, feature extraction, model selection, and evaluation. It is widely used for developing machine learning models for a wide range of applications.
  5. Pygame: Pygame is a set of Python modules used for game development. It provides tools for graphics, sound, input handling, and more, making it easy to develop games in Python.
  6. Twisted: Twisted is an event-driven networking engine for Python that provides a lot of tools for developing network applications, including protocols, transports, and services.
  7. CherryPy: CherryPy is a minimalist web framework for Python that is easy to use and highly customizable. It provides tools for handling HTTP requests and responses, sessions, and more, making it ideal for developing small to medium sized web applications.

These are just a few examples of the many frameworks available for Python. Each framework has its own strengths and weaknesses, so it's important to choose the one that best fits your needs.







Comments

Popular posts from this blog

Question bank solution of CAMP

     1>> Explain basic computer organization and enlist various design components. ANS----> .   Computer organization refers to the way in which a computer's various components work together to execute instructions and perform tasks. The basic computer organization includes various design components, which are as follows: Central Processing Unit (CPU): It is the brain of the computer that performs all the arithmetic and logical operations. The CPU consists of an arithmetic logic unit (ALU) that performs arithmetic and logical operations, a control unit (CU) that fetches instructions from memory and decodes them, and registers that store data. Memory Unit: It is the component of the computer that stores instructions and data. The memory unit consists of two types of memory: primary memory and secondary memory. Primary memory, also known as main memory, includes Random Access Memory (RAM) and Read-Only Memory (ROM), while secondary memory
  PYTHON PROGRAMMING QUESTION BANK SOLUTION:                               UNIT: 1 1>> Explain features of python. ANS---->.   Python is a popular high-level programming language that is known for its simplicity, readability, and versatility. Some of the key features of Python are: Easy to Learn: Python has a clean and simple syntax that is easy to understand and learn, even for beginners. Interpreted Language: Python code is executed line by line by the interpreter, which means that you don't have to compile your code before running it. Cross-platform: Python is a portable language that can be used on a variety of operating systems, including Windows, Linux, and Mac OS. Object-Oriented Programming (OOP) support: Python supports object-oriented programming, which allows developers to write reusable and modular code. Large Standard Library: Python has a large and comprehensive standard library, which includes modules for many common tasks such as file I/O, regular expressio