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のチートシートとして。
できれば皆さんの役に立ちますように
必要があれば追記します。

1.Python実行(Mac)

ターミナルからPython実行

Pythonをインストールして下記コマンド

cd /Users/****/Desktop/Dev/python
python

これ書いてEnterすると下記の画面が出て
Pythonの対話モード(>>>)になる

Python 3.10.9 (main, Mar  1 2023, 12:20:14) [Clang 14.0.6 ] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 

なお、やめるときはquit()と書いてEnterすれば移動したパスのところに戻る

ファイルからPython実行

前もってcdでPythonを使う予定のフォルダに移動しておく
例えばMacでデスクトップのDevフォルダのpythonフォルダに移動して
app.pyを実行する場合は下記

cd /Users/****/Desktop/Dev/python
python app.py

2.仮想環境

仮想環境の作成

以下の作成のところで
venv という名前のディレクトリが作成され、その中に仮想環境が構築
結構よく使う

### 仮想環境の作成
python -m venv venv
##  仮想環境の有効化(Mac)
source venv/bin/activate
## 仮想環境の終了(無効化)->Command + c でも(macの場合)
deactivate

## パッケージのインストール(例: requests)
deactivate
## 必要パッケージを記録
pip freeze > requirements.txt
## 仮想環境に同じ環境を再現
pip install -r requirements.txt

3.チートシート

出力

print('Hello, World')

単数行コメント

# これはコメントです

複数行コメント

#### 複数行コメント(推奨される正式な方法)###

# 1行目のコメント
# 2行目のコメント
# 3行目のコメント

#### 文字列リテラルを使った疑似コメント(非公式)###

"""
このようにクォートを使うことで
複数行の説明文を書くこともできる
主にdocstringに使われる
"""

変数と演算子

下3行がちょっと記憶曖昧なので注意

