0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Python基礎まとめ

Posted at

はじめに

Pythonは、シンプルで読みやすい構文を持つ高水準プログラミング言語です。本記事では、Pythonの基礎から実践的な使い方まで、幅広くカバーしています。これからPythonを学び始める方や、基礎を固めたい方にとって有用な情報をまとめました。

Pythonの基本を身につけよう

Pythonプログラミングを始めるための予備知識

Pythonとはどんな言語?
Pythonは1991年に開発された高水準プログラミング言語です。以下の特徴を持っています:

  • シンプルで読みやすい構文
  • 幅広い用途(Web開発、データ分析、AI開発など)
  • 豊富なライブラリとフレームワーク
  • 大規模なコミュニティサポート

Pythonの導入とPowerShellの使い方(Windows)

  1. Python公式サイトからインストーラーをダウンロード
  2. インストーラーを実行し、「Add Python to PATH」にチェックを入れてインストール
  3. PowerShellを開き、Python --version コマンドでインストールを確認

Pythonの導入とターミナルの使い方(macOS/Linux)

  1. Homebrewを使用してPythonをインストール:brew install Python
  2. ターミナルを開き、Python3 --version コマンドでインストールを確認

Pythonをインタラクティブモードで実行
ターミナルやPowerShellでPythonコマンドを実行すると、インタラクティブモードを起動します。ここで簡単なコードを試すことができます。

>>> print("Hello, World!")
Hello, World!
>>> 2 + 3
5

Pythonの基本

Pythonプログラムを作成
テキストエディタを使用して、.py拡張子のファイルを作成します。例えば:

hello.py
# hello.py
print("Hello, Python!")

ターミナルでpython hello.pyを実行すると、プログラムが動作します。

変数の取り扱いを理解
Pythonでは、変数の型を明示的に宣言する必要がありません。

x = 5
y = "Hello"
z = 3.14

いろいろな組み込み型
Pythonには様々な組み込み型があります:

  • 数値型(int,float,complex)
  • シーケンス型(list,tuple,range)
  • テキスト型(str)
  • マッピングがた(dict)
  • セット型(set,frozenset)
  • ブール型(bool)

モジュールをインポートしてクラスや関数を利用

import math
print(math.pi)

from datetime import datetime
print(datetime.now())
  • mathモジュールをインポートし、円周率piを表示
  • datetimeモジュールからdatetimeクラスを直接インポートし、現在の日時を表示

プログラムの処理を分岐する・繰り返す

条件判断はif文

x = 10
if x > 0:
    print("Positive")
elif x < 0:
    print("Negative")
else:
    print("Zero")
  • ifを使って、xの値に応じたメッセージを表示

if文を活用

age = 20
is_student = True

if age >= 18 and is_student:
    print("Adult student")
  • andを使ってageが18以上かつis_studentがTrueの場合に"Adult student"を表示

処理を繰り返す

# for loop
for i in range(5):
    print(i)

# while loop
count = 0
while count < 5:
    print(count)
    count += 1
  • range(5)で0から4までをループし、iを出力
  • whileループでcountが5になるまで繰り返す

ループを活用

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)
  • リストの要素を1つずつ取り出して表示

例外の処理について

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero")
finally:
    print("This always executes")
  • try内でゼロ除算エラー(10/0)が発生
  • exceptでエラーをキャッチして"Cannot divide by zero"を表示
  • finallyは例外の有無に関係なく実行される

組み込み型の活用方法

文字列を活用

text = "Hello, Python!"
print(len(text))
print(text.upper())
print(text.split(","))
  • len(text):文字列の長さを取得
  • text.upper():すべて大文字に変換
  • text.split(","):,を区切りとしてリストに分割

リストとタプルを活用

# List
fruits = ["apple", "banana", "cherry"]
fruits.append("date")
print(fruits[0])

# Tuple
coordinates = (10, 20)
x, y = coordinates
  • append("date"):リストに新しい要素を追加
  • fruits[0]:インデックス0の要素を取得("apple")
  • coordinates:(10,20)のように値の変更ができない(immutable)
  • x,y=coordinates:タプルの要素を変数に展開

