Skip to main content

 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:

  1. Easy to Learn: Python has a clean and simple syntax that is easy to understand and learn, even for beginners.

  2. 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.

  3. Cross-platform: Python is a portable language that can be used on a variety of operating systems, including Windows, Linux, and Mac OS.

  4. Object-Oriented Programming (OOP) support: Python supports object-oriented programming, which allows developers to write reusable and modular code.

  5. Large Standard Library: Python has a large and comprehensive standard library, which includes modules for many common tasks such as file I/O, regular expressions, networking, and more.

  6. Third-party Libraries: Python has a vast ecosystem of third-party libraries and packages, which can be easily installed and used in your projects.

  7. Dynamic Typing: Python is dynamically typed, which means that you don't have to declare variable types before using them.

  8. High-level Language: Python is a high-level language, which means that it abstracts away many low-level details, making it easier to write and read code.

  9. Supports Functional Programming: Python supports functional programming, which allows developers to write more concise and readable code.

  10. Comprehensive Documentation: Python has comprehensive and up-to-date documentation, which makes it easy to learn and use.




2>>Compare python with C and Java. 
ANS---->

Python, C, and Java are all programming languages, but they differ in several ways. Here are some of the main differences between the three languages:

  1. Syntax: Python has a simple and readable syntax, while C and Java have more complex syntax. Python also has fewer syntax rules and requirements than C or Java, making it easier to learn and use.

  2. Typing: Python is dynamically typed, while C and Java are statically typed. This means that Python variables can be assigned different types at different points in the code, whereas C and Java variables must be declared with a specific type and cannot change.

  3. Performance: C is generally faster than both Python and Java because it is a compiled language that produces executable machine code. Java is also faster than Python because it is compiled into bytecode that can be executed on a Java Virtual Machine (JVM). Python is interpreted, which can make it slower than compiled languages.

  4. Memory Management: C and Java use manual memory management, where the programmer must manually allocate and deallocate memory. Python uses automatic memory management, where the interpreter handles memory allocation and deallocation, making it easier for developers to write and debug code.

  5. Libraries and Frameworks: Python has a vast number of third-party libraries and frameworks, which make it easy to develop complex applications quickly. C and Java also have libraries and frameworks, but they are generally more limited than Python's.

  6. Use Cases: C is often used for system-level programming, embedded systems, and low-level hardware programming. Java is commonly used for developing enterprise-level applications, mobile apps, and web applications. Python is often used for data science, machine learning, web development, scripting, and automation.

  7. Learning Curve: Python has a shallow learning curve compared to C and Java, making it easier for beginners to learn and start coding quickly.

  8. Popularity: Python is currently the most popular language among developers, according to several surveys. Java and C are also popular, but Python's popularity has grown rapidly in recent years due to its ease of use and versatility.


3>>Python is interpreted language explain in details.
ANS---->

Python is an interpreted programming language, which means that instead of being compiled directly into machine code, Python code is executed by an interpreter.

When a Python program is run, the interpreter reads the source code line by line, compiles each line into bytecode, and then executes the bytecode. This process happens in real-time, as the code is being run, which makes it easy to test and debug code quickly.

Because Python is an interpreted language, it is also platform-independent, which means that Python code can run on any platform that has a Python interpreter installed. This makes it easier to write code that can be run on multiple platforms without modification.

Interpreted languages like Python are also typically slower than compiled languages like C or Java because the interpreter must convert the code to machine code each time it is run. However, the performance difference is often negligible for many applications and can be improved through the use of certain techniques like just-in-time (JIT) compilation.

Another advantage of interpreted languages is that they are more flexible and easier to use for rapid development and prototyping. Developers can make changes to their code and see the results immediately, without having to wait for the compiler to generate an executable file.

Overall, the interpreted nature of Python is one of the key factors that makes it an attractive language for developers, particularly for applications that require rapid development, prototyping, or scripting.

UNIT:2


4>>Which are the built in data types in python?

ANS---->

Python has several built-in data types that are used to represent different kinds of data. These include:

  1. Numbers: There are three types of numbers in Python: integers, floating-point numbers, and complex numbers.

  2. Strings: Strings are used to represent text data in Python. They are enclosed in quotes, either single quotes or double quotes.

  3. Lists: Lists are used to represent a collection of values, such as a list of names or a list of numbers. They are ordered and mutable, which means that elements can be added, removed, or changed.

  4. Tuples: Tuples are similar to lists but are immutable, which means that once they are created, their elements cannot be changed. They are often used to represent fixed collections of data, such as the coordinates of a point.

  5. Sets: Sets are used to represent a collection of unique values. They are unordered and mutable, and can be used for operations such as intersection, union, and difference.

  6. Dictionaries: Dictionaries are used to represent key-value pairs, where each key is associated with a value. They are unordered and mutable, and can be used to store data in a way that can be easily looked up by its key.

