Python の基本

WBOY
リリース: 2024-07-23 17:52:13
オリジナル
866 人が閲覧しました

THE BASICS OF PYTHON

Python は、そのシンプルさと多用途性で知られる高レベルのインタープリタ型プログラミング言語です。 Web開発 データ分析 人工知能 科学計算 自動化 など、用途が多いため広く使われています。その広範な標準ライブラリ、シンプルな構文、動的な型付けにより、経験豊富なプログラマーだけでなく、新しい開発者の間でも人気があります。

Pythonのセットアップ

Python の使用を開始するには、まず Python インタープリターとテキスト エディターまたは IDE (統合開発環境) をインストールする必要があります。人気のある選択肢には、PyCharm、Visual Studio Code、Spyder などがあります。

  • Pythonをダウンロード:

      Python の公式 Web サイトにアクセスします: python.org
    • 「ダウンロード」セクションに移動し、オペレーティング システム (Windows、macOS、Linux) に適したバージョンを選択します。
  • Pythonをインストール:

      インストーラーを実行します。
    • インストールプロセス中に「Add Python to PATH」オプションを必ずチェックしてください。
    • インストールのプロンプトに従います。
  • コードエディタをインストールする Python コードは任意のテキスト エディタで作成できますが、統合開発環境 (IDE) または Python をサポートするコード エディタを使用すると、生産性が大幅に向上します。人気のある選択肢をいくつかご紹介します:

      VS Code (Visual Studio Code): Python をサポートする軽量かつ強力なソース コード エディター。
    • PyCharm: Python 開発専用のフル機能の IDE。
    • Sublime Text: コード、マークアップ、散文用の洗練されたテキスト エディター。
  • 仮想環境をインストールする

    仮想環境を作成すると、依存関係を管理し、異なるプロジェクト間の競合を回避するのに役立ちます。

      仮想環境を作成する:
      • ターミナルまたはコマンドプロンプトを開きます。
      • プロジェクト ディレクトリに移動します。
      • コマンドを実行します: python -m venv env
        • これにより、env.という名前の仮想環境が作成されます
    • 仮想環境をアクティブ化します:
      • Windows の場合: .envScriptsactivate
      • macOS/Linux の場合:source env/bin/activate
      • ターミナル プロンプトに (env) または同様のメッセージが表示され、仮想環境がアクティブであることが示されます。
  • 簡単な Python スクリプトを作成して実行する

      Python ファイルを作成します:
    • コードエディターを開きます。
    • hello.py.という名前の新しいファイルを作成します
    • コードを書きます:
    • 次のコードを hello.py に追加します。
  • リーリー
    スクリプトを実行します:
    • ターミナルまたはコマンドプロンプトを開きます。
    • hello.py.を含むディレクトリに移動します
    • 次を使用してスクリプトを実行します: python hello.py
Python でコーディングを開始するには、Python インタープリターとテキスト エディターまたは IDE (統合開発環境) をインストールする必要があります。人気のある選択肢には、PyCharm、Visual Studio Code、Spyder などがあります。

基本構文 Python の構文は簡潔で、学習が簡単です。中かっこやキーワードの代わりにインデントを使用してコード ブロックを定義します。変数は代入演算子 (=) を使用して代入されます。

例:


リーリー

データ型 Python には、以下を含むさまざまなデータ型のサポートが組み込まれています:

    整数 (int): 整数
  • Floats (float): 10 進数
  • 文字列 (str): 文字のシーケンス
  • ブール値 (bool): True または False 値
  • リスト (リスト): 順序付けられたアイテムのコレクション
例:


リーリー

演算子と制御構造

Python は、算術、比較、論理演算などのさまざまな演算子をサポートしています。 if-else ステートメントや for ループなどの制御構造は、意思決定と反復に使用されます。

例:


リーリー

機能

関数は、引数を受け取り値を返す再利用可能なコード ブロックです。コードを整理し、重複を減らすのに役立ちます。

