Python基本概念と操作

Pythonのダウンロードリンク:

https://www.python.org/downloads/release/python-3104/

PyCharmのインストール:

https://www.jetbrains.com.cn/

コメントとリテラル

"""
複数行のコメント
"""
# 1行のコメント

変数とデータ型

balance = 200
print("残高:", balance)

balance_type = type(balance)
print(balance_type)

データ型の変換

number = 200
str_number = str(number)
print(type(str_number), str_number)

int_string = int("200")
print(type(int_string), int_string)

float_string = float("15.75")
print(type(float_string), float_string)

識別子の命名規則

変数名は英文字母、数字、アンダースコアのみを使用可能。

変数名の例: student_name

演算子

# 整数除算
11 // 2 = 5
# 剰余
11 % 2 = 1
# 累乗
2 ** 3 = 8

文字列

文字列の定義

text = """
これは
複数行の
文字列です。
"""
print(type(text))

文字列の連結

# +を使って文字列を連結
full_name = "ジョン" + " ドウ"
print(full_name)

文字列と他の型の連結

# %を使ってフォーマット
age = 25
message = "私は%d歳です" % age
print(message)

name = "ジョン"
message = "%sは%d歳です" % (name, age)
print(message)

数字の桁数制御

# 数値のフォーマット
price = 123.456
formatted_price = "%.2f" % price
print(formatted_price)

f-stringによる高速フォーマット

item_price = 45.678
product_name = "ペン"
description = f"商品名: {product_name}, 価格: {item_price:.2f}"
print(description)

ユーザーからの入力

username = input("あなたの名前は何ですか?")
print(f"こんにちは、{username}さん!")

ブール型

true_value = True
false_value = False

a = 10
b = 12
print(a > b, type(a > b))

条件文

person_age = 20
if person_age == 20:
    print("20歳になりましたね")
elif person_age > 20:
    print("20歳以上です")
else:
    print("まだ20歳ではありません")
print("時間は早いですね")

whileループ

# 1から100までの数を合計
counter = 1
total = 0
while counter <= 100:
    total += counter
    counter += 1
print(total)

改行なし出力とタブ

# 改行なしで出力
print("こんにちは", end="")
print("世界", end="")

# タブを使って整列
print("こんにちは\t世界")
print("仕事\t範囲")

forループ

phrase = "こんにちは 世界 おcéan 私たち 起こっている"
count_o = 0
for char in phrase:
    if char == "お":
        count_o += 1
print(count_o)

continueとbreak

continue: 現在のイテレーションをスキップし、次のイテレーションへ進む。

break: ループを完全に終了する。

range()

# 0から9までの数列
for num in range(10):
    print(num)

# 5から9までの数列
for num in range(5, 10):
    print(num)

# 5から9までの数列、ステップ2
for num in range(5, 10, 2):
    print(num)

関数

# 関数の定義
def sum_two_numbers(x, y):
    total = x + y
    print(f"{x} + {y} = {total}")

# 関数の呼び出し
sum_two_numbers(3, 4)

# 戻り値のある関数
def add_numbers(x, y):
    """
    2つの数を足す関数
    :param x: 第1数値
    :param y: 第2数値
    :return: 2つの数値の和
    """
    return x + y

# 関数の呼び出しと結果の表示
result = add_numbers(3, 4)
print(result)

None

関数が明示的に値を返さない場合、Noneが返されます。

globalキーワード

global_var = 300
def modify_global():
    global global_var
    global_var = 600
    print(global_var)
modify_global()
print(global_var)

リスト

# リストの作成
sample_list = ["こんにちは", "世界", "発生"]
# 要素のインデックス取得
index_hello = sample_list.index("こんにちは")
print(index_hello)

# 要素の更新
sample_list[1] = "グローバル"
print(sample_list)

# 要素の挿入
sample_list.insert(1, "新しい")
print(sample_list)

# 要素の追加
sample_list.append("追加")
print(sample_list)

# 複数の要素の追加
another_list = [1, 2, 3]
sample_list.extend(another_list)
print(sample_list)

# 要素の削除
del sample_list[0]
print(sample_list)

# 要素の取り出しと削除
element = sample_list.pop(2)
print(element)
print(sample_list)

# 最初に一致する要素の削除
sample_list = ["こんにちは", "世界", "世界", "発生"]
sample_list.remove("世界")
print(sample_list)

# リストのクリア
sample_list.clear()
print(sample_list)

# 要素のカウント
sample_list = ["こんにちは", "世界", "世界", "発生"]
count_world = sample_list.count("世界")
print(count_world)

# リストの長さ
list_length = len(sample_list)
print(list_length)

リストのイテレーション

sample_list = ["こんにちは", "世界", "世界", "発生"]
index = 0
while index < len(sample_list):
    print(sample_list[index])
    index += 1

for element in sample_list:
    print(element)

タプル

# タプルの作成 (読み取り専用)
tuple_example = ("タプル", False, "hi")
# インデックスの取得
index_hi = tuple_example.index("hi")
print(index_hi)

# カウント
count_h = tuple_example.count("h")
print(count_h)

# 長さ
tuple_length = len(tuple_example)
print(tuple_length)

文字列の操作

# 文字列のトリム
string_example = "   Pythonの世界   "
trimmed_string = string_example.strip()
print(trimmed_string)

# 特定の文字をトリム
trimmed_specific = string_example.strip(" ")
print(trimmed_specific)

シーケンスのスライシング