In addition to these built-in data types, Python also has several other data types that are used for more specialized purposes, such as bytes, bytearrays, and range objects.


5>>How to comment specific line(s) in Python program?

ANS----> To comment a specific line or lines of code in a Python program, you can use the "#" character at the beginning of the line(s) that you want to comment. Here's an example:

# This is a comment that applies to a single line of code

x = 5  # This is a comment that appears after a line of code


"""

This is a comment that spans multiple lines

Line 1 of the comment

Line 2 of the comment

"""

In the example above, the first line is a single-line comment that applies to the line of code that follows it. The second line is also a single-line comment that appears after the line of code.

The third example is a multi-line comment that spans multiple lines. Multi-line comments are enclosed in triple quotes, and any text within the quotes is ignored by the interpreter.

Comments are used to add context and information to your code, to explain what it does, and to make it easier for others to understand and maintain your code.


6>>Explain a list with examples and explain any 5 methods with examples

ANS---->In Python, a list is a collection of elements that can be of any data type, such as numbers, strings, or even other lists. Lists are ordered, which means that their elements are arranged in a specific order and can be accessed by their index number. Lists are also mutable, which means that their elements can be added, removed, or modified.

Here is an example of a list in Python

fruits = ["apple", "banana", "cherry", "orange"]

In this example, the list "fruits" contains four elements: "apple", "banana", "cherry", and "orange".

Here are some common methods that can be used with lists:

  1. append(): This method is used to add a new element to the end of a list. Here's an example:

  1. fruits = ["apple", "banana", "cherry"] fruits.append("orange") print(fruits) # Output: ["apple", "banana", "cherry", "orange"]

2.remove(): This method is used to remove a specific element from a list. Here's an example

fruits = ["apple", "banana", "cherry"] fruits.remove("banana") print(fruits) # Output: ["apple", "cherry"]


3.pop(): This method is used to remove the last element of a list, or an element at a specific index. Here's an example

fruits = ["apple", "banana", "cherry"] fruits.pop() print(fruits) # Output: ["apple", "banana"] fruits.pop(0) print(fruits) # Output: ["banana"]


4.sort(): This method is used to sort the elements of a list in ascending order. Here's an example:

numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5] numbers.sort() print(numbers) # Output: [1, 1, 2, 3, 4, 5, 5, 6, 9



These are just a few examples of the many methods that can be used with lists in Python.
7>>Is tuple mutable? Demonstrate any two methods of tuple.
ANS---->  

No, a tuple is immutable in Python, which means that once it is created, its elements cannot be modified or deleted. However, you can create a new tuple by concatenating or slicing the original tuple.

Here are two common methods that can be used with tuples in Python:

  1. index(): This method is used to find the index of a specific element in a tuple. Here's an example
fruits = ("apple", "banana", "cherry") index = fruits.index("banana") print(index) # Output: 1


In this example, the index() method is used to find the index of the element "banana" in the tuple "fruits". The method returns the index of the first occurrence of the element, which in this case is 1.

  1. count(): This method is used to count the number of occurrences of a specific element in a tuple. Here's an example:
fruits = ("apple", "banana", "cherry", "banana", "orange") count = fruits.count("banana") print(count) # Output: 2

In this example, the count() method is used to count the number of occurrences of the element "banana" in the tuple "fruits". The method returns the number of times the element appears in the tuple, which in this case is 2.

These methods are just a few examples of the many operations that can be performed on tuples in Python. Because tuples are immutable, they are often used to represent fixed collections of data that should not be modified, such as the coordinates of a point or the RGB values of a color.


8>>Write a program to reverse a list.

ANS---->. Here's an example program in Python to reverse a list using slicing:

original_list = [1, 2, 3, 4, 5] reversed_list = original_list[::-1] print(reversed_list).


Output: [5, 4, 3, 2, 1]

     

In this example, we define a list original_list with the values [1, 2, 3, 4, 5]. We then use slicing to create a new list reversed_list that contains all the elements of the original list in reverse order. The syntax [::-1] specifies a slice that starts at the end of the list and goes backwards by one element at a time.

Finally, we print the reversed list using the print() function. The output of this program is [5, 4, 3, 2, 1], which is the original list reversed.

      

