Python Concepts
1. Data Types
Python has several built-in data types:
- Integer: Whole numbers.
- Float: Decimal numbers.
- String: Text enclosed in quotes.
- List: An ordered collection of items.
- Tuple: An immutable ordered collection.
- Dictionary: A collection of key-value pairs.
Example Code:
# Data Types
integer_var = 10 # Integer
float_var = 10.5 # Float
string_var = "Hello" # String
list_var = [1, 2, 3] # List
tuple_var = (1, 2, 3) # Tuple
dict_var = {"key": "value"} # Dictionary
print(integer_var, float_var, string_var, list_var, tuple_var, dict_var)
Here's a single python.mdx
file that includes Python concepts along with their code examples, all in one file as requested. You can save this content directly in your python.mdx
file.
# Python Concepts and Code Examples
## 1. Data Types
### Integer
```python
# Integer
a = 10
print(a)
Float
# Float
b = 10.5
print(b)
String
# String
name = "John"
print(name)
List
# List
fruits = ["apple", "banana", "cherry"]
print(fruits)
Tuple
# Tuple
coordinates = (10.0, 20.0)
print(coordinates)
Dictionary
# Dictionary
person = {"name": "Alice", "age": 25}
print(person)
2. Control Flow
If-Else Statement
# If-Else Statement
num = 10
if num > 0:
print("Positive")
elif num < 0:
print("Negative")
else:
print("Zero")
For Loop
# For Loop
for i in range(5):
print(i)
While Loop
# While Loop
count = 0
while count < 5:
print(count)
count += 1
3. Functions
Function Definition
# Function Definition
def greet(name):
return f"Hello, {name}!"
print(greet("Alice"))
Function with Default Argument
# Function with Default Argument
def greet(name="World"):
return f"Hello, {name}!"
print(greet())
Function with Variable Number of Arguments
# Function with Variable Number of Arguments
def add(*args):
return sum(args)
print(add(1, 2, 3, 4))
4. Classes and Objects
Class Definition
# Class Definition
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
return f"{self.name} says Woof!"
my_dog = Dog("Buddy")
print(my_dog.bark())
Inheritance
# Inheritance
class Animal:
def speak(self):
return "Animal speaks"
class Cat(Animal):
def speak(self):
return "Meow"
my_cat = Cat()
print(my_cat.speak())
5. Exception Handling
Try-Except Block
# Exception Handling
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
finally:
print("This will always execute.")
6. File Handling
Writing to a File
# Writing to a File
with open('example.txt', 'w') as f:
f.write("Hello, World!")
Reading from a File
# Reading from a File
with open('example.txt', 'r') as f:
content = f.read()
print(content)
7. List Comprehensions
# List Comprehensions
squares = [x**2 for x in range(10)]
print(squares)
8. Lambda Functions
# Lambda Functions
add = lambda x, y: x + y
print(add(5, 3))
9. Map, Filter, and Reduce
Map
# Map Function
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x**2, numbers))
print(squared)
Filter
# Filter Function
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)
Reduce
from functools import reduce
# Reduce Function
sum_numbers = reduce(lambda x, y: x + y, numbers)
print(sum_numbers)
10. Modules and Packages
Importing a Module
# Importing a Module
import math
print(math.sqrt(16))
11. Regular Expressions
import re
# Regular Expressions
pattern = r'\d+'
result = re.findall(pattern, 'There are 2 cats and 3 dogs.')
print(result)
12. Working with JSON
import json
# Working with JSON
data = {'name': 'Alice', 'age': 25}
json_data = json.dumps(data)
print(json_data)
parsed_data = json.loads(json_data)
print(parsed_data)
13. Numpy Example
import numpy as np
# Numpy Example
array = np.array([1, 2, 3])
print(array)
14. Pandas Example
import pandas as pd
# Pandas Example
data = {'Name': ['Alice', 'Bob'], 'Age': [25, 30]}
df = pd.DataFrame(data)
print(df)
15. Matplotlib Example
import matplotlib.pyplot as plt
# Matplotlib Example
x = [1, 2, 3, 4]
y = [10, 20, 25, 30]
plt.plot(x, y)
plt.title('Simple Plot')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.show()
16. Simple HTTP Request
import requests
# Simple HTTP Request
response = requests.get('https://api.github.com')
print(response.status_code)
17. Multithreading Example
import threading
# Multithreading Example
def print_numbers():
for i in range(5):
print(i)
thread = threading.Thread(target=print_numbers)
thread.start()
thread.join()
18. Decorators
# Decorators
def decorator_function(original_function):
def wrapper_function():
print("Wrapper executed before {}".format(original_function.__name__))
return original_function()
return wrapper_function
@decorator_function
def display():
return "Display function executed."
print(display())
## Additional Python Interview Questions
### 1. What is the difference between `deepcopy` and `shallow copy`?
- **Shallow Copy**: Creates a new object but inserts references into it to the objects found in the original. Changes made to mutable objects in the shallow copy will reflect in the original.
- **Deep Copy**: Creates a new object and recursively adds copies of nested objects found in the original, meaning changes in the deep copy will not affect the original.
```python
import copy
original = [[1, 2, 3], [4, 5, 6]]
shallow = copy.copy(original)
deep = copy.deepcopy(original)
shallow[0][0] = 'Changed'
print(original) # Output: [['Changed', 2, 3], [4, 5, 6]]
print(deep) # Output: [[1, 2, 3], [4, 5, 6]]
2. What are list comprehensions and provide an example?
List comprehensions provide a concise way to create lists. They consist of brackets containing an expression followed by a for
clause and optionally if
clauses.
# List comprehension to create a list of squares
squares = [x**2 for x in range(10)]
print(squares) # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
3. Explain the concept of generators and provide an example.
Generators are a type of iterable, like lists or tuples. Unlike lists, they do not store their contents in memory but generate items on the fly using the yield
statement.
def countdown(n):
while n > 0:
yield n
n -= 1
for i in countdown(5):
print(i) # Output: 5, 4, 3, 2, 1
4. What is the purpose of the self
keyword in Python?
The self
keyword is used to represent an instance of the class and allows access to the attributes and methods of the class in Python.
class MyClass:
def __init__(self, value):
self.value = value
def display(self):
print(self.value)
obj = MyClass(10)
obj.display() # Output: 10
5. How does exception handling work in Python?
Python uses try
, except
, else
, and finally
blocks to handle exceptions. Code that may raise an exception is placed inside the try
block, and the handling of exceptions occurs in the except
block.
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero.")
else:
print("Division successful.")
finally:
print("Execution completed.")
6. What is the use of the with
statement in Python?
The with
statement is used for resource management and exception handling. It ensures that resources are properly managed, such as closing files automatically.
with open('example.txt', 'r') as file:
content = file.read()
print(content)
# The file is automatically closed after the block.
7. What are the built-in data types in Python?
The built-in data types in Python include:
- Numeric:
int
,float
,complex
- Sequence:
list
,tuple
,range
- Text:
str
- Binary:
bytes
,bytearray
,memoryview
- Set:
set
,frozenset
- Mapping:
dict
8. What is the difference between __str__
and __repr__
?
__str__
: Intended to provide a readable string representation of an object, typically for end-users.__repr__
: Intended to provide a detailed string representation of an object, typically for debugging, and should ideally be a valid Python expression.
class Person:
def __init__(self, name):
self.name = name
def __str__(self):
return f"Person({self.name})"
def __repr__(self):
return f"Person(name='{self.name}')"
person = Person("Alice")
print(str(person)) # Output: Person(Alice)
print(repr(person)) # Output: Person(name='Alice')
9. What is the Global Interpreter Lock (GIL)?
The Global Interpreter Lock (GIL) is a mutex that protects access to Python objects, preventing multiple threads from executing Python bytecodes at once. This makes Python threads less efficient for CPU-bound tasks but suitable for I/O-bound tasks.
10. What are decorators and how do you create one?
Decorators are functions that modify the functionality of another function. They are created using the @decorator
syntax.
def decorator_function(original_function):
def wrapper_function():
print("Wrapper executed before {}".format(original_function.__name__))
return original_function()
return wrapper_function
@decorator_function
def display():
return "Display function executed."
print(display()) # Output: Wrapper executed before display\nDisplay function executed.
11. Explain what a lambda function is in Python.
A lambda function is an anonymous function defined with the lambda
keyword. It can have any number of arguments but can only have one expression.
add = lambda x, y: x + y
print(add(5, 3)) # Output: 8
12. What is the difference between mutable and immutable types?
- Mutable Types: Objects that can be changed after creation (e.g., lists, dictionaries, sets).
- Immutable Types: Objects that cannot be changed after creation (e.g., tuples, strings, frozensets).
# Mutable example
list_example = [1, 2, 3]
list_example[0] = 10
print(list_example) # Output: [10, 2, 3]
# Immutable example
tuple_example = (1, 2, 3)
# tuple_example[0] = 10 # This will raise a TypeError
13. What is a context manager and how do you create one?
A context manager is a Python object that implements the context management protocol, which consists of the methods __enter__()
and __exit__()
. They are used in with
statements to ensure proper resource management.
class MyContextManager:
def __enter__(self):
print("Entering the context.")
return self
def __exit__(self, exc_type, exc_value, traceback):
print("Exiting the context.")
with MyContextManager() as manager:
print("Inside the context.")
14. How do you handle missing keys in a dictionary?
You can handle missing keys in a dictionary by using the get()
method, which allows you to provide a default value if the key does not exist.
my_dict = {'a': 1, 'b': 2}
value = my_dict.get('c', 'Not Found')
print(value) # Output: Not Found
15. What are *args and **kwargs in Python?
*args
allows you to pass a variable number of non-keyword arguments to a function, while **kwargs
allows you to pass a variable number of keyword arguments.
def sample_function(*args, **kwargs):
print("Arguments:", args)
print("Keyword Arguments:", kwargs)
sample_function(1, 2, 3, name='Alice', age=25)