1) What is the difference between list and tuples in Python?
.py
file, it compiles it into bytecode, which is saved as
.pyc
(Python Compiled) files. These are used to make
subsequent executions faster because Python doesn't need to recompile
the code.
.pyc
file can be run on any system where Python is
installed without the need to recompile the source code.
8. What is slicing in Python?
Answer:
Slicing extracts parts of sequences like
lists, strings, or tuples.
example:
# Example list
my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# Slicing from index 2 to 5
sliced_list = my_list[2:6]
print(sliced_list) # Output: [2, 3, 4, 5]
# Example string
my_string = "Python Slicing"
# Slicing from index 0 to 5
sliced_string = my_string[0:6]
print(sliced_string) # Output: "Python"
Slicing Syntax:
-
start:end:step
:-
start
: The index to begin the slice (inclusive). -
end
: The index to end the slice (exclusive). -
step
(optional): The step size between elements in the slice.
-
9. What are local variables and global variables in Python?
Answer:
- Local Variables: Declared inside functions; accessible only within that function.
- Global Variables: Declared outside all functions; accessible throughout the script.
# Global variable
x = 10
def my_function():
# Local variable
y = 5
print("Local variable y:", y)
# Access global variable
global x
x += 1 # Modify global variable
print("Modified global variable x:", x)
my_function()
print("Global variable x after modification:", x)
Local variable y: 5
Modified global variable x: 11
Global variable x after modification: 11
Key Points:
-
Global variables can be accessed and modified
anywhere if declared as
global
inside a function. - Local variables are restricted to the function in which they are defined and cannot be accessed outside.
10. What is the difference between Python Arrays and lists?
Answer:
-
Arrays: Homogeneous data types; require the
array
module. - Lists: Heterogeneous data types; built-in.
# Python List Example
my_list = [1, "text", 3.14]
print(my_list)
# Python Array Example
import array
my_array = array.array('i', [1, 2, 3]) # 'i' indicates integer array
print(my_array)
11. What is __init__
?
Answer:__init__
is a special
method in Python called a constructor. It initializes object
attributes when the object is created.
Example:
# Define a class
class Person:
# The __init__ method is called when an object is created
def __init__(self, name, age):
self.name = name # Set the name
self.age = age # Set the age
# Display the person's information
def display_info(self):
print(f"Name: {self.name}, Age: {self.age}")
# Create an object of the Person class
person1 = Person("@PythonBeeTelugu", 30)
# Show the person's info
person1.display_info()
Name: @PythonBeeTelugu, Age: 30
Explanation:
-
The
__init__
method is a special method in Python that runs when you create an object. -
It is used to set the initial values of the object's attributes
(
name
andage
). -
In the example, when
person1
is created,name
is set to "@PythonBeeTelugu" andage
is set to 30. - The
display_info
method shows these values.
12. What is a lambda function?
Answer:
A lambda function is an anonymous
function defined using the lambda
keyword.
lambda arguments: expression
. For example,
lambda x, y: x + y
adds two numbers and returns the
result.
# Define a lambda function that adds two numbers
simple_lambda = lambda x, y: x + y
# Use the lambda function
result = simple_lambda(3, 5)
# Print the result
print(result) # Output: 8
13. What is self
in Python?
Answer:self
represents the
instance of the class and is used to access attributes and
methods.
Example:
class PythonClass:
def __init__(self, name):
# `self` refers to the current instance of the class
self.name = name
def say_hello(self):
# `self.name` accesses the instance variable
return f"Hello, {self.name}!"
# Creating an instance of the class
instance = PythonClass("Ravi")
# Calling the method using the instance
print(instance.say_hello()) # Output: Hello, Ravi!
Explanation:
-
self
in__init__
:-
When you create an object (
instance = PythonClass("Ravi")
),self
refers to this specific object. -
self.name = name
sets the instance variablename
to"Ravi"
.
-
When you create an object (
-
Accessing Instance Variables:
-
Inside the
say_hello
method,self.name
is used to access thename
variable of the instance.
-
Inside the
-
Using the Instance:
-
The instance (
instance
) calls the methodsay_hello
. Python automatically passes the instance as the first argument (self
) to the method.
14. What is pickling and unpickling?
Answer:
- Pickling: Serializing Python objects into a byte stream.
- Unpickling: Deserializing the byte stream back to Python objects.
-
Pickling:
- Converts a Python object into a byte stream (serialized format).
- Can store the byte stream in a file or send it over a network.
-
Achieved using
pickle.dump(obj, file)
orpickle.dumps(obj)
.
-
Unpickling:
- Reconstructs the original Python object from the byte stream.
-
Achieved using
pickle.load(file)
orpickle.loads(data)
.
import pickle
# Python object to be pickled
data = {'name': 'Ravi', 'age': 28, 'skills': ['Python', 'FastAPI']}
# Pickling: Save object to a file
with open('data.pkl', 'wb') as file:
pickle.dump(data, file)
print("Data has been pickled and saved to data.pkl")
# Unpickling: Load object from a file
with open('data.pkl', 'rb') as file:
loaded_data = pickle.load(file)
print("Data after unpickling:", loaded_data)
15. What are docstrings in Python?
Answer:
Docstrings are documentation
strings used to explain the purpose of a function, class, or
module.
Example:
"""This is a module-level docstring."""
def add(a, b):
"""Returns the sum of a and b."""
return a + b
class Calculator:
"""A class to perform basic calculations."""
def multiply(self, a, b):
"""Returns the product of a and b."""
return a * b
# Accessing docstrings
print(add.__doc__) # Output: Returns the sum of a and b.
print(Calculator.__doc__) # Output: A class to perform basic calculations.
help(add) # Shows the function's docstring
help(Calculator) # Shows the class's docstring and its methods
help()
or __doc__
to view docstrings at runtime.
Comments
Post a Comment