9>>Differentiate between list and set
ANS---->

Lists and sets are both data structures in Python, but they have some fundamental differences:

  1. Ordering: Lists are ordered collections of elements, which means that the elements have a specific order that is maintained. In contrast, sets are unordered collections of elements, which means that the order of elements is not maintained.

  2. Duplicates: Lists allow duplicate elements, which means that an element can occur multiple times in a list. Sets, on the other hand, do not allow duplicates, which means that each element in a set must be unique.

  3. Mutability: Lists are mutable, which means that you can modify the elements of a list after it has been created. Sets are also mutable, which means that you can add or remove elements from a set after it has been created.

  4. Indexing: Lists can be accessed using an index, which is an integer that specifies the position of an element in the list. Sets, on the other hand, cannot be accessed using an index because they are unordered collections.

  5. Type of brackets used: In Python, lists are created using square brackets [], while sets are created using curly braces {} or by using the set() constructor.

Here's an example to illustrate the differences between lists and sets:



# Creating a list my_list = [1, 2, 3, 3, 4, 5, 5] print(my_list) # Output: [1, 2, 3, 3, 4, 5, 5] # Creating a set my_set = {1, 2, 3, 3, 4, 5, 5} print(my_set) # Output: {1, 2, 3, 4, 5} # Adding an element to a list my_list.append(6) print(my_list) # Output: [1, 2, 3, 3, 4, 5, 5, 6] # Adding an element to a set my_set.add(6) print(my_set) # Output: {1, 2, 3, 4, 5, 6} # Accessing an element in a list print(my_list[2]) # Output: 3 # Accessing an element in a set (not possible) # print(my_set[2]) # TypeError: 'set' object is not subscriptable



In this example, we create a list my_list and a set my_set that contain the same elements. We demonstrate that lists can contain duplicates, while sets cannot. We also demonstrate that lists are mutable, while sets are also mutable. Finally, we demonstrate that lists can be accessed using an index, while sets cannot.



10>>What is dictionary in Python? Explain with an example

ANS---->A dictionary is a built-in data structure in Python that is used to store and retrieve key-value pairs. It is also known as a hash table or associative array in other programming languages. In Python, dictionaries are enclosed in curly braces {} and consist of comma-separated key-value pairs.

Here's an example of a dictionary in Python:


# Creating a dictionary person = {'name': 'John', 'age': 30, 'gender': 'male', 'city': 'New York'} # Accessing values in a dictionary print(person['name']) # Output: John print(person['age']) # Output: 30 print(person['gender']) # Output: male print(person['city']) # Output: New York # Modifying values in a dictionary person['age'] = 35 person['city'] = 'San Francisco' print(person) # Output: {'name': 'John', 'age': 35, 'gender': 'male', 'city': 'San Francisco'} # Adding a new key-value pair to a dictionary person['occupation'] = 'software engineer' print(person) # Output: {'name': 'John', 'age': 35, 'gender': 'male', 'city': 'San Francisco', 'occupation': 'software engineer'} # Removing a key-value pair from a dictionary del person['gender'] print(person) # Output: {'name': 'John', 'age': 35, 'city': 'San Francisco', 'occupation': 'software engineer'}

In this example, we create a dictionary person that contains key-value pairs representing various attributes of a person. We then demonstrate how to access values in a dictionary using keys, modify values in a dictionary, add new key-value pairs to a dictionary, and remove key-value pairs from a dictionary.

Dictionaries are commonly used in Python for tasks such as storing configuration settings, representing JSON data, and building data structures for algorithms like graphs and hash tables.


11>>Explain Bitwise Operator.

ANS---->. In Python, bitwise operators are used to manipulate the bits of integers at the binary level. They are useful when working with low-level data like binary files, network packets, and hardware drivers.

There are six bitwise operators in Python:

  1. AND (&): Returns a binary number where each bit is 1 only if the corresponding bits in both operands are 1.

  2. OR (|): Returns a binary number where each bit is 1 if either of the corresponding bits in both operands is 1.

  3. XOR (^): Returns a binary number where each bit is 1 only if the corresponding bits in both operands are different.

  4. NOT (~): Inverts all the bits in the operand, i.e., it returns the one's complement of the operand.

  5. Left Shift (<<): Shifts the bits of the operand to the left by a specified number of positions, and fills the vacated positions with 0.

  6. Right Shift (>>): Shifts the bits of the operand to the right by a specified number of positions, and fills the vacated positions with 0 (for non-negative numbers) or 1 (for negative numbers)

