본문 바로가기

카테고리 없음

Python #3

In this session, we'll delve into more advanced Python features, including modules, libraries, and an introduction to some popular Python libraries for data manipulation and visualization.

Modules and Packages

Modules are files containing Python code that can be imported into other Python scripts. Packages are collections of modules.

Creating a Module

Create a file named mymodule.py:

# mymodule.py
def greet(name):
    return f"Hello, {name}!"

Importing a Module

You can import your custom module into another script:

import mymodule

print(mymodule.greet("Alice"))  # Output: Hello, Alice!

Standard Libraries

Python comes with a rich standard library. Here are a few useful modules:

  • math: Provides mathematical functions.
  • datetime: Supplies classes for manipulating dates and times.
  • os: Provides functions for interacting with the operating system.

Example Using math

import math

print(math.sqrt(16))  # Output: 4.0

Popular Python Libraries

Python has a vast ecosystem of third-party libraries. Here are some popular ones:

NumPy

NumPy is used for numerical computations.

import numpy as np

array = np.array([1, 2, 3])
print(array * 2)  # Output: [2 4 6]

Pandas

Pandas is used for data manipulation and analysis.

import pandas as pd

data = {'Name': ['Alice', 'Bob'], 'Age': [25, 30]}
df = pd.DataFrame(data)
print(df)

Matplotlib

Matplotlib is used for creating static, interactive, and animated visualizations.

import matplotlib.pyplot as plt

x = [1, 2, 3]
y = [4, 5, 6]
plt.plot(x, y)
plt.show()

Introduction to Virtual Environments

Virtual environments allow you to manage dependencies for different projects separately.

Creating a Virtual Environment

python -m venv myenv

Activating a Virtual Environment

  • On Windows:

    myenv\Scripts\activate
  • On macOS/Linux:

    source myenv/bin/activate

Installing Packages

Once the virtual environment is activated, you can install packages using pip:

pip install numpy pandas matplotlib

These topics will help you build more complex applications and manage your projects efficiently.