x = 10
y = 3
print(x + y)    
print(x * y)    
print(x / y)    
print(x // y)   # 整数除算
print(x % y)    # 剰余
print(x ** y)   # 累乗

リスト

fruits = ['apple', 'banana', 'cherry']
print(fruits[0])          # 要素アクセス
fruits.append('orange')   # 追加
fruits.remove('banana')   # 値指定で削除
del fruits[1]             # インデックス削除

more = ['grape', 'melon']
combined = fruits + more  # 結合

辞書

辞書はまあまあ、よく使うよね
VBAにもあるし

person = {"name": "Alice", "age": 25}
print(person["name"])          # アクセス
person["city"] = "Tokyo"       # 追加
del person["age"]              # 削除

people = [{"name": "A"}, {"name": "B"}]
for p in people:
    print(p["name"])

タプル

タプルは変更不可のリストのようなもの、順序あり、辞書のキーなどに使える
未だにわかってない概念。復習必要かも

# タプルはカッコ () を使い、変更できないリストのようなもの
colors = ('red', 'green', 'blue')

# 要素へのアクセス
print(colors[0])  # => 'red'

# アンパック(複数代入)
point = (3, 7)
x, y = point
print(x, y)  # => 3 7

# 1要素のタプルを作るにはカンマが必要
single = ('apple',)
print(type(single))  # => <class 'tuple'>

# タプルはイミュータブル(変更不可)
# colors[0] = 'yellow'  ← 実行するとエラー

集合(set)

集合:順序なし、重複なし、集合演算が可能

# 集合は波カッコ {} または set() を使い、重複しない要素の集まりを表す
fruits = {'apple', 'banana', 'apple', 'orange'}
print(fruits)  # => {'banana', 'orange', 'apple'}(重複が自動で消える)

# 要素の追加
fruits.add('grape')

# 要素の削除
fruits.remove('banana')  # removeは対象がなければエラー
fruits.discard('melon')  # discardは存在しなくてもエラーなし

# 他の集合との演算
a = {'apple', 'banana'}
b = {'banana', 'cherry'}

print(a & b)  # 積集合(共通) => {'banana'}
print(a | b)  # 和集合(すべて) => {'apple', 'banana', 'cherry'}
print(a - b)  # 差集合(aからbを引く) => {'apple'}

# 空の集合は set() で作る({} は空辞書になる)
empty_set = set()
print(type(empty_set))  # => <class 'set'>

# 0〜9までのうち、偶数だけを集めた集合を作る内包表記
even_set = {x for x in range(10) if x % 2 == 0}
print(even_set)  # => {0, 2, 4, 6, 8}

繰り返し

あ、、、while忘れた。。。

# for文
for i in range(3):
    print(i)

# while文
i = 0
while i < 3:
    print(i)
    i += 1

# リストループ
for fruit in ['apple', 'banana']:
    print(fruit)

# 辞書ループ
person = {'name': 'Taro', 'age': 30}
for key, val in person.items():
    print(key, val)

# 内包表記
nums = [1, 2, 3]
squares = [n**2 for n in nums]
even = [n for n in nums if n % 2 == 0]

if文

時々:を忘れる。他の言語と違うところだよなぁ
Case文も一応はあるが今んところあんまり使ってない?
必要なら追記します

x = 10
if x > 5:
    print("大きい")
elif x == 5:
    print("等しい")
else:
    print("小さい")

関数

引数は()の中、戻り値はreturnで返す。

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

def add(a, b):
    return a + b

greet("Taro")
print(add(2, 3))

オブジェクト・クラス

ちなみに、クラスや関数を先に書いて最後に本文を書くのが良い。
下記の場合だと、dog = Dog("Pochi")以下が本文。

class Dog:
    def __init__(self, name):
        self.name = name

    def bark(self):
        print(f"{self.name} says woof!")

dog = Dog("Pochi")
dog.bark()
dog.breed = "Shiba"  # 属性追加
del dog.name         # 属性削除

例外処理

ここは他の言語ともよく似ているかな

try:
    result = 10 / 0
except ZeroDivisionError:
    print("ゼロ除算エラー")
finally:
    print("終了処理")

ファイル操作

ファイル操作はよくある。

# 書き込み
with open("sample.txt", "w", encoding="utf-8") as f:
    f.write("Hello File!")

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

クラスの継承

微妙にPHPとかと異なるかな

class Animal:
    def speak(self):
        print("...")

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

cat = Cat()
cat.speak()

モジュール(自作・標準)

ここらへんはJSとよく似ているかな

# sample_module.py
def hello():
    print("Hi from module!")

# main.py
import sample_module
sample_module.hello()

標準ライブラリ

結構よく使う気がします。多分結構使ってる。
math使わねーだろ、と思ったらDeepLearning系でよく使う。
AI扱うなら覚えておかねば。

# math:数学関数
import math
print("--- math ---")
print(math.sqrt(16))          # 平方根
print(math.factorial(5))      # 階乗
print(math.pi)                # 円周率

# random:ランダム処理
import random
print("\n--- random ---")
print(random.randint(1, 10))          # 1〜10の整数
print(random.choice(['A', 'B', 'C'])) # 選択
items = [1, 2, 3, 4]
random.shuffle(items)
print(items)                          # シャッフル

# datetime:日時処理
import datetime
print("\n--- datetime ---")
now = datetime.datetime.now()
print(now)
today = datetime.date.today()
print(today)
tomorrow = today + datetime.timedelta(days=1)
print(tomorrow)

# calendar:カレンダー出力
import calendar
print("\n--- calendar ---")
print(calendar.month(2025, 5))  # 2025年5月のカレンダー

# os:OS操作
import os
print("\n--- os ---")
print(os.name)
print(os.getcwd())
# os.mkdir("test_dir")  # コメント解除でディレクトリ作成

# sys:システム情報
import sys
print("\n--- sys ---")
print(sys.version)
print(sys.argv)  # コマンドライン引数

# pathlib:ファイルパス操作
from pathlib import Path
print("\n--- pathlib ---")
p = Path("example.txt")
print(p.exists())   # 存在確認
print(p.resolve())  # 絶対パス

# statistics:統計処理
import statistics
print("\n--- statistics ---")
data = [1, 2, 3, 4, 4, 5]
print(statistics.mean(data))
print(statistics.median(data))
print(statistics.mode(data))

# collections:便利なデータ構造
from collections import Counter, defaultdict
print("\n--- collections ---")
c = Counter("aabbbcccc")
print(c)
d = defaultdict(int)
d["apple"] += 1
print(d)

# itertools:イテレータ操作
import itertools
print("\n--- itertools ---")
# 無限ループになるため注意:1個だけ表示
for i in itertools.cycle("AB"):
    print(i)
    break

product = list(itertools.product([1, 2], ['a', 'b']))
print(product)

サードパーティ製パッケージ(例: requests)

まずTerminalでpip installをしないといけない

requestsはAPI関連でよく出ますね

pip install requests
import requests
response = requests.get("https://httpbin.org/get")
print(response.status_code)

フレームワーク(例: Flask)

上と同じくTerminalで(以下略)
私の場合はフレームワークは違うけど会社でよく使いますね

pip install flask
from flask import Flask
app = Flask(__name__)

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

# 実行: flask run

APIの呼び出し(例: OpenWeatherMap)

「動かしながら学ぶPython」ではShopifyのAPIを使ったけど
大体やり方は同じです
ただ、仕様は当たり前だけど各団体によって異なるので
APIの確認は必須
まあ、ひとまずリクエストしてどんな形式になってるか確認して
目的のデータに絞って取得するっていう流れでいいのかな?
(仕様はまあ確認したほうがいいかな。。。)

import requests

API_KEY = "your_api_key"
city = "Tokyo"
url = f"https://api.openweathermap.org/data/2.5/weather?q={city}&appid={API_KEY}"

response = requests.get(url)
data = response.json()
print(data["weather"][0]["description"])

番外編:Paiza用 標準入力・出力

普段はあんまりつかわない?
Paiza以外で使った記憶が。。。

# 1行の入力を受け取る
s = input()
print(s)

# 数値として受け取る
n = int(input())
print(n * 2)

#スペース区切りの複数入力
a, b = map(int, input().split())
print(a + b)

#複数行の入力(最初に件数がわかっている場合)
n = int(input())
for _ in range(n):
    line = input()
    print(line)

# 裏技? 入力全体を取得してリスト化
# JSの場合とよく似てるな
import sys
lines = sys.stdin.read().splitlines()
for line in lines:
    print(line)

++++++++++++++++++++++++++++++++++++++++++++++++++++++++

動かしながら学ぶ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?