# スライシングの例
sequence = [0, 1, 2, 3, 4, 5]
sliced_sequence = sequence[1:5:2]
print(sliced_sequence)

# 逆順のスライシング
reverse_slice = sequence[::-1]
print(reverse_slice)

セット

# セットの作成 (重複排除)
unique_set = {"apple", "banana", "banana", "cherry"}
empty_set = set()
print(unique_set)
print(empty_set)

# 要素の追加
unique_set.add("date")
print(unique_set)

# 要素の削除
unique_set.remove("banana")
print(unique_set)

# ランダムな要素の取り出しと削除
random_element = unique_set.pop()
print(random_element)
print(unique_set)

# セットのクリア
unique_set.clear()
print(unique_set)

# 差集合
set_one = {1, 2, 3, 4}
set_two = {3, 4, 5, 6}
difference_set = set_one.difference(set_two)
print(difference_set)

# 差集合の更新
set_one.difference_update(set_two)
print(set_one)

# 結合
union_set = set_one.union(set_two)
print(union_set)

ディクショナリー

# ディクショナリーの作成
score_dict = {"alice": 88, "bob": 92, "carol": 90}
print(score_dict)

# キーによる値の取得
alice_score = score_dict["alice"]
print(alice_score)

# 追加または更新
score_dict["dave"] = 85
print(score_dict)

# キーによる値の削除と取得
removed_value = score_dict.pop("bob")
print(removed_value)
print(score_dict)

# クリア
score_dict.clear()
print(score_dict)

# キーのリスト取得
keys = score_dict.keys()
print(keys)

# ディクショナリーのイテレーション
for key in keys:
    print(f"{key}: {score_dict[key]}")

for key in score_dict:
    print(f"{key}: {score_dict[key]}")

コンテナの一般的な操作

最大値と最小値

numbers_set = {10, 20, 30, 40, 50}
max_number = max(numbers_set)
min_number = min(numbers_set)
print(max_number, min_number)

コンテナの変換

# セットからリストへの変換
list_from_set = list(numbers_set)
print(list_from_set)

# セットからタプルへの変換
tuple_from_set = tuple(numbers_set)
print(tuple_from_set)

# セットから文字列への変換
string_from_set = str(numbers_set)
print(string_from_set)

# ディクショナリーからセットへの変換
keys_set = set(score_dict)
print(keys_set)

ソートと逆順ソート

# ソート
sorted_numbers = sorted(numbers_set)
print(sorted_numbers)

# 逆順ソート
reverse_sorted_numbers = sorted(numbers_set, reverse=True)
print(reverse_sorted_numbers)

文字列比較

# ASCIIコードに基づく比較
comparison_result = 'b' > 'abc'
print(comparison_result)

関数の複数の戻り値

# 複数の戻り値を持つ関数
def multiple_returns():
    return 10, "こんにちは", False

val1, val2, val3 = multiple_returns()
print(val1, val2, val3)

関数のパラメータ

# 位置パラメータ
def greet_user(name, age):
    print(f"{name}さんは{age}歳です")
greet_user("田中", 25)

# キーワードパラメータ
greet_user(age=25, name="田中")

# デフォルトパラメータ
def greet_with_gender(name, age, gender="男性"):
    print(f"{name}さんは{age}歳で{gender}です")
greet_with_gender("田中", 25)
greet_with_gender("田中", 25, "女性")

# 可変長パラメータ (*args)
def print_args(*args):
    print(args)
print_args("apple", "banana", "cherry")

# キーワード可変長パラメータ (**kwargs)
def print_kwargs(**kwargs):
    print(kwargs)
print_kwargs(name="田中", age=25, gender="男性")

lambda関数

# lambda関数の使用
def apply_function(func, x, y):
    result = func(x, y)
    print(result)
apply_function(lambda a, b: a + b, 5, 3)

ファイル操作

# ファイルの開閉
file_path = "D:/example/text.txt"
with open(file_path, "r", encoding="utf-8") as file:
    content = file.read()
    print(content)

# ファイルへの書き込み
with open(file_path, "w", encoding="utf-8") as file:
    file.write("新しい内容を追加します")

例外処理

# 例外のキャッチ
try:
    with open("D:/example/nonexistent.txt", "r", encoding="utf-8") as file:
        data = file.read()
except FileNotFoundError as e:
    print(f"ファイルが見つかりません: {e}")
    with open("D:/example/nonexistent.txt", "w", encoding="utf-8") as file:
        file.write("新しいファイルを作成しました")
except Exception as e:
    print(f"エラーが発生しました: {e}")
finally:
    print("処理が完了しました")

Pythonパッケージ

Pythonパッケージは、複数のモジュールを含むディレクトリです。

__init__.pyファイルが存在すると、そのディレクトリがパッケージとして認識されます。

__all__変数を使って、import *によってインポートされるモジュールを制御できます。

サードパーティパッケージのインストール:

pip install -i https://pypi.tuna.tsinghua.edu.cn/simple numpy

JSONデータの変換

import json

# PythonオブジェクトからJSONへの変換
data_list = [{"名前": "山田", "年齢": 30}, {"名前": "佐藤", "年齢": 28}]
json_string = json.dumps(data_list, ensure_ascii=False)
print(json_string)

# JSONからPythonオブジェクトへの変換
json_input = '[{"名前": "山田", "年齢": 30}, {"名前": "佐藤", "年齢": 28}]'
parsed_data = json.loads(json_input)
print(parsed_data)

タグ: Python 基本概念 データ型 変数 演算子

6月26日 18:13 投稿