Python
Python
Introduction to Python
#### Lists
- **Creating Lists**: Using square brackets `[]`.
```python
my_list = [1, 2, 3, 4]
```
- **List Methods**: Common methods like `append()`, `remove()`, `sort()`, and
slicing.
```python
my_list.append(5)
my_list.remove(2)
```
#### Tuples
- **Creating Tuples**: Using parentheses `()`.
```python
my_tuple = (1, 2, 3, 4)
```
- **Tuple Properties**: Immutable, ordered collections.
```python
# Tuples cannot be changed
```
#### Dictionaries
- **Creating Dictionaries**: Using curly braces `{}` with key-value pairs.
```python
my_dict = {'key1': 'value1', 'key2': 'value2'}
```
- **Dictionary Methods**: Common methods like `get()`, `keys()`, `values()`.
```python
value = my_dict.get('key1')
```
#### Sets
- **Creating Sets**: Using curly braces `{}` or `set()` function.
```python
my_set = {1, 2, 3, 4}
```
- **Set Operations**: Union, intersection, difference.
```python
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2)
```
#### Strings and String Manipulation
- **Creating Strings**: Using single, double, or triple quotes.
```python
my_string = "Hello, World!"
```
- **String Methods**: Common methods like `upper()`, `lower()`, `split()`, `join()`.
```python
upper_string = my_string.upper()
```
#### Inheritance
- **Syntax**: Creating a subclass that inherits from a parent class.
```python
class ChildClass(ParentClass):
def __init__(self, attributes):
super().__init__(attributes)
```
#### Polymorphism
- **Method Overriding**: Redefining methods in a subclass.
```python
class ParentClass:
def method(self):
print("Parent method")
class ChildClass(ParentClass):
def method(self):
print("Child method")
```
#### Encapsulation
- **Access Modifiers**: Using public, protected, and private attributes.
```python
class MyClass:
def __init__(self):
self.public = "Public"
self._protected = "Protected"
self.__private = "Private"
```
JSON data.
```python
import json
tree = ET.parse('data.xml')
root = tree.getroot()
```
os.mkdir('new_directory')
os.chdir('new_directory')
os.listdir()
```
response = requests.get('https://api.example.com/data')
```
app = Flask(__name__)
@app.route('/')
def home():
return 'Hello, Flask!'
```
app = Flask(__name__)
@app.route('/api/data', methods=['GET'])
def get_data():
return jsonify({'data': 'example data'})
```
### 11. Data Science and Machine Learning with Python
iris = load_iris()
X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.2)
model = LogisticRegression()
model.fit(X_train, y_train)
```
sns.set(style="whitegrid")
tips = sns.load_dataset("tips")
sns.boxplot(x="day", y="total_bill", data=tips)
```
- **Plotly**: Creating interactive visualizations.
```python
import plotly.express as px
df = px.data.iris()
fig = px.scatter(df, x='sepal_width', y='sepal_length', color='species')
fig.show()
```
#### SQLite
- **Using SQLite**: Creating and querying SQLite databases.
```python
import sqlite3
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
engine = create_engine('sqlite:///example.db')
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
age = Column(Integer)
Base.metadata.create_all(engine)
```
def print_numbers():
for i in range(10):
print(i)
thread = threading.Thread(target=print_numbers)
thread.start()
```
#### Multiprocessing
- **Using Processes**: Implementing multiprocessing for parallel operations.
```python
from multiprocessing import Process
def print_numbers():
for i in range(10):
print(i)
process = Process(target=print_numbers)
process.start()
```
asyncio.run(main())
```
class TestMath(unittest.TestCase):
def test_add(self):
self.assertEqual(add(2, 3), 5)
if __name__ == '__main__':
unittest.main()
```
#### Decorators
- **Creating Decorators**: Using functions to modify the behavior of other functions.
```python
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
```
with MyContextManager():
print("Inside the context")
```
#### Metaclasses
- **Understanding Metaclasses**: Advanced class customization in Python.
```python
class Meta(type):
def __new__(cls, name, bases, dct):
print("Creating class", name)
return super().__new__(cls, name, bases, dct)
class MyClass(metaclass=Meta):
pass
obj = MyClass()
```
Parameters:
a (int): The first number.
b (int): The second number.
Returns:
int: The sum of a and b.
"""
return a + b
```
#### Implementation
- **Developing the Solution**: Applying Python skills to build the project.
- Example: A web application using Flask, a data analysis tool using Pandas, or an
automation script.