okpy

Pythonエンジニア兼テックリーダーが、多くのプロジェクトとチーム運営から得た実践的な知識を共有するブログです。

Pythonの基礎

Pythonはその簡潔な構文と応用性から、初心者に最適なプログラミング言語です。以下では、Pythonのインストール方法から基本文法、最初のプログラム作成までを詳しく解説します。さらに、Python 3を基準にした基本文法の例を20個紹介し、学びを深めます。


1. Pythonのインストールと環境構築
Python 3を始めるには、インストールと環境設定が必要です。以下は主要OSごとのインストール手順です。

  • Windowsユーザー:
    Python公式サイト(python.org)から最新のPython 3インストーラーをダウンロードし、「Add Python to PATH」にチェックを入れてインストールを完了します。その後、コマンドプロンプトpython --versionを実行してインストールを確認します。

  • Macユーザー:
    Homebrewをインストール後、以下を実行します。

    brew install python
    python3 --version
    
  • Linuxユーザー:
    ターミナルで以下を実行してインストールを完了します。

    sudo apt update
    sudo apt install python3
    python3 --version
    

2. Python 3の基本文法
以下は、Python 3を基準にした基本文法の具体例20個です。

  1. 変数とデータ型
name = "Alice"  # 文字列型
age = 25        # 整数型
height = 160.5  # 浮動小数点型
is_student = True  # 真偽値型

print(f"名前: {name}, 年齢: {age}, 身長: {height}cm, 学生: {is_student}")
  1. 条件分岐
score = 85
if score >= 90:
    print("優秀です!")
elif score >= 70:
    print("よくできました!")
else:
    print("次はもっと頑張りましょう!")
  1. 繰り返し処理
# forループ
for i in range(5):
    print(f"ループ回数: {i}")

# whileループ
count = 0
while count < 3:
    print(f"カウント: {count}")
    count += 1
  1. リスト
fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
print(fruits)

for fruit in fruits:
    print(f"I like {fruit}")
  1. 辞書
person = {"name": "Alice", "age": 25, "city": "Tokyo"}
person["age"] = 26
print(person)
  1. 関数
def greet(name):
    print(f"こんにちは, {name}さん!")

greet("Alice")
greet("Bob")
  1. リスト内包表記
numbers = [1, 2, 3, 4, 5]
squared = [n ** 2 for n in numbers]
print(squared)
  1. ファイル操作
with open("example.txt", "w") as file:
    file.write("Hello, Python!")

with open("example.txt", "r") as file:
    content = file.read()
    print(content)
  1. 例外処理
try:
    number = int(input("数字を入力してください: "))
    print(f"入力された数字は {number} です。")
except ValueError:
    print("無効な入力です。数字を入力してください!")
  1. クラスとオブジェクト
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def introduce(self):
        print(f"私は{self.name}、{self.age}歳です。")

person = Person("Alice", 25)
person.introduce()
  1. タプル
coordinates = (10, 20)
print(f"X: {coordinates[0]}, Y: {coordinates[1]}")
  1. セット
unique_numbers = {1, 2, 3, 4, 4, 5}
print(unique_numbers)
  1. スライス
numbers = [0, 1, 2, 3, 4, 5]
print(numbers[2:5])
  1. ラムダ関数
square = lambda x: x ** 2
print(square(5))
  1. マップ関数
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x ** 2, numbers))
print(squared)
  1. フィルタ関数
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)
  1. zip関数
names = ["Alice", "Bob", "Charlie"]
scores = [85, 90, 88]
result = list(zip(names, scores))
print(result)
  1. 文字列フォーマット
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")
  1. 正規表現
import re
text = "My phone number is 123-456-7890"
match = re.search(r"\d{3}-\d{3}-\d{4}", text)
if match:
    print(f"見つかった番号: {match.group()}")
  1. モジュールのインポート
import math
print(f"円周率: {math.pi}")

3. 最初のプログラムを作成する
Python 3を使用して、最初に「Hello, World!」プログラムを作成してみましょう。

コード例:

print("Hello, World!")

ターミナルでこのプログラムを実行し、Pythonの動作を確認してください。


これらの例を参考に、Python 3の基本をマスターし、次のステップとして簡単なプロジェクトに挑戦してみましょう!