2. Pythonの基本構文

Pythonの基本構文

以下はPythonの基本的な文法の例です。

1. Hello, World!

print("Hello, world!")

2. 変数とデータ型

x = 10         # 整数
y = 3.14       # 浮動小数点数
z = "Python"   # 文字列

3. 条件分岐

age = 18
if age >= 18:
    print("Adult")
else:
    print("Minor")

4. 繰り返し(ループ)

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

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

5. 関数


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

print(greet("Kenji"))

6. クラス

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

    def speak(self):
        return f"{self.name} says hello!"

dog = Animal("Dog")
print(dog.speak())

7. リスト・辞書

# リスト
fruits = ["apple", "banana", "cherry"]
print(fruits[1])

# 辞書
person = {"name": "Kenji", "age": 25}
print(person["name"])

タイトルとURLをコピーしました