Here's an example that demonstrates the use of bitwise operators:

a = 10 # Binary representation: 1010 b = 6 # Binary representation: 0110 # Bitwise AND print(a & b) # Output: 2 (Binary representation: 0010) # Bitwise OR print(a | b) # Output: 14 (Binary representation: 1110) # Bitwise XOR print(a ^ b) # Output: 12 (Binary representation: 1100) # Bitwise NOT print(~a) # Output: -11 (Binary representation: 11110101) # Left Shift print(a << 2) # Output: 40 (Binary representation: 101000) # Right Shift print(a >> 2) # Output: 2 (Binary representation: 10)


In this example, we perform various bitwise operations on the integers a and b. We use the &, |, ^, ~, <<, and >> operators to manipulate the bits of these integers and obtain the desired results. Note that the output values are in decimal format, but we can also represent them in binary format for better understanding.


13>>Explain membership operator. 

ANS——>.    


Membership operators are used to test whether a value is a member of a sequence or a collection of values. In Python, there are two membership operators:

  1. in: Returns True if the specified value is found in the sequence or collection, otherwise returns False.
  2. not in: Returns True if the specified value is not found in the sequence or collection, otherwise returns False.

These operators are useful when working with strings, lists, tuples, sets, and dictionaries. They allow us to quickly check whether a value is present in a collection without having to loop through each element.

Here's an example that demonstrates the use of membership operators:


fruits = ['apple', 'banana', 'cherry', 'orange']


# Membership operators with lists

print('apple' in fruits)        # Output: True

print('pear' in fruits)         # Output: False

print('pear' not in fruits)     # Output: True


# Membership operators with strings

text = 'Python is a high-level programming language'


print('Python' in text)         # Output: True

print('Java' in text)           # Output: False

print('Java' not in text)       # Output: True


# Membership operators with sets

colors = {'red', 'green', 'blue'}


print('red' in colors)          # Output: True

print('yellow' in colors)       # Output: False

print('yellow' not in colors)   # Output: True


# Membership operators with dictionaries

person = {'name': 'John', 'age': 30}


print('name' in person)         # Output: True

print('gender' in person)       # Output: False

print('gender' not in person)   # Output: True


In this example, we use the in and not in operators to check whether a value is present in a list, a string, a set, and a dictionary. We also demonstrate the use of the in operator with a dictionary, which checks whether a key is present in the dictionary.




14>>Explain python list constructor 

ANS——>


In Python, the list() constructor is used to create a new list object. The list() constructor can take an iterable object as its argument, such as a string, tuple, set, or another list, and convert it into a new list.

Here's an example that demonstrates the use of the list() constructor:


# Creating a new list using the list() constructor

numbers = list(range(1, 6))

print(numbers)   # Output: [1, 2, 3, 4, 5]


# Converting a string into a list using the list() constructor

string = "Hello, World!"

chars = list(string)

print(chars)     # Output: ['H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!']


# Converting a tuple into a list using the list() constructor

tuple1 = (1, 2, 3)

list1 = list(tuple1)

print(list1)     # Output: [1, 2, 3]


# Creating a new list by copying an existing list using the list() constructor

list2 = [4, 5, 6]

list3 = list(list2)

print(list3)     # Output: [4, 5, 6]


  

In this example, we use the list() constructor to create a new list object in various ways. In the first example, we create a list of numbers using the range() function, and then pass it to the list() constructor to create a new list. In the second example, we convert a string into a list of characters using the list() constructor. In the third example, we convert a tuple into a list. Finally, in the fourth example, we create a new list by copying an existing list using the list() constructor.



15>>Illustrate dictionary in Python programming language. 

ANS——>


In Python, a dictionary is an unordered collection of key-value pairs, where each key is unique. Dictionaries are implemented as hash tables, which allows for fast lookups and insertions. Dictionaries are defined using curly braces {} and the key-value pairs are separated by colons :. Here's an example that demonstrates the use of a dictionary:




# Creating a dictionary

person = {'name': 'John', 'age': 30, 'gender': 'Male'}


# Accessing the values in the dictionary

print(person['name'])     # Output: John

print(person['age'])      # Output: 30

print(person['gender'])   # Output: Male


# Adding a new key-value pair to the dictionary

person['occupation'] = 'Engineer'

print(person)             # Output: {'name': 'John', 'age': 30, 'gender': 'Male', 'occupation': 'Engineer'}


# Modifying an existing value in the dictionary

person['age'] = 35