例:


リーリー

モジュールとパッケージ

Python には、数学、ファイル I/O、ネットワーキングなどのさまざまなタスク用のライブラリとモジュールの膨大なコレクションがあります。 import ステートメントを使用してモジュールをインポートできます。

例:


リーリー

ファイル入出力

Python は、テキスト ファイル、CSV ファイルなどを含む、ファイルを読み書きするためのさまざまな方法を提供します。

例:


リーリー

例外処理

Python は Try-Except ブロックを使用してエラーと例外を適切に処理します。

例:


リーリー

オブジェクト指向プログラミング

Python は、クラス、オブジェクト、継承、ポリモーフィズムなどのオブジェクト指向プログラミング (OOP) の概念をサポートします。

Example:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def greet(self):
        print("Hello, my name is " + self.name + " and I am " + str(self.age) + " years old.")

person = Person("John", 30)
person.greet()  # outputs "Hello, my name is John and I am 30 years old."
ログイン後にコピー

Advanced Topics

Python has many advanced features, including generators, decorators, and asynchronous programming.

Example:

def infinite_sequence():
    num = 0
    while True:
        yield num
        num += 1

seq = infinite_sequence()
for _ in range(10):
    print(next(seq))  # prints numbers from 0 to 9
ログイン後にコピー
ログイン後にコピー

Decorators

Decorators are a special type of function that can modify or extend the behavior of another function. They are denoted by the @ symbol followed by the decorator's name.

Example:

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()
ログイン後にコピー

Generators

Generators are a type of iterable, like lists or tuples, but they generate their values on the fly instead of storing them in memory.

Example:

def infinite_sequence():
    num = 0
    while True:
        yield num
        num += 1

seq = infinite_sequence()
for _ in range(10):
    print(next(seq))  # prints numbers from 0 to 9
ログイン後にコピー
ログイン後にコピー

Asyncio

Asyncio is a library for writing single-threaded concurrent code using coroutines, multiplexing I/O access over sockets and other resources, and implementing network clients and servers.

Example:

import asyncio

async def my_function():
    await asyncio.sleep(1)
    print("Hello!")

asyncio.run(my_function())
ログイン後にコピー

Data Structures

Python has a range of built-in data structures, including lists, tuples, dictionaries, sets, and more. It also has libraries like NumPy and Pandas for efficient numerical and data analysis.

Example:

import numpy as np

my_array = np.array([1, 2, 3, 4, 5])
print(my_array * 2)  # prints [2, 4, 6, 8, 10]
ログイン後にコピー

Web Development

Python has popular frameworks like Django, Flask, and Pyramid for building web applications. It also has libraries like Requests and BeautifulSoup for web scraping and crawling.

Example:

from flask import Flask, request

app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello, World!"

if __name__ == "__main__":
    app.run()
ログイン後にコピー

Data Analysis

Python has libraries like Pandas, NumPy, and Matplotlib for data analysis and visualization. It also has Scikit-learn for machine learning tasks.

Example:

import pandas as pd
import matplotlib.pyplot as plt

data = pd.read_csv("my_data.csv")
plt.plot(data["column1"])
plt.show()
ログイン後にコピー

Machine Learning

Python has libraries like Scikit-learn, TensorFlow, and Keras for building machine learning models. It also has libraries like NLTK and spaCy for natural language processing.

Example:

from sklearn.linear_model import LinearRegression
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split

boston_data = load_boston()
X_train, X_test, y_train, y_test = train_test_split(boston_data.data, boston_data.target, test_size=0.2, random_state=0)
model = LinearRegression()
model.fit(X_train, y_train)
print(model.score(X_test, y_test))  # prints the R^2 score of the model
ログイン後にコピー

Conclusion

Python is a versatile language with a wide range of applications, from web development to data analysis and machine learning. Its simplicity, readability, and large community make it an ideal language for beginners and experienced programmers alike.

以上がPython の基本の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ソース:dev.to
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!