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はシンプルで読みやすい構文が特徴のプログラミング言語です。本記事では、基本構文+応用構文を日本語でまとめ、各項目に丁寧な解説を追加しました。


✅ 基本構文

コメント

# これはコメント
"""
これは複数行コメント
"""

解説# は1行コメント、""" ... """ は複数行コメントや関数の説明に使います。

変数とデータ型

x = 10          # 整数
pi = 3.14       # 浮動小数点
name = "Alice"  # 文字列
flag = True     # 真偽値
nothing = None  # None

解説:Pythonは動的型付けなので型宣言不要。代入するだけでOKです。

演算子

# 算術演算子: +, -, *, /, //, %, **
# 比較演算子: ==, !=, <, >, <=, >=
# 論理演算子: and, or, not

解説// は整数除算、** はべき乗を意味します。

条件分岐

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

解説ifelifelseで条件分岐を行います。インデントでブロックを表現します。

ループ

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

while count < 5:
   print(count)
   count += 1

解説range(n)は0からn-1までの整数を生成します。

コレクション型

fruits = ["apple", "banana"]
coordinates = (10, 20)
person = {"name": "Alice", "age": 25}
unique_numbers = {1, 2, 3}

解説:リストは順序あり、辞書はキーと値、タプルは変更不可、セットは重複なしです。

関数

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

解説defで関数を定義し、returnで値を返します。

クラス

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

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

解説__init__はコンストラクタ、selfはインスタンス自身を指します。

例外処理

try:
   x = 10 / 0
except ZeroDivisionError:
   print("ゼロで割ることはできません")
finally:
   print("終了")

解説tryで実行、exceptでエラー処理、finallyは必ず実行されます。

モジュール

import math
print(math.sqrt(16))

解説importでモジュールを読み込み、math.sqrt()で平方根を計算します。


✅ 応用構文(丁寧な解説付き)

ラムダ式

add = lambda a, b: a + b
print(add(3, 5))

解説:ラムダ式は無名関数を簡潔に書くための構文です。lambda 引数: 式の形で記述します。

リスト内包表記

squares = [x**2 for x in range(5)]

解説:リスト内包表記は、ループを使わずにリストを生成する簡潔な方法です。

ジェネレータ

def gen_numbers():
   for i in range(3):
       yield i

for num in gen_numbers():
   print(num)

解説yieldを使うと、関数がジェネレータになり、値を一つずつ返します。メモリ効率が良いです。

デコレータ

def decorator(func):
   def wrapper():
       print("前処理")
       func()
       print("後処理")
   return wrapper

@decorator
def hello():
   print("こんにちは")

hello()

解説:デコレータは関数に追加機能を付与する仕組みです。@decoratorで簡単に適用できます。


✅ まとめ

このチートシートでPythonの基本構文+応用構文を網羅できます。Qiita記事や学習メモに最適です!

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?