print(person)             # Output: {'name': 'John', 'age': 35, 'gender': 'Male', 'occupation': 'Engineer'}


# Removing a key-value pair from the dictionary

del person['occupation']

print(person)             # Output: {'name': 'John', 'age': 35, 'gender': 'Male'}


In this example, we create a dictionary called person that contains information about a person, such as their name, age, and gender. We access the values in the dictionary using their respective keys. We add a new key-value pair to the dictionary using the square bracket notation. We modify an existing value in the dictionary using the square bracket notation as well. We remove a key-value pair from the dictionary using the del keyword. Note that dictionaries are mutable, which means that we can add, modify, and remove key-value pairs from them.







16>>Explain the list method index() with an example. 

ANS——>


The index() method in Python is used to find the index of the first occurrence of a specified item in a list. The method takes the value of the item as an argument and returns the index of the item if it is found in the list. If the item is not found, the method raises a ValueError. Here's an example that demonstrates the use of the index() method:



# Creating a list

fruits = ['apple', 'banana', 'cherry', 'banana', 'kiwi', 'banana']


# Finding the index of the first occurrence of 'banana' in the list

index = fruits.index('banana')

print(index)      # Output: 1


# Finding the index of the first occurrence of 'banana' after index 2

index = fruits.index('banana', 2)

print(index)      # Output: 3


# Finding the index of the first occurrence of 'orange' in the list (raises ValueError)

index = fruits.index('orange')


In this example, we create a list called fruits that contains multiple occurrences of the string 'banana'. We use the index() method to find the index of the first occurrence of 'banana' in the list, which is at index 1. We also use the index() method to find the index of the first occurrence of 'banana' after index 2, which is at index 3. Finally, we try to find the index of the string 'orange' in the list using the index() method, but since 'orange' is not in the list, the method raises a ValueError.


17>>Design about Creating a tuple in Python. 

ANS—->


In Python, a tuple is an ordered and immutable collection of elements. Tuples are defined using parentheses () and the elements are separated by commas. Here's an example of how to create a tuple in Python:


# Creating a tuple with three elements

my_tuple = (1, 'two', 3.0)


# Accessing the elements of the tuple using indexing

print(my_tuple[0])      # Output: 1

print(my_tuple[1])      # Output: two

print(my_tuple[2])      # Output: 3.0


# Trying to modify an element of the tuple (raises TypeError)

my_tuple[0] = 2



In this example, we create a tuple called my_tuple that contains three elements: the integer 1, the string 'two', and the floating-point number 3.0. We can access the elements of the tuple using indexing, just like we would with a list. However, we cannot modify the elements of a tuple because tuples are immutable. If we try to modify an element of the tuple using indexing, we get a TypeError.




18>>Explain the following method with examples i)append() 

ANS——>


The append() method is a built-in list method in Python that is used to add an element to the end of a list. This method takes a single argument, which is the element to be added to the list, and modifies the original list. Here's an example that demonstrates the use of the append() method:



# Creating an empty list

my_list = []


# Adding elements to the list using append()

my_list.append(1)

my_list.append('two')

my_list.append(3.0)


# Printing the modified list

print(my_list)      # Output: [1, 'two', 3.0]



In this example, we create an empty list called my_list. We then use the append() method to add the integer 1 to the end of the list, followed by the string 'two', and finally the floating-point number 3.0. We print the modified list and see that it now contains all three elements in the order that they were added using the append() method


19>>Write a Python program that implements i)Reverse a list.
ii)Copy a list.
iii)Insert a number in list. 

ANS——>


# Reverse a list

def reverse_list(lst):

    return lst[::-1]


my_list = [1, 2, 3, 4, 5]

print("Original list:", my_list)

reversed_list = reverse_list(my_list)

print("Reversed list:", reversed_list)


# Copy a list

def copy_list(lst):

    return lst.copy()


my_list = [1, 2, 3, 4, 5]

print("Original list:", my_list)

copied_list = copy_list(my_list)

print("Copied list:", copied_list)


# Insert a number in list

def insert_number(lst, num, index):

    lst.insert(index, num)

    return lst


my_list = [1, 2, 3, 4, 5]

print("Original list:", my_list)

new_list = insert_number(my_list, 6, 2)

print("List after inserting 6 at index 2:", new_list)



In this program, we define three functions to perform the three tasks you requested. The reverse_list() function takes a list as an argument and returns a reversed version of the list using slicing. The copy_list() function takes a list as an argument and returns a copy of the list using the copy() method. The insert_number() function takes a list, a number, and an index as arguments, and inserts the number at the specified index using the insert() method.