辞書と集合の操作

# Dictionary
person = {"name": "Alice", "age": 30}
print(person["name"])

# Set
unique_numbers = {1, 2, 3, 3, 4, 5}
print(unique_numbers)
  • {"key": value} のペアでデータを管理
  • person["name"]: キー "name" の値 "Alice" を取得
  • {} で要素を囲む
  • 重複する要素は自動的に排除される

リスト、辞書、集合を生成する内包表記

squares = [x**2 for x in range(10)]
even_squares = {x: x**2 for x in range(10) if x % 2 == 0}
  • 結果: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
  • 結果: {0: 0, 2: 4, 4: 16, 6: 36, 8: 64}
    → 偶数のみをキーにして平方値を格納

Pythonプログラミングを実践してみよう

オリジナルの関数を作成

関数を作成

def greet(name):
    return f"Hello, {name}!"

print(greet("Alice"))
  • def 関数名(引数): 関数を定義
  • return: 値を返す

可変長引数と無名関数の取り扱い

def sum_all(*args):
    return sum(args)

print(sum_all(1, 2, 3, 4))

# Lambda function
square = lambda x: x**2
print(square(5))
  • *args: 可変長引数(タプルとして扱われる)
  • lambda 引数: 戻り値の計算 の形式
  • square(5) で 5**2 を計算

関数を活用

def apply_operation(func, x, y):
    return func(x, y)

add = lambda x, y: x + y
multiply = lambda x, y: x * y

print(apply_operation(add, 5, 3))
print(apply_operation(multiply, 5, 3))
  • 関数を引数として受け取る
  • apply_operation(add, 5, 3) → 5 + 3
  • apply_operation(multiply, 5, 3) → 5 * 3

テキストファイルの読み書き

テキストファイルを読み込む

with open("example.txt", "r") as file:
    content = file.read()
    print(content)
  • "r": 読み取りモード
  • with open(...) as file:: 自動でファイルを閉じる

テキストファイルに文字列を書き込む

with open("output.txt", "w") as file:
    file.write("Hello, File I/O!")
  • "w": 書き込みモード(上書き)

JSONファイルに読み込み

import json

with open("data.json", "r") as file:
    data = json.load(file)
    print(data)
  • json.load(file): JSONデータを辞書として取得

オリジナルのクラスを作成

クラス作成

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def introduce(self):
        return f"My name is {self.name} and I'm {self.age} years old."

alice = Person("Alice", 30)
print(alice.introduce())
  • init: コンストラクタ
  • self.name: インスタンス変数
  • introduce(): メソッド

オリジナルのクラスの活用方法

class BankAccount:
    def __init__(self, balance=0):
        self.balance = balance
    
    def deposit(self, amount):
        self.balance += amount
    
    def withdraw(self, amount):
        if self.balance >= amount:
            self.balance -= amount
        else:
            print("Insufficient funds")
    
    def get_balance(self):
        return self.balance

account = BankAccount(1000)
account.deposit(500)
account.withdraw(200)
print(account.get_balance())
  • deposit(amount): 入金
  • withdraw(amount): 出金(残高不足ならエラーメッセージ)

クラスを継承する

class Animal:
    def __init__(self, name):
        self.name = name
    
    def speak(self):
        pass

class Dog(Animal):
    def speak(self):
        return "Woof!"

class Cat(Animal):
    def speak(self):
        return "Meow!"

dog = Dog("Buddy")
cat = Cat("Whiskers")
print(dog.name, dog.speak())
print(cat.name, cat.speak())
  • Animal: 親クラス
  • Dog, Cat: 子クラスで speak() をオーバーライド

まとめ

この記事では、Pythonの基礎から実践的な使い方まで幅広くカバーしました。Pythonの特徴である読みやすい構文と豊富なライブラリを活かすことで、様々な分野でプログラミングを活用できます。継続的な学習と実践を通じて、Pythonの力を最大限に引き出しましょう。最後まで読んでくださり、ありがとうございました。もし改善点や質問があれば、ぜひコメントしてください!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?