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. コメント

# 1行コメント
"""
複数行コメント(ドキュメントにも使える)
"""

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


✅ 2. 変数とデータ型

x = 10          # 整数(int)
pi = 3.14       # 浮動小数点(float)
name = "Alice"  # 文字列(str)
flag = True     # 真偽値(bool)
nothing = None  # None(値なし)

ポイント:Pythonは動的型付けなので型宣言不要。


✅ 3. 演算子

# 算術演算子
a + b, a - b, a * b, a / b, a // b, a % b, a ** b

# 比較演算子
==, !=, <, >, <=, >=

# 論理演算子
and, or, not

ポイント// は整数除算、** はべき乗。


✅ 4. 条件分岐

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

ポイント:インデントでブロックを表現。


✅ 5. ループ

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

# while文
count = 0
while count < 5:
   print(count)
   count += 1

ポイントrange(n)は0からn-1まで。


✅ 6. コレクション型

fruits = ["apple", "banana"]       # リスト
coordinates = (10, 20)             # タプル
person = {"name": "Alice", "age": 25}  # 辞書
unique_numbers = {1, 2, 3}         # セット

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


✅ 7. 関数

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

ポイントdefで関数定義、returnで値を返す。


✅ 8. クラス

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

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

ポイント__init__はコンストラクタ、selfはインスタンス自身。


✅ 9. 例外処理

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

ポイントtryで実行、exceptでエラー処理、finallyは必ず実行。


✅ 10. モジュール

import math
print(math.sqrt(16))  # 4.0

ポイントimportでモジュールを読み込み。


✅ 11. 応用構文

🔹 リスト内包表記

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

ポイント:簡潔にリストを生成。

🔹 f文字列

name = "Alice"
print(f"こんにちは、{name}さん")

ポイント:文字列中に変数を埋め込む。

🔹 ラムダ式

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

ポイント:一行で関数を定義。

🔹 ジェネレータ

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()

ポイント:関数に追加処理を簡単に付与。


✅ まとめ

このチートシートでPythonの基本構文+応用構文を網羅できます。
次のステップ

  • PDF版を作成してダウンロード可能にする
  • 図解付きのビジュアルチートシートを作成

👍 この記事を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?