We then create a list called my_list and use each of the functions to perform the three tasks you requested. We print the original list and the modified list after each task to demonstrate the results.



20>>Explore the standard data types in Python? 

ANS——>


Python provides several built-in data types to store different types of data. The standard data types in Python include:

  1. Numeric data types: These data types are used to store numeric values such as integers, floating-point numbers, and complex numbers. Examples include int, float, and complex.
  2. Sequence data types: These data types are used to store a sequence of values, such as lists, tuples, and range objects. Examples include list, tuple, and range.
  3. Text data type: This data type is used to store text-based data, such as strings. Example: str.
  4. Boolean data type: This data type is used to store the truth values True and False. Example: bool.
  5. Set data type: This data type is used to store a collection of unique and unordered values. Example: set.
  6. Dictionary data type: This data type is used to store key-value pairs, where each key is unique and mapped to a corresponding value. Example: dict.

Each of these data types has its own unique set of properties and methods that can be used to manipulate the data. By understanding the standard data types in Python, you can choose the appropriate data type for your program based on the type of data you need to store and the operations you need to perform on that data.




21>>Illustrate bitwise operator. 

ANS——>



In Python, there are several bitwise operators that can be used to perform operations on binary representations of numbers. These operators include:

  1. Bitwise AND (&): Returns 1 if both bits at the same position are 1, otherwise returns 0.
  2. Bitwise OR (|): Returns 1 if at least one bit at the same position is 1, otherwise returns 0.
  3. Bitwise XOR (^): Returns 1 if the bits at the same position are different, otherwise returns 0.
  4. Bitwise NOT (~): Returns the complement of the binary representation of the number.
  5. Left Shift (<<): Shifts the bits of the number to the left by a specified number of positions and pads the new positions with 0s.
  6. Right Shift (>>): Shifts the bits of the number to the right by a specified number of positions and pads the new positions with 0s or 1s depending on the sign of the number.



Here are some examples of how these operators work in Python:


# Bitwise AND

a = 0b1010  # binary representation of 10

b = 0b1100  # binary representation of 12

c = a & b   # bitwise AND of a and b

print(bin(c))  # output: 0b1000


# Bitwise OR

a = 0b1010  # binary representation of 10

b = 0b1100  # binary representation of 12

c = a | b   # bitwise OR of a and b

print(bin(c))  # output: 0b1110


# Bitwise XOR

a = 0b1010  # binary representation of 10

b = 0b1100  # binary representation of 12

c = a ^ b   # bitwise XOR of a and b

print(bin(c))  # output: 0b0110


# Bitwise NOT

a = 0b1010  # binary representation of 10

b = ~a      # bitwise NOT of a

print(bin(b))  # output: -0b1011


# Left Shift

a = 0b1010  # binary representation of 10

b = a << 2  # shift a to the left by 2 positions

print(bin(b))  # output: 0b101000


# Right Shift

a = 0b1010  # binary



In this example, we use binary literals (0b) to represent numbers in binary format. We perform various bitwise operations using the operators mentioned above and print the results in binary format using the bin() function. Note that the bitwise NOT operator (~) returns a negative number in binary format because it includes the two's complement representation of the number.




22>>Explain membership operator. 

ANS——>.    


Membership operators are used to test whether a value is a member of a sequence or a collection of values. In Python, there are two membership operators:

  1. in: Returns True if the specified value is found in the sequence or collection, otherwise returns False.
  2. not in: Returns True if the specified value is not found in the sequence or collection, otherwise returns False.

These operators are useful when working with strings, lists, tuples, sets, and dictionaries. They allow us to quickly check whether a value is present in a collection without having to loop through each element.

Here's an example that demonstrates the use of membership operators:


fruits = ['apple', 'banana', 'cherry', 'orange']


# Membership operators with lists

print('apple' in fruits)        # Output: True

print('pear' in fruits)         # Output: False

print('pear' not in fruits)     # Output: True


# Membership operators with strings

text = 'Python is a high-level programming language'


print('Python' in text)         # Output: True

print('Java' in text)           # Output: False

print('Java' not in text)       # Output: True


# Membership operators with sets

colors = {'red', 'green', 'blue'}


print('red' in colors)          # Output: True

print('yellow' in colors)       # Output: False

print('yellow' not in colors)   # Output: True


# Membership operators with dictionaries

person = {'name': 'John', 'age': 30}


print('name' in person)         # Output: True

