Python入門書


 

Python入門書

はじめに

Pythonはシンプルで習得しやすく、さまざまな分野で活用できるプログラミング言語です。この入門書では、Pythonの基本から実践的な使い方まで、段階的に学んでいきましょう。

Pythonとは

Pythonは1991年にGuido van Rossumによって開発された高水準プログラミング言語です。読みやすい構文と豊富なライブラリが特徴で、初心者からプロフェッショナルまで幅広く使われています。

環境設定

Pythonのインストール

  1. Python公式サイトからお使いのOSに合ったバージョンをダウンロード
  2. インストーラを実行(WindowsではPATHを追加するオプションを選択)
  3. コマンドラインでpython --versionと入力し、インストールを確認

統合開発環境(IDE)

  • Visual Studio Code
  • PyCharm
  • Jupyter Notebook

基本的な構文

最初のプログラム

print("Hello, World!")

変数と基本データ型

# 整数
age = 30

# 浮動小数点
height = 175.5

# 文字列
name = "田中太郎"

# ブール値
is_student = True

条件分岐

age = 18

if age >= 20:
    print("成人です")
elif age >= 18:
    print("18歳以上です")
else:
    print("未成年です")

ループ

# forループ
for i in range(5):
    print(i)  # 0から4まで出力

# whileループ
count = 0
while count < 5:
    print(count)
    count += 1

データ構造

リスト

fruits = ["りんご", "バナナ", "オレンジ"]
print(fruits[0])  # りんご
fruits.append("ぶどう")
print(len(fruits))  # 4

ディクショナリ

person = {
    "name": "佐藤花子",
    "age": 25,
    "city": "東京"
}
print(person["name"])  # 佐藤花子

タプル

coordinates = (35.6895, 139.6917)  # 東京の座標

関数

def greet(name):
    return f"こんにちは、{name}さん!"

message = greet("鈴木")
print(message)  # こんにちは、鈴木さん!

クラスとオブジェクト

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def introduce(self):
        return f"私は{self.name}、{self.age}歳です。"

tanaka = Person("田中", 30)
print(tanaka.introduce())  # 私は田中、30歳です。

例外処理

try:
    number = int(input("数字を入力してください: "))
    result = 100 / number
    print(f"結果: {result}")
except ValueError:
    print("有効な数字を入力してください")
except ZeroDivisionError:
    print("ゼロで割ることはできません")
finally:
    print("処理を終了します")

ファイル操作

# ファイル書き込み
with open("sample.txt", "w", encoding="utf-8") as file:
    file.write("Pythonでファイル操作をしています。\n")
    file.write("2行目の内容です。")

# ファイル読み込み
with open("sample.txt", "r", encoding="utf-8") as file:
    content = file.read()
    print(content)

モジュールとパッケージ

# 標準ライブラリの利用
import random
import datetime

# 乱数生成
random_number = random.randint(1, 100)
print(f"乱数: {random_number}")

# 現在の日時
now = datetime.datetime.now()
print(f"現在: {now}")

実践プロジェクト: 簡易電卓

def calculator():
    print("簡易電卓")
    print("操作: +, -, *, /")
    
    num1 = float(input("1つ目の数字: "))
    operator = input("演算子: ")
    num2 = float(input("2つ目の数字: "))
    
    if operator == "+":
        result = num1 + num2
    elif operator == "-":
        result = num1 - num2
    elif operator == "*":
        result = num1 * num2
    elif operator == "/":
        if num2 == 0:
            return "ゼロで割ることはできません"
        result = num1 / num2
    else:
        return "無効な演算子です"
    
    return f"結果: {result}"

print(calculator())

次のステップ

  • データ分析 (Pandas, NumPy)
  • ウェブ開発 (Django, Flask)
  • 機械学習 (Scikit-learn, TensorFlow)
  • 自動化スクリプト作成

これでPythonの基本は習得できました。実際にコードを書いて練習することで、さらに理解が深まります。プログラミングを楽しみましょう!

コメント

このブログの人気の投稿

ヨーヨーの科学:回転の不思議に迫る

Q4OS:WindowsやMacOSに代わる軽量Linuxディストリビューション

軽快動作!Windowsにクリソツ!Q4OSは神的かも!