Pythonは、シンプルで読みやすい構文を持つプログラミング言語です。以下にPythonの基本構文を簡単にまとめました。
—
## **1. コメント**
– **単一行コメント**: `#`を使う
“`python
# これはコメントです
print(“Hello, World!”) # この行の後半もコメント
“`
– **複数行コメント**: `”’` または `”””` を使用
“`python
”’
この部分はコメントです。
複数行にわたります。
”’
“`
—
## **2. 変数の宣言とデータ型**
– **変数の宣言**: 型を明示する必要はありません。
“`python
x = 10 # 整数型
y = 3.14 # 浮動小数点型
name = “Alice” # 文字列型
is_active = True # ブール型
“`
– **型の確認**: `type()`を使用
“`python
print(type(x)) # <class ‘int’>
print(type(y)) # <class ‘float’>
“`
—
## **3. 基本的なデータ型**
| データ型 | 説明 | 例 |
|————-|————————–|————————|
| `int` | 整数型 | `10`, `-5` |
| `float` | 浮動小数点型 | `3.14`, `-0.01` |
| `str` | 文字列型 | `”Hello”`, `’World’` |
| `bool` | 真偽値(ブール型) | `True`, `False` |
| `list` | リスト(配列のようなもの)| `[1, 2, 3]` |
| `tuple` | タプル(変更不可なリスト)| `(1, 2, 3)` |
| `dict` | 辞書(キーと値のペア) | `{“key”: “value”}` |
| `set` | 集合(重複なし) | `{1, 2, 3}` |
—
## **4. 条件分岐**
– **if文**
“`python
x = 10
if x > 5:
print(“xは5より大きい”)
elif x == 5:
print(“xは5と等しい”)
else:
print(“xは5より小さい”)
“`
—
## **5. ループ**
– **forループ**
“`python
for i in range(5): # 0から4まで繰り返す
print(i)
“`
– **whileループ**
“`python
count = 0
while count < 5:
print(count)
count += 1
“`
—
## **6. 関数**
– **関数の定義**
“`python
def greet(name):
return f”Hello, {name}!”
print(greet(“Alice”)) # Hello, Alice!
“`
—
## **7. クラスとオブジェクト**
– **クラスの定義**
“`python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
return f”My name is {self.name} and I am {self.age} years old.”
person = Person(“Alice”, 25)
print(person.greet()) # My name is Alice and I am 25 years old.
“`
—
## **8. リスト操作**
– **リストの作成と操作**
“`python
fruits = [“apple”, “banana”, “cherry”]
fruits.append(“orange”) # 要素を追加
fruits.remove(“banana”) # 要素を削除
print(fruits) # [‘apple’, ‘cherry’, ‘orange’]
“`
—
## **9. 辞書操作**
– **辞書の作成と操作**
“`python
person = {“name”: “Alice”, “age”: 25}
print(person[“name”]) # Alice
person[“age”] = 26 # 値を更新
print(person) # {‘name’: ‘Alice’, ‘age’: 26}
“`
—
## **10. ファイル操作**
– **ファイルの読み書き**
“`python
# 書き込み
with open(“example.txt”, “w”) as file:
file.write(“Hello, World!”)
# 読み込み
with open(“example.txt”, “r”) as file:
content = file.read()
print(content) # Hello, World!
“`
—
## **11. 例外処理**
– **try-except文**
“`python
try:
x = 10 / 0
except ZeroDivisionError:
print(“ゼロで割ることはできません”)
finally:
print(“処理終了”)
“`
—
これらはPythonの基本的な構文の一部です。さらに詳しい内容や具体例が必要であれば、気軽に質問してください!