print('gender' in person)       # Output: False

print('gender' not in person)   # Output: True


In this example, we use the in and not in operators to check whether a value is present in a list, a string, a set, and a dictionary. We also demonstrate the use of the in operator with a dictionary, which checks whether a key is present in the dictionary.



23>>Write different types of operators? 

ANS——>


In Python, there are several types of operators that can be used to perform various operations. These operators can be classified into the following categories:

  1. Arithmetic operators: These operators are used to perform basic mathematical operations such as addition, subtraction, multiplication, division, and modulus. The operators are +, -, *, /, and %, respectively.
  2. Comparison operators: These operators are used to compare two values and return a Boolean value (True or False). The operators are == (equal to), != (not equal to), < (less than), > (greater than), <= (less than or equal to), and >= (greater than or equal to).
  3. Logical operators: These operators are used to perform logical operations on Boolean values. The operators are and, or, and not.
  4. Assignment operators: These operators are used to assign values to variables. The basic assignment operator is =. There are also compound assignment operators such as +=, -=, *=, /=, and %=.
  5. Identity operators: These operators are used to compare the memory locations of two objects. The operators are is (returns True if both operands are the same object) and is not (returns True if both operands are different objects).
  6. Membership operators: These operators are used to check if a value is a member of a sequence or collection. The operators are in (returns True if the value is a member of the sequence) and not in (returns True if the value is not a member of the sequence).
  7. Bitwise operators: These operators are used to perform operations on binary representations of numbers. The operators are & (bitwise AND), | (bitwise OR), ^ (bitwise XOR), ~ (bitwise NOT), << (left shift), and >> (right shift).

These are the different types of operators in Python. Depending on the context of the program, different types of operators can be used to perform various operations.





24>>Express an operator and explain about the arithmetic operators and assignment operators in Python with example. 

ANS——>


An operator is a symbol or keyword that is used to perform operations on one or more operands in a programming language. In Python, there are various types of operators available, including arithmetic operators and assignment operators.

Arithmetic Operators:

Arithmetic operators are used to perform mathematical operations on numeric operands. The basic arithmetic operators in Python are +, -, *, /, and %. Let's take a look at some examples of arithmetic operators:



a = 10

b = 3


# Addition

c = a + b

print(c)    # Output: 13


# Subtraction

c = a - b

print(c)    # Output: 7


# Multiplication

c = a * b

print(c)    # Output: 30


# Division

c = a / b

print(c)    # Output: 3.3333333333333335


# Modulus

c = a % b

print(c)    # Output: 1





Assignment Operators:

Assignment operators are used to assign values to variables. The basic assignment operator in Python is =. There are also compound assignment operators such as +=, -= , *= , /= and %=. Let's see how they work with some examples:




# Basic Assignment

a = 10

print(a)    # Output: 10


# Compound Assignment

a += 5      # Equivalent to a = a + 5

print(a)    # Output: 15


a -= 3      # Equivalent to a = a - 3

print(a)    # Output: 12


a *= 2      # Equivalent to a = a * 2

print(a)    # Output: 24


a /= 4      # Equivalent to a = a / 4

print(a)    # Output: 6.0


a %= 2      # Equivalent to a = a % 2

print(a)    # Output: 0.0





In the above examples, we first assign values to the variable a, and then we perform various arithmetic and assignment operations on it. The compound assignment operators perform an operation and then assign the result back to the same variable.




25>>Describe about input statements in Python examples. 

ANS——>



In Python, the input() function is used to accept user input. The input() function takes a prompt as an argument and returns the input provided by the user as a string. Here's an example:


name = input("What is your name? ")

print("Hello, " + name + "!")





In this example, we use the input() function to ask the user for their name. The prompt "What is your name?" is displayed on the screen. The user then enters their name, and the input is assigned to the variable name. We then use the print() function to display a greeting message that includes the user's name.

The input() function can also be used to accept numerical input from the user. However, since input() always returns a string, we need to convert the input to a numerical data type before we can perform mathematical operations on it. Here's an example:



age = int(input("What is your age? "))

print("You will be " + str(age + 10) + " in 10 years.")





In this example, we use the input() function to ask the user for their age. The input is then converted to an integer using the int() function and assigned to the variable age. We then use the print() function to display a message that calculates the user's age in 10 years.

It's important to note that the input() function can also be used to accept input from files or other input streams by passing the appropriate argument to the function. However, the most common use case is to accept user input from the command line.


26>>Summarize about built-in data types and sequences in Python with examples. 

ANS——>


