Python Full Question Bank Answers
Python Full Question Bank Answers
● Easy to Learn: Python has a simple and readable syntax, making it beginner-friendly.
● Open-Source: Python is free to use, and its open-source nature means a vast
community contributes to its development.
● Cross-Platform: Python runs on various operating systems, making it versatile and
accessible.
● Large Standard Library: Python comes with a rich standard library that simplifies
many common programming tasks.
● Dynamic Typing: Python is dynamically typed, meaning you don't need to declare
variable types, making coding more flexible.
● Interpreted Language: Python is an interpreted language, allowing for quick code
execution without the need for compilation.
● Great Community Support: The Python community is vast, offering resources,
forums, and libraries to help you learn and solve problems.
● High-level Language: Python abstracts many complex programming details, making it
easier to focus on problem-solving.
Certainly, here are the assignment operators in Python with brief explanations:
not Returns the opposite boolean value of the operand. not flag False
These logical operators are fundamental for making decisions and controlling the flow of
your Python code.
== Equal to x == y True
These relational operators allow you to compare values and make decisions based on the
relationships between them in your Python code.
is not Returns True if both variables reference different objects. a is not b True
Result
Arithmetic Operator Description Example
+ Addition 5+3 8
- Subtraction 10 - 4 6
* Multiplication 6*7 42
/ Division 12 / 3 4.0
% Modulus (Remainder) 17 % 4 1
** Exponentiation 2 ** 3 8
Arithmetic operators in Python are used for performing basic mathematical operations on
numeric values. Here's a table with explanations and examples for the common arithmetic
operators:
b=10 + 9 - 4 / (2 - 3) + 1
c=10 + 9 / (4 / 2 - 3) + 1
Expression c = 10 + 9 / (4 / 2 - 3) + 1: So, c = 2.
10. What is an identifier (variable)? What are the rules to construct identifier
(variable)?
Classify the following as valid/invalid Identifiers. i) num2 ii) $num1 iii) +add iv) a_2 v)
199_space vi) _apple vii)#12
3. Identifiers are case-sensitive, meaning `myVar` and `myvar` are considered different
identifiers.
4. Identifiers should not be the same as reserved keywords in Python (e.g., `if`, `while`, `for`,
etc.).
5. Python supports Unicode characters in identifiers, but it's recommended to use ASCII
characters for compatibility and readability.
Now, let's classify the given identifiers as valid or invalid according to these rules:
i) `num2` - Valid
v) `199_space` -
So, the valid identifiers are: `num2`, `a_2`, and `_apple`. The invalid identifiers are: `$num1`,
`+add`, `199_space`, and `#12`.
UNIT 2
1. Explain different loops available in python with syntax and suitable examples
A.For Loop:
● Definition: A for loop is used to iterate over a sequence (such as a list, tuple, or string)
or other iterable objects. It executes a block of code for each item in the sequence.
● Example:
for item in sequence:
# Code to be executed for each item
B.While Loop:
● Definition: A while loop is used to repeatedly execute a block of code as long as a
specified condition is true. It may run zero or more times.
● Example:
while condition:
# Code to be executed while the condition is true
2. Illustrate the different types of conditional branching statements available in Python with
suitable example
A.if Statement:
● Definition: The if statement is used to execute a block of code if a specified condition
is True.
● Example:
x = 10
if x > 5:
print("x is greater than 5")
3. Illustrate the different types of control flow statements available in Python with
flowcharts
A.Conditional Statements (if, elif, else):
● if Statement:
● Definition: The if statement is used to execute a block of code if a specified
condition is True.
elif Statement (Optional):
● Definition: The elif statement is used to check multiple conditions if the previous if or
elif conditions are False.
else Statement (Optional):
● Definition: The else statement is used to execute a block of code if none of the
previous conditions is True.
B.Loop Statements (for, while):
● for Loop:
● Definition: The for loop is used to iterate over a sequence and execute a block
of code for each item in the sequence.
# Code to execute for each item in the sequen
● while Loop:
● Definition: The while loop is used to repeatedly execute a block of code as long
as a specified condition is True.
Example:
print(i)
UNIT 3
Lists (Mutable):
● Lists are mutable, meaning you can add, remove, or modify elements after creation.
● They are defined using square brackets [].
● Lists are typically used when you need a collection of items that may change during
the program, such as a list of tasks or items in a shopping cart.
● Lists have a slightly higher memory consumption and may have lower performance
due to their mutability.
Tuples (Immutable):
● Tuples are immutable, so once you define their elements, you cannot modify them.
● They are defined using parentheses ().
● Tuples are used when you need a collection of items that should remain constant and
not be altered, like coordinates or configurations.
● Tuples are more memory-efficient and may have slightly better performance compared
to lists.
3. What are the different operations that can be performed on a list? Explain with
examples
Various operations can be performed on lists in Python. Here are some common list
operations with brief explanations and examples:
Appending Elements:
● Add an element to the end of the list.
my_list = [1, 2, 3]
my_list.append(4)
Inserting Elements:
● Insert an element at a specific position.
my_list = [1, 2, 3]
my_list.insert(1, 4) # Inserts 4 at index 1
Removing Elements:
● Remove elements by value or index.
my_list = [1, 2, 3, 4]
my_list.remove(2) # Removes element with value 2
my_list.pop(1) # Removes element at index 1 (returns 3)
Sorting:
● Sort elements in ascending or descending order.
my_list = [3, 1, 2]
my_list.sort() # Sort in ascending order
my_list.sort(reverse=True) # Sort in descending order
Finding Length:
● Get the length (number of elements) in a list.
my_list = [1, 2, 3, 4]
length = len(my_list) # Result: 4
4. Explain the following list methods with an example. a) append() b) extend() c) insert()
d) index() e) pop() f) sort()
a) append():
my_list = [1, 2, 3]
my_list.append(4) # Result: [1, 2, 3, 4]
b) extend():
● extend() appends the elements of an iterable (e.g., another list) to the end of the list.
● Example:
my_list = [1, 2, 3]
other_list = [4, 5]
my_list.extend(other_list) # Result: [1, 2, 3, 4, 5]
c) insert():
my_list = [1, 2, 3]
my_list.insert(1, 4) # Inserts 4 at index 1; Result: [1, 4, 2, 3]
d) index():
● index() returns the index of the first occurrence of a specified element in the list.
● Example:
my_list = [1, 2, 3, 2]
index = my_list.index(2) # Result: 1 (index of the first 2)
e) pop():
my_list = [1, 2, 3, 4]
popped = my_list.pop(2) # Removes element at index 2 (value 3) and returns it
f) sort():
● sort() arranges the list's elements in ascending order. Use reverse=True for descending
order.
● Example:
my_list = [3, 1, 2]
my_list.sort() # Sorts in ascending order; Result: [1, 2, 3]
5. Write in brief about Tuple in python. Write operations with suitable examples.
A tuple in Python is an ordered, immutable, and indexed collection of elements. Tuples are
defined using parentheses ()
my_tuple = (1, 2, 3, 4, 5)
Operations on Tuples:
Accessing Elements:
● You can access elements by index, just like in lists.
Slicing:
● You can slice tuples to extract a subset of elements.
sliced_tuple = my_tuple[1:4] # Slices elements from index 1 to 3 (result: (2, 3, 4))
Length:
● Determine the number of elements in a tuple using len().
length = len(my_tuple) # Result: 5
Concatenation:
● Combine two or more tuples using the + operator.
new_tuple = my_tuple + (6, 7) # Concatenates two tuples
6. Write in brief about Set in python. Write operations with suitable examples.
A set in Python is an unordered collection of unique elements. Sets are defined using curly
braces {} or the set() constructor
Adding Elements:
● You can add elements to a set using the add() method.
my_set.add(6) # Adds the element 6 to the set
Removing Elements:
● Remove an element from a set using the remove() method.
my_set.remove(3) # Removes the element 3 from the set
Union of Sets:
● Create a new set that contains all unique elements from multiple sets.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2) # Creates a set containing {1, 2, 3, 4, 5}
Intersection of Sets:
● Create a new set that contains elements common to multiple sets.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
intersection_set = set1.intersection(set2) # Creates a set containing {3}
Difference of Sets:
● Create a new set with elements from one set that are not in another.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
difference_set = set1.difference(set2) # Creates a set containing {1, 2}
7. Write in brief about Dictionary in python. Write operations with suitable examples.
A dictionary in Python is an unordered collection of key-value pairs. Dictionaries are defined
using curly braces {} and have a unique key for each value.
my_dict = {'name': 'Alice', 'age': 30, 'city': 'New York'}
Accessing Values:
● You can access values in a dictionary using their keys
name = my_dict['name'] # Access the value associated with the key 'name'
Modifying Values:
● You can modify the value associated with a key in a dictionary.
my_dict['age'] = 31 # Update the 'age' value to 31
UNIT 4
1. Explain about functions with suitable examples or
A.Predefined (Built-in) Functions:
B.User-Defined Functions:
def is_even_or_odd(number):
if number % 2 == 0:
return "Even"
else:
return "Odd"
num = 7
result = is_even_or_odd(num)
In this program:
● We call the function with a number (e.g., num = 7) and print the result.
variables)
In Python, the scope of a variable refers to where in the code that variable can be accessed or
A.Global Variables:
Example:
global_var = 10
def my_function():
my_function()
B.Local Variables:
● They can only be accessed and modified within the function where they are defined.
● Example:
def my_function():
my_function()
Positional Arguments:
● The values are passed in the order in which parameters are defined in the function.
● Example:
greet("Alice", 30)
Keyword Arguments:
● Values are passed by specifying the parameter names, regardless of their order.
● This provides clarity and can make the code more readable.
● Example:
greet(age=30, name="Bob")
Default Arguments:
● Example:
● These are specified using *args and **kwargs for positional and keyword arguments,
respectively.
● Example:
def add(*numbers):
total = sum(numbers)
return total
● Example:
greet("David", age=35)
function that does not have a name. It is defined using the lambda keyword and can take
multiple arguments but can only contain a single expression. Lambda functions are often used
square = lambda x: x ** 2
In this example:
● We define a lambda function square that takes one argument x and calculates the
square of x.
● We use the lambda function to calculate the square of the number 5 and store the
technique used when a problem can be broken down into smaller, similar sub-problems.
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
7. How to create a module and use it in a python program explain with an example.
Create a Python script with functions or variables you want to use as a module. Save it
with a .py extension. For example, let's create a module named mymodule.py with a
function.
Example (mymodule.py):
def greet(name):
Example (main.py):
import mymodule
result = mymodule.greet("Alice")
Run the main script (main.py), and it can access the functions or variables from the
module (mymodule.py).
UNIT 5
1. What is NumPy array? Why we use NumPy? Explain different types of array
with example
NumPy stands for "Numerical Python" and is a fundamental library in Python for
numerical and mathematical operations. It provides support for arrays and matrices,
NumPy Array:
operations.
● NumPy arrays are optimized for numerical operations and are significantly faster than
and readable.
1-D Array:
● Example:
import numpy as np
● Example:
import numpy as np
3-D Array:
● Example
import numpy as np
Pandas is an open-source Python library used for data manipulation and analysis. It provides
easy-to-use data structures and functions for working with structured data,
DataFrame in Pandas:
table.
● A DataFrame consists of rows and columns, where each column can contain different
data efficiently.
Example
import pandas as pd
data = {
df = pd.DataFrame(data)
import pandas as pd
data = [1, 2, 3, 4, 5]
series = pd.Series(data)
import pandas as pd
import numpy as np
series = pd.Series(data)
import pandas as pd
series = pd.Series(data)
Binary search is an efficient algorithm for finding a specific target value within a sorted
sequence, such as an array. It works by repeatedly dividing the search interval in half.
if arr[mid] == target:
left = mid + 1
else:
right = mid - 1
return -1
sorted_list = [2, 5, 8, 12, 16, 23, 38, 45, 56, 72, 91]
target = 23
if result != -1:
else:
7, Write a python to find the max value with and without using built in functions
def find_max(arr):
if len(arr) == 0:
max_val = arr[0]
max_val = val
return max_val
# Example list
max_value = find_max(my_list)
# Example list
max_value = max(my_list)
atabase:
and management.
and more.
Tables:
● Each row represents a record or entry, and each column represents a field or attribute.
● Tables are used to store related data, and they are linked through keys to establish
relationships.
Fields:
● Fields, also known as attributes or columns, are the individual pieces of data stored in
a table.
● Each field represents a specific type of information related to the records in the table.
● For example, in a table storing information about employees, fields might include