Python Basics - Q&A
1. Define function in Python:
In Python, a function is defined using the 'def' keyword followed by the function name,
parentheses (which may include parameters), and a colon. The body of the function is
indented.
Syntax:
def function_name(parameters):
# code block
return result
Example:
def greet():
print("Hello, World!")
2. Explain two ways to add objects/elements to list:
1. append() – Adds one item to the end of the list
fruits = ["apple", "banana"]
fruits.append("orange")
2. extend() – Adds multiple items to the list
fruits = ["apple", "banana"]
fruits.extend(["orange", "grape"])
3. Use of any four methods in math module:
1. math.sqrt(x): Returns square root
Example: math.sqrt(16) → 4.0
2. math.pow(x, y): Returns x raised to the power y
Example: math.pow(2, 3) → 8.0
3. math.floor(x): Rounds down a float to nearest integer
Example: math.floor(3.7) → 3
4. math.pi: Returns the constant π
Example: math.pi → 3.14159...
4. Describe any two data conversion functions:
1. int(): Converts a value to an integer
x = "10"
y = int(x)
print(y) # Output: 10
2. str(): Converts a value to a string
num = 25
text = str(num)
print(text) # Output: '25'
5. Define Data Hiding concept with advantages:
Data Hiding is an OOP concept where internal class details (like variables) are kept private
to prevent direct access from outside the class.
Example:
class Person:
def __init__(self, name):
self.__name = name
Advantages:
1. Security and protection of internal object state
2. Supports encapsulation and modular code design
6. Use of lambda function in Python:
A lambda function is a small anonymous function used for short tasks, especially useful in
functions like map(), filter(), etc.
Example:
add = lambda a, b: a + b
print(add(3, 4)) # Output: 7
7. List of built-in class attributes in Python:
1. __dict__ – Dictionary of class namespace
2. __doc__ – Documentation string
3. __name__ – Class name
4. __module__ – Module name where class is defined
5. __bases__ – Tuple of base classes
8. Compare between local and global variable:
Local Variable Global Variable
Declared inside a function Declared outside all functions
Accessible only within that function Accessible anywhere in the code
9. Two differences between List and Tuple:
List Tuple
Mutable (can be changed) Immutable (cannot be changed)
Defined with square brackets [] Defined with parentheses ()
10. Syntax of defining class in Python:
Example:
class ClassName:
def __init__(self, parameter1):
self.parameter1 = parameter1
def method_name(self):
print("This is a method")
Here’s a well-structured answer to the question:
1. Describe Module in Python with its Advantages
✅ What is a Module in Python?
A module in Python is simply a file containing Python code (functions, classes, or variables)
which can be imported and used in other Python programs.
Modules help organize and reuse code efficiently.
✅ How to Use a Module:
You can import a module using the import statement.
Example:
import math
print(math.sqrt(25)) # Output: 5.0
✅ Advantages of Using Modules in Python:
1. Code Reusability:
Functions and classes written in one module can be reused in different programs
without rewriting them.
2. Improved Organization:
Breaks down a large codebase into smaller, logical pieces, making the program more
readable and manageable.
3. Avoids Name Conflicts:
Modules maintain their own namespaces, which helps prevent variable and function
name conflicts.
4. Access to Built-in Functions:
Python provides many useful standard modules like math, datetime, random, etc.,
that save time and effort.
Sure! Here's a clear and simple answer for your second question:
2. Describe 'self' Parameter with Example
✅ What is self in Python?
In Python, self represents the instance of the class.
It is used to access variables and methods associated with the current object.
self must be the first parameter of any method inside a class, although it's not
passed when the method is called — Python handles it automatically.
✅ Why is self important?
It allows each object to keep its own data.
It helps differentiate between instance variables and local variables inside a
method.
✅ Example:
class Student:
def __init__(self, name):
self.name = name # 'self.name' is an instance variable
def greet(self):
print("Hello, my name is", self.name)
# Create an object
s1 = Student("Alice")
s1.greet() # Output: Hello, my name is Alice
In this example:
self.name = name assigns the passed name to the instance.
self lets each object keep its own name.
3. Write a Python Program to accept values from user in a list and find the largest
number and smallest number in a list.
numbers = []
n = int(input("How many numbers do you want to enter? "))
for i in range(n):
num = int(input(f"Enter number {i + 1}: "))
numbers.append(num)
# Find largest and smallest number
largest = max(numbers)
smallest = min(numbers)
# Display results
print("Numbers entered:", numbers)
print("Largest number:", largest)
print("Smallest number:", smallest)
4. Design a class Employee with data members: name, department and salary. Create
suitable methods for reading and printing employee information
class Employee:
def __init__(self):
self.name = ""
self.department = ""
self.salary = 0.0
def read_info(self):
self.name = input("Enter employee name: ")
self.department = input("Enter department: ")
self.salary = float(input("Enter salary: "))
def display_info(self):
print("\nEmployee Information:")
print("Name:", self.name)
print("Department:", self.department)
print("Salary:", self.salary)
# Create object and use methods
emp = Employee()
emp.read_info()
emp.display_info()
5. Write a program for importing module for addition and subtraction of two numbers.
Here's a simple way to create a Python program that imports a module and performs
addition and subtraction using functions defined in that module.
Step 1: Create a module named mymath.py
# mymath.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
✅ Step 2: Create another Python file to import and use the module
# main.py
import mymath
# Input from user
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
# Perform operations
sum_result = mymath.add(num1, num2)
diff_result = mymath.subtract(num1, num2)
# Display results
print("Addition:", sum_result)
print("Subtraction:", diff_result)
6. Write any four methods of dictionary.
dict.keys()
Returns a list of all the keys in the dictionary.
my_dict = {"name": "Alice", "age": 25}
print(my_dict.keys()) # Output: dict_keys(['name', 'age'])
dict.values()
Returns a list of all the values in the dictionary.
print(my_dict.values()) # Output: dict_values(['Alice', 25])
dict.items()
Returns all key-value pairs as a list of tuples.
print(my_dict.items()) # Output: dict_items([('name', 'Alice'), ('age', 25)])
dict.get(key)
Returns the value of the specified key. Returns None if the key is not found.
print(my_dict.get("name")) # Output: Alice
print(my_dict.get("city")) # Output: None
7. Illustrate with example method over loading.
Method Overloading in Python
🔹 What is Method Overloading?
Method Overloading means defining multiple methods with the same name but
different numbers or types of parameters.
Python does not support method overloading like some other languages (e.g.,
Java or C++).
But we can simulate it using default arguments or variable-length arguments.
✅ Example using default arguments:
class Calculator:
def add(self, a=0, b=0, c=0):
return a + b + c
# Create object
calc = Calculator()
# Call method with different number of arguments
print(calc.add(5, 10)) # Output: 15
print(calc.add(2, 3, 4)) # Output: 9
print(calc.add()) # Output: 0
🧠 In this example:
One method add() handles 0, 2, or 3 arguments using default values.
This is a way to simulate method overloading in Python.
Would you like me to add this explanation and example to your Word document?
9. Explain four built-in list functions.
Four Built-in List Functions in Python
append()
Adds a single element to the end of the list.
fruits = ["apple", "banana"]
fruits.append("orange")
print(fruits) # Output: ['apple', 'banana', 'orange']
remove()
Removes the first occurrence of the specified value.
fruits.remove("banana")
print(fruits) # Output: ['apple', 'orange']
sort()
Sorts the list in ascending order (by default).
numbers = [5, 2, 9, 1]
numbers.sort()
print(numbers) # Output: [1, 2, 5, 9]
pop()
Removes and returns the last item (or an item at a specific index).
item = numbers.pop()
print(item) # Output: 9
print(numbers) # Output: [1, 2, 5]
10. Explain different functions or ways to remove key : value pair from Dictionary.
. Wys to Remove Key:Value Pair from a Dictionary
1. pop(key)
Removes the specified key and returns its value.
Raises KeyError if the key is not found (unless default value is given).
my_dict = {'a': 1, 'b': 2, 'c': 3}
value = my_dict.pop('b')
print(my_dict) # Output: {'a': 1, 'c': 3}
2. popitem()
Removes and returns the last inserted key-value pair (in Python 3.7+).
pair = my_dict.popitem()
print(pair) # Output: ('c', 3)
print(my_dict) # Output: {'a': 1}
3. del Statement
Deletes the key-value pair by key.
my_dict = {'x': 10, 'y': 20}
del my_dict['y']
print(my_dict) # Output: {'x': 10}
4. clear()
Removes all items from the dictionary (empties it).
my_dict.clear()
print(my_dict) # Output: {}