Python has several built-in data types, including:

  1. Numeric types: Integers, Floats, and Complex numbers.
  2. Boolean type: True or False.
  3. Sequence types: Lists, Tuples, and Range objects.
  4. String type: Ordered collection of characters.
  5. Set types: Sets and Frozen sets.
  6. Mapping type: Dictionaries.

Sequences are ordered collections of objects that can be indexed and sliced. The main sequence types in Python are lists, tuples, and range objects.

  • Lists are mutable sequences that can hold a collection of objects of different data types.




fruits = ['apple', 'banana', 'cherry']

numbers = [1, 2, 3, 4, 5]



Tuples are immutable sequences that can hold a collection of objects of different data types.




person = ('John', 25, 'USA')

coordinates = (3.14, -2.71)




Range objects represent an arithmetic sequence of integers.


numbers = range(1, 6)

print(list(numbers)) # Output: [1, 2, 3, 4, 5]




Built-in data types and sequences are used extensively in Python programming to store and manipulate data. Understanding the properties and characteristics of these data types is important for writing efficient and effective Python programs.



27>>List out different arithmetic Python? 

ANS—->


The arithmetic operators in Python are:

  1. Addition (+): adds two operands.
  2. Subtraction (-): subtracts the right operand from the left operand.
  3. Multiplication (*): multiplies two operands.
  4. Division (/): divides the left operand by the right operand and returns a float.
  5. Integer division (//): divides the left operand by the right operand and returns the quotient as an integer.
  6. Modulus (%): returns the remainder of dividing the left operand by the right operand.
  7. Exponentiation (**): raises the left operand to the power of the rig




a = 10

b = 3


print(a + b)   # Output: 13

print(a - b)   # Output: 7

print(a * b)   # Output: 30

print(a / b)   # Output: 3.3333333333333335

print(a // b)  # Output: 3

print(a % b)   # Output: 1

print(a ** b)  # Output: 1000





In the above example, a and b are two operands. The arithmetic operators are applied on these operands to perform different arithmetic operations.


28>>Explain different sequences in Python? 

ANS——>



In Python, sequences are ordered collections of objects that can be indexed and sliced. There are three main types of sequences in Python:

  1. Lists: Lists are mutable sequences that can hold a collection of objects of different data types. They are defined using square brackets [] and elements are separated by commas.



Example


fruits = ['apple', 'banana', 'cherry']

numbers = [1, 2, 3, 4, 5]




  1. Tuples: Tuples are immutable sequences that can hold a collection of objects of different data types. They are defined using parentheses () and elements are separated by commas.



Example:



person = ('John', 25, 'USA')

coordinates = (3.14, -2.71)




  1. Range objects: Range objects represent an arithmetic sequence of integers. They are commonly used to iterate over a sequence of numbers in a for loop. Range objects are created using the range() function.


Example:


numbers = range(1, 6)

print(list(numbers)) # Output: [1, 2, 3, 4, 5]



Sequences are one of the fundamental concepts in Python programming and are used extensively in many different applications. Understanding the properties and characteristics of sequences is important for writing efficient and effective Python program




29>>Write a Python program to find area of circle. 

ANS——>




To find the area of a circle in Python, we need to use the formula:

Area = π * r^2

where π is the mathematical constant pi and r is the radius of the circle.

Here's a Python program to find the area of a circle, where the radius is taken as input from the user:




import math


radius = float(input("Enter the radius of the circle: "))

area = math.pi * radius**2


print("The area of the circle is:", area)





In this program, we first import the math module which contains the mathematical constant pi and other mathematical functions. Then, we take the radius of the circle as input from the user using the input() function and convert it to a float using the float() function. Next, we calculate the area of the circle using the formula, and store it in the variable area. Finally, we print the result using the print() function



30>>Write a Python program to find Perimeter of rectangle 

ANS—->




To find the perimeter of a rectangle in Python, we need to use the formula:

Perimeter = 2 * (length + width)

where length and width are the dimensions of the rectangle.

Here's a Python program to find the perimeter of a rectangle, where the length and width are taken as input from the user:



length = float(input("Enter the length of the rectangle: "))

width = float(input("Enter the width of the rectangle: "))

perimeter = 2 * (length + width)


print("The perimeter of the rectangle is:", perimeter)




In this program, we take the length and width of the rectangle as input from the user using the input() function and convert them to floats using the float() function. Then, we calculate the perimeter of the rectangle using the formula, and store it in the variable perimeter. Finally, we print the result using the print() function.









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 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: 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&#