1. 変数 ❎
値(文字列、整数、浮動小数点数、ブール値)を格納するコンテナ
変数は、その変数が含む値として振る舞います
# 文字列
first_name = "Bro"
food = "ピザ"
email = "Bro123@gmail.com"
print(f"こんにちは {first_name}")
print(f"あなたは {food} が好きです")
print(f"あなたのメールアドレスは: {email}")
# 整数
age = 25
quantity = 3
num_of_students = 30
print(f"あなたは {age} 歳です")
print(f"あなたは {quantity} 個のアイテムを購入しています")
print(f"あなたのクラスには {num_of_students} 人の生徒がいます")
# 浮動小数点数
price = 10.99
gpa = 3.2
distance = 5.5
print(f"価格は ${price} です")
print(f"あなたのGPAは: {gpa}")
print(f"あなたは {distance}km 走りました")
# ブール値
is_student = False
for_sale = False
is_online = True
if is_online:
print("あなたはオンラインです")
else:
print("あなたはオフラインです")
変数の代入
user_name = "Yuuniji"
year = 2025
pi = 3.14
is_admin = True
print(f"ユーザー名: {user_name}")
print(f"現在の年: {year}")
# 小数点以下2桁に丸める
print(f"円周率: {pi:.2f}")
# ブール値を「はい」または「いいえ」に変換
print(f"管理者ステータス: {'はい' if is_admin else 'いいえ'}")
2. 型変換 💱
型変換 = 変数をあるデータ型から別のデータ型に変換するプロセス
str(), int(), float(), bool()
name = "Yuuniji"
age = 25
gpa = 3.2
is_student = True
# print(type(name))
gpa = int(gpa) # 3
age = float(age) # 25.0
age = str(age)
age += "1" # "251"
name = bool(name) # True
3. ユーザー入力 ⌨️
ユーザーにデータの入力を促す関数
入力されたデータを文字列として返します
name = input("あなたの名前は何ですか?: ")
age = int(input("あなたは何歳ですか?: "))
# age = int(age)
age = age + 1
print(f"こんにちは {name}!")
print("お誕生日おめでとう")
print(f"あなたは {age} 歳です")
演習1 長方形の面積計算
length = float(input("長さを入力してください: "))
width = float(input("幅を入力してください: "))
area = length * width
print(f"面積は: {area}cm²")
#Macの上付き文字2: Command + Control + Space、検索バーに「superscript」または「2」と入力。またはOption + v
演習2 ショッピングカートプログラム
item = input("どのアイテムを購入しますか?: ")
price = float(input("価格はいくらですか?: "))
quantity = int(input("いくつ購入しますか?: "))
total = price * quantity
print(f"あなたは {quantity} 個の {item} を購入しました")
print(f"合計金額は: ${total}")
4. ⭐ マッドリブゲーム
ランダムな単語を空白に埋めてストーリーを作成する単語ゲーム
adjective1 = input("形容詞(説明)を入力してください: ")
noun1 = input("名詞(人、場所、物)を入力してください: ")
adjective2 = input("形容詞(説明)を入力してください: ")
verb1 = input("「ing」で終わる動詞を入力してください: ")
adjective3 = input("形容詞(説明)を入力してください: ")
print(f"今日、私は {adjective1} 動物園に行きました。")
print(f"展示場で、私は {noun1} を見ました")
print(f"{noun1} は {adjective2} で、{verb1} していました")
print(f"私は {adjective3} でした!")
5. 算術演算子と数学関数 📐
friends = 10
friends = friends + 1
friends += 1
friends = friends - 2
friends -= 2
friends = friends * 3
friends *= 3
friends = friends / 2
friends /= 2
friends = friends ** 2
friends **= 2
remainder = friends % 3
x = 3.14
y = 4
z = 5
result = round(x) # 3
result = abs(y) # 4
result = pow(4, 3) # 4*4*4=64
result = max(x, y, z) # 5
result = min(x, y, z) # 3.14
import math
x = 9
y = 9.1
z = 9.9
print(math.pi) # 3.141592653589793
print(math.e) # 2.718281828459045
result = math.sqrt(x) # 3.0
result = math.ceil(y) # 10
result = math.floor(z) # 9
# C = 2πr
import math
radius = float(input('円の半径を入力してください: ')) # 10.5
circumference = 2 * math.pi * radius
print(f"円周は: {round(circumference, 2)}cm") # 65.97
# A = πr²
import math
radius = float(input('円の半径を入力してください: ')) # 10.5
area = math.pi * pow(radius, 2)
print(f"円の面積は: {round(area, 2)}cm²") # 346.36
# c = √(a²+b²)
import math
a = float(input("辺Aを入力してください: ")) # 3
b = float(input("辺Bを入力してください: ")) # 4
c = math.sqrt(pow(a, 2) + pow(b, 2))
print(f"辺C = {c}") # 5.0
6. if文 🤔
️ ある条件がTrueの場合にのみ、特定のコードを実行します。
それ以外の場合は、別のことを行います。
age = int(input("年齢を入力してください: "))
if age >= 100:
print("申し込みには年をとりすぎています")
elif age >= 18:
print("申し込みが完了しました!")
elif age < 0:
print("あなたはまだ生まれていません!")
else:
print("申し込みには18歳以上である必要があります")
response = input("食べ物はいかがですか? (Y/N): ")
if response == "Y":
print("どうぞ、食べ物をお取りください!")
else:
print("食べ物はありません!")
name = input("名前を入力してください: ")
if name == "":
print("名前を入力していません!")
else:
print(f"こんにちは {name}")
for_sale = True
if for_sale:
print("この商品は販売中です")
else:
print("この商品は販売中ではありません")
7. ⭐ 計算機プログラム 🧮
# + = 加算
# - = 減算
# * = 乗算
# / = 除算
operator = input("演算子を入力してください (+ - * /): ")
num1 = float(input("1番目の数値を入力してください: "))
num2 = float(input("2番目の数値を入力してください: "))
if operator == "+":
result = num1 + num2
print(round(result, 3))
elif operator == "-":
result = num1 - num2
print(round(result, 3))
elif operator == "*":
result = num1 * num2
print(round(result, 3))
elif operator == "/":
result = num1 / num2
print(round(result, 3))
else:
print(f"{operator} は有効な演算子ではありません")
8. ⭐ 体重変換プログラム 🏋️
weight = float(input("体重を入力してください: "))
unit = input("キログラムまたはポンドですか? (K or L): ")
if unit == "K":
weight = weight * 2.205
unit = "ポンド"
print(f"あなたの体重は: {round(weight, 1)} {unit}です")
elif unit == "L":
weight = weight / 2.205
unit = "キログラム"
print(f"あなたの体重は: {round(weight, 1)} {unit}です")
else:
print(f"{unit} は有効な単位ではありません")
9. ⭐ 温度変換プログラム 🌡️
# (°C x 9/5) + 32 = °F
# (°F - 32) x 5/9 = °C
# °(Option + Shift + 8)
unit = input("この温度は摂氏または華氏ですか? (C/F): ")
temp = float(input("温度を入力してください: "))
if unit == "C":
temp = round((9 * temp) / 5 + 32, 1)
print(f"華氏での温度は: {temp}°Fです")
elif unit == "F":
temp = round((temp - 32) * 5 / 9, 1)
print(f"摂氏での温度は: {temp}°Cです")
else:
print(f"{unit} は有効な測定単位ではありません")
10. 論理演算子 🌦️
複数の条件を評価します(または、かつ、ではない)
または = 少なくとも1つの条件がTrueでなければならない
かつ = 両方の条件がTrueでなければならない
ではない = 条件を反転します(Falseではない、Trueではない)
temp = 25
is_raining = True
if temp > 35 or temp < 0 or is_raining:
print("屋外イベントは中止されます")
else:
print("屋外イベントは予定通り開催されます")
temp = 25
is_sunny = True
if temp >= 28 and is_sunny:
print("外は暑いです 🥵")
print("晴れています 🌞")
elif temp <= 0 and is_sunny:
print("外は寒いです 🥶")
print("晴れています 🌞")
elif 28 > temp > 0 and is_sunny:
print("外は暖かいです 🙂")
print("晴れています 🌞")
elif temp >= 28 and not is_sunny:
print("外は暑いです 🥵")
print("曇っています ☁️")
elif temp <= 0 and not is_sunny:
print("外は寒いです 🥶")
print("曇っています ☁️")
elif 28 > temp > 0 and not is_sunny:
print("外は暖かいです 🙂")
print("曇っています ☁️")
11. 条件式 ❓
if-else文のワンライナーショートカット(三項演算子)
条件に基づいて2つの値のいずれかを出力または代入します
X if condition else Y
num = 5
a = 6
b = 7
age = 13
temperature = 20
user_role = "guest"
print("正" if num > 0 else "負")
result = "偶数" if num % 2 == 0 else "奇数"
max_num = a if a > b else b
min_num = a if a < b else b
status = "成人" if age >= 18 else "子供"
weather = "暑い" if temperature > 20 else "寒い"
access_level = "フルアクセス" if user_role == "admin" else "制限付きアクセス"
print(access_level)
12. 文字列メソッド 〰️
name = input("フルネームを入力してください: ")
result = len(name)
# yuunijiy -> 8
result = name.find("n")
# yuunijiy -> 3
result = name.rfind("n")
# yuunijiy -> 4
name = name.capitalize()
# yuunijiy -> Yuunijiy
name = name.upper()
# yuunijiy -> YUUNIJIY
name = name.lower()
# YUUNIJIY -> yuunijiy
result = name.isdigit()
# yuunijiy,yuu123 -> False; 123 -> True
result = name.isalpha()
# yuunijiy -> True; yuu niji,yuu123,123 -> False
phone_number = input("電話番号を入力してください: ")
result = phone_number.count("-")
# 1-234-567-8901 -> 3
phone_number = phone_number.replace("-", " ")
# 1-234-567-8901 -> 1 234 567 8901
利用可能なすべての文字列メソッドの完全なリストが必要な場合は、help関数を使用します:print(help(str))
演習:
# ユーザー入力の検証演習
# 1. ユーザー名は12文字以内
# 2. ユーザー名にスペースを含めてはいけない
# 3. ユーザー名に数字を含めてはいけない
username = input("ユーザー名を入力してください: ")
if len(username) > 12:
print("ユーザー名は12文字以内でなければなりません")
elif not username.find(" ") == -1:
print("ユーザー名にスペースを含めることはできません")
elif not username.isalpha():
print("ユーザー名に数字を含めることはできません")
else:
print(f"ようこそ {username}")
13. 文字列インデックス ✂️
シーケンスの要素にアクセスするために[](インデックス演算子)を使用します
[開始 : 終了 : ステップ]
credit_number = "1234-5678-9012-3456"
print(credit_number[0]) # 1
print(credit_number[:4]) # 1234
print(credit_number[5:9]) # 5678
print(credit_number[5:]) # 5678-9012-3456
print(credit_number[-1]) # 6
print(credit_number[-2]) # 5
print(credit_number[::2]) # 13-6891-46
print(credit_number[::3]) # 146-136
credit_number = "1234-5678-9012-3456"
last_digits = credit_number[-4:] # 3456
print(f"XXXX-XXXX-XXXX-{last_digits}")
credit_number = "1234-5678-9012-3456"
credit_number = credit_number[::-1]
print(credit_number)
# 6543-2109-8765-4321
14. フォーマット指定子 💬
{value:flags} は、挿入されたフラグに基づいて値をフォーマットします
.(数値)f
= 指定された小数点以下の桁数に丸める(固定小数点):(数値)
= 指定された数のスペースを割り当てる:03
= 指定された数のスペースを割り当て、ゼロで埋める:<
= 左揃え:>
= 右揃え:^
= 中央揃え:+
= 正の値にプラス記号を使用する:=
= 符号を最左の位置に配置する:
= 正の数の前にスペースを挿入する:,
= カンマ区切り
price1 = 3.14159
price2 = -987.65
price3 = 12.34
print(f"Price 1 is ${price1:.3f}") # 3.142
print(f"Price 2 is ${price2:.3f}") # -987.650
print(f"Price 3 is ${price3:.3f}") # 12.340
print(f"Price 1 is ${price1:10}")
print(f"Price 2 is ${price2:10}")
print(f"Price 3 is ${price3:10}")
# Price 1 is $ 3.14159
# Price 2 is $ -987.65
# Price 3 is $ 12.34
print(f"Price 1 is ${price1:010}")
print(f"Price 2 is ${price2:010}")
print(f"Price 3 is ${price3:010}")
# Price 1 is $0003.14159
# Price 2 is $-000987.65
# Price 3 is $0000012.34
print(f"Price 1 is ${price1:<10}")
print(f"Price 2 is ${price2:<10}")
print(f"Price 3 is ${price3:<10}")
# Price 1 is $3.14159 |
# Price 2 is $-987.65 |
# Price 3 is $12.34 |
print(f"Price 1 is ${price1:+}") # +3.14159
print(f"Price 2 is ${price2:+}") # -987.65
print(f"Price 3 is ${price3:+}") # +12.34
print(f"Price 1 is ${price1:10}")
print(f"Price 2 is ${price2:10}")
print(f"Price 3 is ${price3:10}")
# Price 1 is $ 3.14159
# Price 2 is $-987.65
# Price 3 is $ 12.34
price1 = 3000.14159
price2 = -9870.65
price3 = 1200.34
print(f"Price 1 is ${price1:,}")
print(f"Price 2 is ${price2:,}")
print(f"Price 3 is ${price3:,}")
# Price 1 is $3,000.14159
# Price 2 is $-9,870.65
# Price 3 is $1,200.34
print(f"Price 1 is ${price1:+,.2f}")
print(f"Price 2 is ${price2:+,.2f}")
print(f"Price 3 is ${price3:+,.2f}")
# Price 1 is $+3,000.14
# Price 2 is $-9,870.65
# Price 3 is $+1,200.34
15. while ループ ♾️
ある条件が真である間、コードを実行します
age = int(input("年齢を入力してください: "))
while age < 0:
print("年齢は負の値にできません")
age = int(input("年齢を入力してください: "))
print(f"あなたは {age} 歳です")
food = input("好きな食べ物を入力してください (終了するには q を入力): ")
while not food == "q":
print(f"あなたは {food} が好きです")
food = input("別の好きな食べ物を入力してください (終了するには q を入力): ")
print("さようなら")
num = int(input("1 から 10 までの数字を入力してください: "))
while num < 1 or num > 10:
print(f"{num} は無効です")
num = int(input("1 から 10 までの数字を入力してください: "))
print(f"あなたの数字は {num} です")
16. ⭐ 複利計算機 💵
# A = P (1 + r/n)ᵗ
# A = 最終金額
# P = 初期元本
# r = 利率
# t = 経過期間
principle = 0
rate = 0
time = 0
while principle <= 0:
principle = float(input("元本を入力してください: "))
if principle <= 0:
print("元本はゼロ以下にできません")
while rate <= 0:
rate = float(input("利率を入力してください: "))
if rate <= 0:
print("利率はゼロ以下にできません")
while time <= 0:
time = int(input("年数を入力してください: "))
if time <= 0:
print("年数はゼロ以下にできません")
print(principle)
print(rate)
print(time)
total = principle * pow((1 + rate / 100), time)
print(f"{time} 年後の残高: ${total:.2f}")
principle = 0
rate = 0
time = 0
while True:
principle = float(input("元本を入力してください: "))
if principle < 0:
print("元本は負の値にできません")
else:
break
while True:
rate = float(input("利率を入力してください: "))
if rate < 0:
print("利率は負の値にできません")
else:
break
while True:
time = int(input("年数を入力してください: "))
if time < 0:
print("年数は負の値にできません")
else:
break
total = principle * pow((1 + rate / 100), time)
print(f"{time} 年後の残高: ${total:.2f}")
17. forループ 🔁
固定回数だけコードブロックを実行します。
範囲、文字列、シーケンスなどを反復処理できます。
for x in range(1, 6):
print(x)
# 1
# 2
# 3
# 4
# 5
for x in reversed(range(1, 6)):
print(x)
print("HAPPY NEW YEAR!")
# 1
# 2
# 3
# 4
# 5
# HAPPY NEW YEAR!
for x in range(1, 6, 3):
print(x)
# 1
# 4
credit_card = "12-34"
for x in credit_card:
print(x)
# 1
# 2
# -
# 3
# 4
for x in range(1, 6):
if x == 3:
continue
else:
print(x)
# 1
# 2
# 4
# 5
for x in range(1, 6):
if x == 3:
break
else:
print(x)
# 1
# 2
18. ⭐ カウントダウンタイマープログラム ⌛
import time
my_time = int(input("秒数を入力してください: ")) # 3
for x in range(0, my_time):
print(x)
time.sleep(1)
# 0
# 1
# 2
print("TIME'S UP!")
import time
my_time = int(input("秒数を入力してください: ")) # 3
for x in range(my_time, 0, -1):
print(x)
time.sleep(1)
# 3
# 2
# 1
print("TIME'S UP!")
import time
my_time = int(input("秒数を入力してください: ")) # 3605
for x in range(my_time, 0, -1):
seconds = x % 60
minutes = int(x / 60) % 60
hours = int(x / 3600)
print(f"{hours:02}:{minutes:02}:{seconds:02}")
time.sleep(1)
# 01:00:05
# 01:00:04
# 01:00:03
# 01:00:02
# 01:00:01
# 01:00:00
# 00:59:59
# 00:59:58
print("TIME'S UP!")
19. ネストされたループ ➿
ループ内のループ(外側のループ、内側のループ)
外側のループ:
内側のループ:
for x in range(1, 10):
print(x, end="")
# 123456789
for x in range(3):
for y in range(1, 10):
print(y, end="")
# 123456789123456789123456789
for x in range(3):
for y in range(1, 10):
print(y, end="")
print()
# 123456789
# 123456789
# 123456789
rows = int(input("行数を入力してください: ")) # 3
columns = int(input("列数を入力してください: ")) # 5
symbol = input("使用する記号を入力してください: ") # *
for x in range(rows):
for y in range(columns):
print(symbol, end="")
print()
# *****
# *****
# *****
以下是将内容翻译为日文版本并保持Markdown格式的版本:
20. リスト、セット、タプル 🍎
- コレクション = 複数の値を格納するための単一の「変数」
- リスト =
[]
順序付けされ、変更可能。重複可 - セット =
{}
順序付けされず、不変だが、追加/削除可。重複不可 - タプル =
()
順序付けされ、変更不可。重複可。高速
fruits = ["apple", "orange", "banana", "coconut"]
# print(help(fruits))
print(dir(fruits))
# ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
print("apple" in fruits) # True
print(fruits[0]) # apple
print(fruits[0:3])
# ["apple", "orange", "banana"]
print(fruits[::2])
# ["apple", "banana"]
print(fruits[::-1])
# ["coconut", "banana", "orange", "apple"]
fruits = ["apple", "orange", "banana", "coconut"]
fruits.append("pineapple")
# fruits.remove("pineapple")
print(fruits)
# ["apple", "orange", "banana", "coconut", "pineapple"]
fruits = ["apple", "orange", "banana", "coconut"]
fruits.insert(0, "pineapple")
print(fruits)
# ["pineapple", "apple", "orange", "banana", "coconut"]
fruits = ["apple", "orange", "banana", "coconut"]
fruits.sort()
print(fruits)
# ["apple", "banana", "coconut", "orange"]
fruits = ["apple", "orange", "banana", "coconut"]
fruits.reverse()
print(fruits)
# ["coconut", "banana", "orange", "apple"]
fruits = ["apple", "orange", "banana", "coconut"]
fruits.sort()
fruits.reverse()
print(fruits)
# ["orange", "coconut", "banana", "apple"]
fruits = ["apple", "orange", "banana", "coconut"]
fruits.clear()
print(fruits)
# []
fruits = ["apple", "orange", "banana", "coconut"]
print(fruits.index("apple")) # 0
fruits = {"apple", "orange", "banana", "coconut", "coconut"}
print(len(fruits)) # 4
print(dir(fruits))
# ['__and__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__iand__', '__init__', '__init_subclass__', '__iter__', '__ixor__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__rand__', '__reduce__', '__reduce_ex__', '__repr__', '__ror__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__xor__', 'add', 'clear', 'copy', 'difference', 'difference_update', 'discard', 'intersection', 'intersection_update', 'isdisjoint', 'issubset', 'issuperset', 'pop', 'remove', 'symmetric_difference', 'symmetric_difference_update', 'union', 'update']
print(fruits[0])
# TypeError: 'set' object is not subscriptable
print(fruits)
# {"orange", "apple", "banana", "coconut"}
fruits.pop()
# {"orange", "apple", "banana"}
# OR {"apple", "banana", "coconut"}
# OR {"orange", "banana", "coconut"}
# OR ...
fruits.clear() # set()
fruits = ("apple", "orange", "banana", "coconut", "coconut")
print(dir(fruits))
# ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']
print(fruits)
# ("apple", "orange", "banana", "coconut", "coconut")
21. ⭐ ショッピングカートプログラム 🛒
foods = []
prices = []
total = 0
while True:
food = input("購入する食品を入力してください (qで終了): ")
if food.lower() == "q":
break
else:
price = float(input(f"{food}の価格を入力してください: $"))
foods.append(food)
prices.append(price)
print("----- あなたのカート -----")
for food in foods:
print(food, end=" ")
for price in prices:
total += price
print()
print(f"合計金額は: ${total}")
22. 2Dコレクション ⬜
fruits = ["りんご", "オレンジ", "バナナ", "ココナッツ"]
vegetables = ["セロリ", "にんじん", "じゃがいも"]
meats = ["鶏肉", "魚", "七面鳥"]
groceries = [fruits, vegetables, meats]
print(groceries[0])
# ["りんご", "オレンジ", "バナナ", "ココナッツ"]
print(groceries[0][3])
# ココナッツ
print(groceries[2][3])
# IndexError: リストのインデックスが範囲外です
groceries = [["りんご", "オレンジ", "バナナ", "ココナッツ"],
["セロリ", "にんじん", "じゃがいも"],
["鶏肉", "魚", "七面鳥"]]
for collection in groceries:
for food in collection:
print(food, end=" ")
print()
# りんご オレンジ バナナ ココナッツ
# セロリ にんじん じゃがいも
# 鶏肉 魚 七面鳥
num_pad = ((1, 2, 3),
(4, 5, 6),
(7, 8, 9),
("*", 0, "#"))
for row in num_pad:
for num in row:
print(num, end=" ")
print()
# 1 2 3
# 4 5 6
# 7 8 9
# * 0 #
23. ⭐ クイズゲーム 💯
questions = ("周期表にはいくつの元素がありますか?: ",
"最も大きな卵を産む動物はどれですか?: ",
"地球の大気中で最も豊富な気体は何ですか?: ",
"人間の体にはいくつの骨がありますか?: ",
"太陽系で最も暑い惑星はどれですか?: ")
options = (("A. 116", "B. 117", "C. 118", "D. 119"),
("A. クジラ", "B. ワニ", "C. 象", "D. ダチョウ"),
("A. 窒素", "B. 酸素", "C. 二酸化炭素", "D. 水素"),
("A. 206", "B. 207", "C. 208", "D. 209"),
("A. 水星", "B. 金星", "C. 地球", "D. 火星"))
answers = ("C", "D", "A", "A", "B")
guesses = []
score = 0
question_num = 0
for question in questions:
print("-----------------------")
print(question)
for option in options[question_num]:
print(option)
guess = input("(A, B, C, D)を入力してください: ").upper()
guesses.append(guess)
if guess == answers[question_num]:
score += 1
print("正解!")
else:
print("不正解!")
print(f"正解は {answers[question_num]} です")
question_num += 1
print("-----------------------")
print(" 結果 ")
print("-----------------------")
print("正解: ", end="")
for answer in answers:
print(answer, end=" ")
print()
print("あなたの回答: ", end="")
for guess in guesses:
print(guess, end=" ")
print()
score = int(score / len(questions) * 100)
print(f"あなたのスコアは: {score}%")
24. 辞書 📙
{key: value} ペアのコレクションで、順序付けられており、変更可能です。重複はありません。
capitals = {"USA": "Washington D.C.",
"India": "New Delhi",
"China": "Beijing",
"Russia": "Moscow"}
print(dir(capitals))
# print(help(capitals))
# ['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
print(capitals.get("USA")) # Washington D.C.
print(capitals.get("Japan")) # None
capitals.update({"Germany": "Berlin"})
capitals.update({"USA": "Detroit"})
# {"USA": "Detroit", "India": "New Delhi", "China": "Beijing", "Russia": "Moscow", "Germany": "Berlin"}
capitals.pop("China")
# {"USA": "Detroit", "India": "New Delhi", "Russia": "Moscow", "Germany": "Berlin"}
capitals.popitem()
# {"USA": "Detroit", "India": "New Delhi", "Russia": "Moscow"}
# capitals.clear()
# {}
keys = capitals.keys()
# dict_keys(['USA', 'India', 'Russia'])
for key in capitals.keys():
print(key)
# USA
# India
# Russia
values = capitals.values()
# dict_values(['Detroit', 'New Delhi', 'Moscow'])
for value in capitals.values():
print(value)
# Detroit
# New Delhi
# Moscow
items = capitals.items()
print(items)
# dict_items([('USA', 'Detroit'), ('India', 'New Delhi'), ('Russia', 'Moscow')])
for key, value in capitals.items():
print(f"{key}: {value}")
# USA: Detroit
# India: New Delhi
# Russia: Moscow
25. ⭐ 売店プログラム 🍿
menu = {"pizza": 3.00, # ピザ
"nachos": 4.50, # ナチョス
"popcorn": 6.00, # ポップコーン
"fries": 2.50, # フライドポテト
"chips": 1.00, # ポテトチップス
"pretzel": 3.50, # プレッツェル
"soda": 3.00, # ソーダ
"lemonade": 4.25} # レモネード
cart = []
total = 0
print("----- メニュー -----")
for key, value in menu.items():
print(f"{key:10}: ${value:.2f}")
print("--------------------")
while True:
food = input("商品を選んでください(終了するには q を入力):").lower()
if food == "q":
break
elif menu.get(food) is not None:
cart.append(food)
print("-- ご注文内容 --")
for food in cart:
total += menu.get(food)
print(food, end=" ")
print()
print(f"合計金額: ${total:.2f}")
26. ランダムな数 🎲
import random
# print(help random) # random モジュールのヘルプを表示
low = 1
high = 100
options = ("rock", "paper", "scissors") # グー、パー、チョキ
cards = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"] # トランプのカード
# number = random.randint(1, 6) # 1〜6 の整数をランダムに生成
# number = random.randint(low, high) # low〜high の整数をランダムに生成
# number = random.random() # 0〜1 のランダムな小数を生成
# option = random.choice(options) # ランダムに1つ選択
# random.shuffle(cards) # カードをシャッフル
27. ⭐ 数当てゲーム 🔢
import random
lowest_num = 1
highest_num = 100
answer = random.randint(lowest_num, highest_num)
guesses = 0
is_running = True
print("Python 数当てゲーム")
print(f"{lowest_num}〜{highest_num} の間の数字を選んでください")
while is_running:
guess = input("数字を入力してください:")
if guess.isdigit():
guess = int(guess)
guesses += 1
if guess < lowest_num or guess > highest_num:
print("その数字は範囲外です")
print(f"{lowest_num}〜{highest_num} の間で選んでください")
elif guess < answer:
print("小さすぎます!もう一度!")
elif guess > answer:
print("大きすぎます!もう一度!")
else:
print(f"正解!答えは {answer} でした")
print(f"試行回数: {guesses}")
is_running = False
else:
print("無効な入力です")
print(f"{lowest_num}〜{highest_num} の間で数字を選んでください")
28. ⭐ じゃんけんゲーム 🗿
import random
options = ("グー", "パー", "チョキ")
playing = True
while playing:
player = None
computer = random.choice(options)
while player not in):
player = input("選択してください(グー、パー、チョキ):")
print(f"プレイヤー: {player}")
print(f"コンピューター: {computer}")
if player == computer:
print("引き分けです!")
elif player == "グー" and computer == "チョキ":
print("あなたが勝ちました!")
elif player == "パー" and computer == "グー":
print("あなたが勝ちました!")
elif player == "チョキ" and computer == "パー":
print("あなたが勝ちました!")
else:
print("あなたが負けました!")
play_again = input("もう一度遊びますか?(y/n): ").lower()
if not play_again == "y":
playing = False
print("プレイしてくれてありがとう!")
29. ⭐ サイコロプログラム ⚂
import random
print("\u25CF \u250C \u2500 \u2510 \u2502 \u2514 \u2518")
# ● ┌ ─ ┐ │ └ ┘
"┌─────────┐"
"│ │"
"│ │"
"│ │"
"└─────────┘"
dice_art = {
1: ("┌─────────┐",
"│ │",
"│ ● │",
"│ │",
"└─────────┘"),
2: ("┌─────────┐",
"│ ● │",
"│ │",
"│ ● │",
"└─────────┘"),
3: ("┌─────────┐",
"│ ● │",
"│ ● │",
"│ ● │",
"└─────────┘"),
4: ("┌─────────┐",
"│ ● ● │",
"│ │",
"│ ● ● │",
"└─────────┘"),
5: ("┌─────────┐",
"│ ● ● │",
"│ ● │",
"│ ● ● │",
"└─────────┘"),
6: ("┌─────────┐",
"│ ● ● │",
"│ ● ● │",
"│ ● ● │",
"└─────────┘"),
}
dice = []
total = 0
num_of_dice = int(input("サイコロの数は?: "))
for die in range(num_of_dice):
dice.append(random.randint(1, 6))
print(dice)
for line in range(5): # 外部ループ、行ごとに印刷
for die in dice: # 内部ループ、各サイコロの目を処理
print(dice_art.get(die)[line], end="") # 現在のサイコロの行を印刷
print() # 行の印刷後に改行
for die in dice:
total += die
print(f"合計: {total}")
30. 関数 📞
# 関数 = 再利用可能なコードのブロック
# 関数名の後に()をつけて呼び出す
def happy_birthday(name, age):
print(f"{name}さん、お誕生日おめでとう!")
print(f"あなたは{age}歳です!")
print("お誕生日おめでとう!")
print()
happy_birthday("ブロ", 20)
happy_birthday("スティーブ", 30)
happy_birthday("ジョー", 40)
--------
def display_invoice(username, amount, due_date):
print(f"こんにちは {username}さん")
print(f"請求額 ${amount:.2f} の支払い期限: {due_date}")
display_invoice("YuuNiji", 100.01, "01/02")
--------
# return = 関数を終了し、結果を呼び出し元に返すステートメント
def add(x, y):
z = x + y
return z
def subtract(x, y):
z = x - y
return z
def multiply(x, y):
z = x * y
return z
def divide(x, y):
z = x / y
return z
print(add(1, 2)) # 3
print(subtract(1, 2)) # -1
print(multiply(1, 2)) # 2
print(divide(1, 2)) # 0.5
--------
def create_name(first, last):
first = first.capitalize()
last = last.capitalize()
return first + " " + last
full_name = create_name("yuuniji", "code")
print(full_name) # Yuuniji Code
31. デフォルト引数 👍
# デフォルト引数 = 特定の引数のデフォルト値
# 引数が省略された場合に使用される
# 関数をより柔軟にし、引数の数を減らす
# 1. 位置引数, 2. デフォルト, 3. キーワード, 4. 任意
def net_price(list_price, discount=1, tax=0.05):
return list_price * (1 - discount) * (1 + tax)
print(net_price(500)) # 525.0
print(net_price(500, 0.1)) # 472.5
print(net_price(500, 0.1, 0)) # 450
--------
import time
def count(start, end):
for x in range(start, end+1):
print(x)
time.sleep(1)
print("完了!")
count(0, 10)
# 0
# 1
# 2
# 3
# 4
# 5
# 6
# 7
# 8
# 9
# 10
# 完了!
--------
import time
def count(end, start=0):
for x in range(start, end+1):
print(x)
time.sleep(1)
print("完了!")
count(10)
# 0
# 1
# 2
# 3
# 4
# 5
# 6
# 7
# 8
# 9
# 10
# 完了!
--------
import time
def count(end, start=0):
for x in range(start, end+1):
print(x)
time.sleep(1)
print("完了!")
count(30, 15)
# 15
# 16
# 17
# 18
# 19
# 20
# 21
# 22
# 23
# 24
# 25
# 26
# 27
# 28
# 29
# 30
# 完了!
32. キーワード引数 🗝️
# キーワード引数 = 識別子が先行する引数
# 可読性を向上させる
# 引数の順序は関係ない
# 1. 位置引数 2. デフォルト 3. キーワード 4. 任意
def hello(greeting, title, first, last):
print(f"{greeting} {title}{first} {last}")
hello("こんにちは", "さん", "スポンジボブ", "スクエアパンツ")
# こんにちは さんスポンジボブ スクエアパンツ
hello("こんにちは", "スポンジボブ", "スクエアパンツ", "さん")
# こんにちは スポンジボブスクエアパンツ さん
hello("こんにちは", title="さん", first="スポンジボブ", last="スクエアパンツ")
# こんにちは さんスポンジボブ スクエアパンツ
hello("こんにちは", title="さん", last="スクエアパンツ", first="スポンジボブ")
# こんにちは さんスポンジボブ スクエアパンツ
hello(title="さん", last="スクエアパンツ", first="スポンジボブ", "こんにちは")
# SyntaxError: キーワード引数の後に位置引数が続く
hello("こんにちは", "さん", "ジョン", "ジェームズ")
# こんにちは さんジョン ジェームズ
hello("こんにちは", title="さん", last="ジョン", first="ジェームズ")
# こんにちは さんジェームズ ジョン
--------
for x in range(1, 11):
print(x, end=" ")
# 1 2 3 4 5 6 7 8 9 10
--------
print("1", "2", "3", "4", "5", sep="-")
# 1-2-3-4-5
--------
def get_phone(country, area, first, last):
return f"{country}-{area}-{first}-{last}"
phone_num = get_phone(country=1, area=123, first=456, last=7890)
print(phone_num)
# 1-123-456-7890
33. *args & **kwargs 📦
# *args = 複数の非キーワード引数を渡すことができる
# **kwargs = 複数のキーワード引数を渡すことができる
# * アンパック演算子
# 1. 位置引数 2. デフォルト 3. キーワード 4. 任意
def add(a, b):
return a + b
print(add(1, 2)) # 3
print(add(1, 2, 3))
# TypeError: add() は2つの位置引数を取りますが、3つが与えられました
--------
def add(*args):
print(type(args)) # <class 'tuple'>
total = 0
for arg in args:
total += arg
return total
print(add(1, 2, 3, 4, 5)) # 15
--------
def display_name(*args):
for arg in args:
print(arg, end=" ")
display_name("博士", "スポンジボブ", "ハロルド", "スクエアパンツ")
# 博士 スポンジボブ ハロルド スクエアパンツ
--------
def print_address(**kwargs):
print(type(kwargs)) # <class 'dict'>
for value in kwargs.values():
print(value)
print_address(street="123 フェイク通り",
city="デトロイト",
state="MI",
zip="54321")
# 123 フェイク通り
# デトロイト
# MI
# 54321
--------
def print_address(**kwargs):
print(type(kwargs)) # <class 'dict'>
for key in kwargs.keys():
print(key)
print_address(street="123 フェイク通り",
city="デトロイト",
state="MI",
zip="54321")
# street
# city
# state
# zip
--------
def print_address(**kwargs):
print(type(kwargs)) # <class 'dict'>
for key, value in kwargs.items():
print(f"{key}: {value}")
print_address(street="123 フェイク通り",
city="デトロイト",
state="MI",
zip="54321")
# street: 123 フェイク通り
# city: デトロイト
# state: MI
# zip: 54321
--------
def shipping_label(*args, **kwargs):
for arg in args:
print(arg, end=" ")
print()
for value in kwargs.values():
print(value, end=" ")
shipping_label("博士", "スポンジボブ", "スクエアパンツ", "III",
street="123 フェイク通り",
apt="100",
city="デトロイト",
state="MI",
zip="54321")
# 博士 スポンジボブ スクエアパンツ III
# 123 フェイク通り 100 デトロイト MI 54321
--------
def shipping_label(*args, **kwargs):
for arg in args:
print(arg, end=" ")
print()
print(f"{kwargs.get('street')} {kwargs.get('apt')}")
print(f"{kwargs.get('city')} {kwargs.get('state')}, {kwargs.get('zip')}")
shipping_label("博士", "スポンジボブ", "スクエアパンツ",
street="123 フェイク通り",
apt="#100",
city="デトロイト",
state="MI",
zip="54321")
# 博士 スポンジボブ スクエアパンツ
# 123 フェイク通り #100
# デトロイト MI 54321
--------
def shipping_label(*args, **kwargs):
for arg in args:
print(arg, end=" ")
print()
print(f"{kwargs.get('street')} {kwargs.get('apt')}")
print(f"{kwargs.get('city')} {kwargs.get('state')}, {kwargs.get('zip')}")
shipping_label("博士", "スポンジボブ", "スクエアパンツ",
street="123 フェイク通り",
city="デトロイト",
state="MI",
zip="54321")
# 博士 スポンジボブ スクエアパンツ
# 123 フェイク通り None
# デトロイト MI 54321
--------
def shipping_label(*args, **kwargs):
for arg in args:
print(arg, end=" ")
print()
if "apt" in kwargs:
print(f"{kwargs.get('street')} {kwargs.get('apt')}")
elif "pobox" in kwargs:
print(f"{kwargs.get('street')}")
print(f"{kwargs.get('pobox')}")
else:
print(f"{kwargs.get('street')}")
print(f"{kwargs.get('city')} {kwargs.get('state')}, {kwargs.get('zip')}")
shipping_label("博士", "スポンジボブ", "スクエアパンツ",
street="123 フェイク通り",
pobox="PO box #1001",
city="デトロイト",
state="MI",
zip="54321")
# 博士 スポンジボブ スクエアパンツ
# 123 フェイク通り
# PO box #1001
# デトロイト MI 54321
34. イテラブル 🔂
# イテラブル = 要素を1つずつ返すことができるオブジェクト/コレクション
# ループで反復処理が可能
numbers = [1, 2, 3, 4, 5]
for number in numbers:
print(number)
# 1
# 2
# 3
# 4
# 5
numbers = [1, 2, 3, 4, 5]
for number in reversed(numbers):
print(number)
# 5
# 4
# 3
# 2
# 1
numbers = [1, 2, 3, 4, 5]
for number in reversed(numbers):
print(number, end=" ")
# 5 4 3 2 1
numbers = [1, 2, 3, 4, 5]
for number in reversed(numbers):
print(number, end="-")
# 5-4-3-2-1-
numbers = [1, 2, 3, 4, 5]
for number in reversed(numbers):
print(number, end=" - ")
# 5 - 4 - 3 - 2 - 1 -
numbers = (1, 2, 3, 4, 5)
for number in numbers:
print(number)
# 1
# 2
# 3
# 4
# 5
fruits = {"リンゴ", "オレンジ", "バナナ", "ココナッツ"}
for fruit in fruits:
print(fruit)
# リンゴ
# オレンジ
# バナナ
# ココナッツ
name = "Yuu Niji"
for character in name:
print(character)
# Y
# u
# u
#
# N
# i
# j
# i
name = "Yuu Niji"
for character in name:
print(character, end=" ")
# Y u u N i j i
my_dictionary = {"A": 1, "B": 2, "C": 3}
for key in my_dictionary:
print(key)
# A
# B
# C
my_dictionary = {"A": 1, "B": 2, "C": 3}
for value in my_dictionary.values():
print(value)
# 1
# 2
# 3
my_dictionary = {"A": 1, "B": 2, "C": 3}
for key, value in my_dictionary.items():
print(key, value)
# A 1
# B 2
# C 3
my_dictionary = {"A": 1, "B": 2, "C": 3}
for key, value in my_dictionary.items():
print(f"{key} = {value}")
# A = 1
# B = 2
# C = 3
35. メンバーシップ演算子 🔎
# メンバーシップ演算子 = 値や変数がシーケンス(文字列、リスト、タプル、セット、または辞書)に含まれているかをテストするために使用されます
# 1. in
# 2. not in
word = "APPLE"
letter = input("秘密の単語に含まれる文字を推測してください: ")
if letter in word:
print(f"{letter} があります")
else:
print(f"{letter} は見つかりませんでした")
# 秘密の単語に含まれる文字を推測してください: A
# A があります
# 秘密の単語に含まれる文字を推測してください: Z
# Z は見つかりませんでした
word = "APPLE"
letter = input("秘密の単語に含まれる文字を推測してください: ")
if letter not in word:
print(f"{letter} は見つかりませんでした")
else:
print(f"{letter} があります")
# 秘密の単語に含まれる文字を推測してください: E
# E があります
# 秘密の単語に含まれる文字を推測してください: Q
# Q は見つかりませんでした
students = {"Spongbob", "Patrick", "Sandy"}
student = input("生徒の名前を入力してください: ")
if student in students:
print(f"{student} は生徒です")
else:
print(f"{student} は見つかりませんでした")
# 生徒の名前を入力してください: Spongbob
# Spongbob は生徒です
# 生徒の名前を入力してください: Yuuniji
# Yuuniji は見つかりませんでした
students = {"Spongbob", "Patrick", "Sandy"}
student = input("生徒の名前を入力してください: ")
if student not in students:
print(f"{student} は見つかりませんでした")
else:
print(f"{student} は生徒です")
# 生徒の名前を入力してください: Sandy
# Sandy は生徒です
# 生徒の名前を入力してください: Github
# Github は見つかりませんでした
grades = {"Sandy": "A",
"Squidward": "B",
"Spongbob": "C",
"Patrickテンプレート: "D"}
student = input("生徒の名前を入力してください: ")
if student in grades:
print(f"{student} の成績は {grades[student]} です")
else:
print(f"{student} は見つかりませんでした")
# 生徒の名前を入力してください: Spongbob
# Spongbob の成績は C です
# 生徒の名前を入力してください: Sandy
# Sandy の成績は A です
# 生徒の名前を入力してください: Squidward
# Squidward の成績は B です
# 生徒の名前を入力してください: Patrick
# Patrick の成績は D です
# 生徒の名前を入力してください: Yuuniji
# Yuuniji は見つかりませんでした
email = "yuuniji81@gmail.com"
if "@" in email and "." in email:
print("有効なメールアドレス")
else:
print("無効なメールアドレス")
# 有効なメールアドレス
email = "yuuniji81gmail.com"
if "@" in email and "." in email:
print("有効なメールアドレス")
else:
print("無効なメールアドレス")
# 無効なメールアドレス
email = "yuuniji81@gmailcom"
if "@" in email and "." in email:
print("有効なメールアドレス")
else:
print("無効なメールアドレス")
# 無効なメールアドレス
36. リスト内包表記 📃
# リスト内包表記 = Pythonでリストを作成する簡潔な方法
# 伝統的なループよりもコンパクトで読みやすい
# [式 for 値 in イテラブル if 条件]
doubles = []
for x in range(1, 11):
doubles.append(x * 2)
print(doubles)
# [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
doubles = [x * 2 for x in range(1, 11)]
print(doubles)
# [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
triples = [y * 3 for y in range(1, 11)]
print(triples)
# [3, 6, 9, 12, 15, 18, 21, 24, 27, 30]
squares = [z * z for z in range(1, 11)]
print(squares)
# [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
fruits = ["apple", "orange", "banana", "coconut"]
fruits = [fruit.upper() for fruit in fruits]
print(fruits)
# ['APPLE', 'ORANGE', 'BANANA', 'COCONUT']
fruits = [fruit.upper() for fruit in ["apple", "orange", "banana", "coconut"]]
print(fruits)
# ['APPLE', 'ORANGE', 'BANANA', 'COCONUT']
fruits = ["apple", "orange", "banana", "coconut"]
fruit_chars = [fruit[0] for fruit in fruits]
print(fruit_chars)
# ['a', 'o', 'b', 'c']
numbers = [1, -2, 3, -4, 5, -6, 8, -7]
positive_nums = [num for num in numbers if num >= 0]
negative_nums = [num for num in numbers if num < 0]
even_nums = [num for num in numbers if num % 2 == 0]
odd_nums = [num for num in numbers if num % 2 == 1]
print(positive_nums)
# [1, 3, 5, 8]
print(negative_nums)
# [-2, -4, -6, -7]
print(even_nums)
# [-2, -4, -6, 8]
print(odd_nums)
# [1, 3, 5, -7]
grades = [85, 42, 79, 90, 56, 61, 30]
passing_grades = [grade for grade in grades if grade >= 60]
print(passing_grades)
# [85, 79, 90, 61]
37. マッチケース文 📆
# マッチケース文(スイッチ):多数の「elif」文を使用する代替手段
# 値が「case」に一致する場合にコードを実行
# 利点:よりクリーンで構文が読みやすい
def day_of_week(day):
if day == 1:
return "日曜日です"
elif day == 2:
return "月曜日です"
elif day == 3:
return "火曜日です"
elif day == 4:
return "水曜日です"
elif day == 5:
return "木曜日です"
elif day == 6:
return "金曜日です"
elif day == 7:
return "土曜日です"
else:
return "有効な曜日ではありません"
print(day_of_week(1))
# 日曜日です
def day_of_week(day):
match day:
case 1:
return "日曜日です"
case 2:
return "月曜日です"
case 3:
return "火曜日です"
case 4:
return "水曜日です"
case 5:
return "木曜日です"
case 6:
return "金曜日です"
case 7:
return "土曜日です"
case _: # _ = ワイルドカード
return "有効な曜日ではありません"
print(day_of_week(1))
# 日曜日です
def is_weekend(day):
match day:
case "Sunday":
return True
case "Monday":
return False
case "Tuesday":
return False
case "Wednesday":
return False
case "Thursday":
return False
case "Friday":
return False
case "Saturday":
return True
case _: # _ = ワイルドカード
return False
print(is_weekend("Sunday"))
# True
def is_weekend(day):
match day:
case "Saturday" | "Sunday": # | = または
return True
case "Monday" | "Tuesday" | "Wednesday" | "Thursday" | "Friday":
return False
case _: # _ = ワイルドカード
return False
print(is_weekend("Sunday"))
# True
38. モジュール 📨
# モジュール = プログラムに含めたいコードを含むファイル
# 'import'を使用してモジュールをインクルード(組み込みまたは独自のもの)
# 大規模なプログラムを再利用可能な別々のファイルに分割するのに便利
# print(help("modules"))
# print(help("math"))
import math
print(math.pi)
# 3.141592653589794
import math as m
print(math.pi)
# NameError: name 'math' is not defined
import math as m
print(m.pi)
# 3.141592653589794
from math import pi
print(pi)
# 3.141592653589794
from math import e
print(e)
# 2.718281828459045
from math import e
a, b, c, d = 1, 2, 3, 4
print(e ** a)
print(e ** b)
print(e ** c)
print(e ** d)
# 2.718281828459045
# 7.3890560989306495
# 20.085536923187664
# 54.5915003314423
from math import e
a, b, c, d, e = 1, 2, 3, 4, 5
print(e ** a)
print(e ** b)
print(e ** c)
print(e ** d)
print(e ** e)
# 2.718281828459045
# 7.3890560989306495
# 20.085536923187664
# 54.5915003314423
# 148.41315910257657
# example.py
pi = 3.14159
def square(x):
return x ** 2
def cube(x):
return x ** 3
def circumference(radius):
return 2 * pi * radius
def area(radius):
return pi * radius ** 2
# main.py
import example
result = example.pi
print(result)
# 3.14159
import example
result = example.square(3)
print(result)
# 9
import example
result = example.cube(3)
print(result)
# 27
import example
result = example.circumference(3)
print(result)
# 18.849539999999998
import example
result = example.area(3)
print(result)
# 28.27431
39. スコープ解決 🔬
# 変数のスコープ = 変数が参照可能でアクセス可能な範囲
# スコープ解決 = (LEGB) ローカル -> 囲まれたスコープ -> グローバル -> ビルトイン
def func1():
a = 1
print(a)
def func2():
b = 2
print(b)
func1() # 1
func2() # 2
def func1():
a = 1
print(b)
def func2():
b = 2
print(a)
func1()
func2()
# NameError: name 'b' is not defined
def happy_birthday(name, age):
print(f"お誕生日おめでとう、{name}さん")
print(f"あなたは{age}歳です")
def main():
name = "Yuuniji"
age = 21
happy_birthday(name, age)
main()
def func1():
x = 1
print(x)
def func2():
x = 2
print(x)
func1() # 1
func2() # 2
def func1():
x = 1
def func2():
x = 2
print(x)
func2()
func1()
# 2
def func1():
x = 1
def func2():
print(x)
func2()
func1()
# 1
def func1():
print(x)
def func2():
print(x)
x = 3
func1() # 3
func2() # 3
def func1():
x = 1
print(x)
def func2():
x = 2
print(x)
x = 3
func1() # 1
func2() # 2
from math import e
print(e)
# 2.718281828459045
from math import e
def func1():
print(e)
func1()
# 2.718281828459045
from math import e
def func1():
print(e)
e = 3
func1()
# 3
40. if name == ‘main’: 📥
# if __name__ == '__main__': (このスクリプトはインポートまたは単独で実行可能)
# このモジュールの関数やクラスは、メインのコードブロックが実行されずに再利用可能
# 良い習慣(コードがモジュール化され、
# 可読性が向上し、
# グローバル変数を残さず、
# 意図しない実行を防ぐ)
# 例: ライブラリ = 機能のためにライブラリをインポート
# ライブラリを直接実行すると、ヘルプページを表示
def main():
# ここにプログラムを書く
if __name__ == '__main__':
main()
# script1.py
# print(dir())
print(__name__)
# __main__
# script1.py
from script2 import *
# script2.pyがscript1.pyにインポートされると、モジュールとして扱われ、メインスクリプトではなくなる。そのため、Pythonは__name__をモジュール名である「script2」(.py拡張子を除いたファイル名)に設定する。
# script2.pyのprint(__name__)はインポート時に実行され、「script2」を出力する。
print(__name__)
# script2
# __main__
# script1.py
print(__name__)
# script2
# __main__
--------
# script2.py
from script1 import *
print(__name__)
# script1
# __main__
# script1.py
def favorite_food(food):
print(f"あなたの好きな食べ物は{food}です")
def main():
print("これはscript1です")
favorite_food("ピザ")
print("さようなら!")
if __name__ == '__main__':
main()
# これはscript1です
# あなたの好きな食べ物はピザです
# さようなら!
--------
# script2.py
from script1 import *
#
# script1.py
def favorite_food(food):
print(f"あなたの好きな食べ物は{food}です")
print("これはscript1です")
favorite_food("ピザ")
print("さようなら!")
--------
# script2.py
from script1 import *
# これはscript1です
# あなたの好きな食べ物はピザです
# さようなら!
# script1.py
def favorite_food(food):
print(f"あなたの好きな食べ物は{food}です")
def main():
print("これはscript1です")
favorite_food("ピザ")
print("さようなら!")
if __name__ == '__main__':
main()
--------
# script2.py
from script1 import *
def favorite_drink(drink):
print(f"あなたの好きな飲み物は{drink}です")
print("これはscript2です")
favorite_food("寿司")
favorite_drink("コーヒー")
print("さようなら!")
# これはscript2です
# あなたの好きな食べ物は寿司です
# あなたの好きな飲み物はコーヒーです
# さようなら!
# script1.py
def favorite_food(food):
print(f"あなたの好きな食べ物は{food}です")
def main():
print("これはscript1です")
favorite_food("ピザ")
print("さようなら!")
if __name__ == '__main__':
main()
--------
# script2.py
from script1 import *
def favorite_drink(drink):
print(f"あなたの好きな飲み物は{drink}です")
def main():
print("これはscript2です")
favorite_food("寿司")
favorite_drink("コーヒー")
print("さようなら!")
if __name__ == '__main__':
main()
# これはscript2です
# あなたの好きな食べ物は寿司です
# あなたの好きな飲み物はコーヒーです
# さようなら!
41. ⭐ 銀行プログラム 💰
# Python 銀行プログラム
# 1. 残高表示
# 2. 入金
# 3. 出金
def show_balance():
pass
def deposit():
pass
def withdraw():
pass
balance = 0
is_running = True
while is_running:
print("銀行プログラム")
print("1. 残高表示")
print("2. 入金")
print("3. 出金")
print("4. 終了")
choice = input("選択してください (1-4): ")
if choice == '1':
show_balance()
elif choice == '2':
deposit()
elif choice == '3':
withdraw()
elif choice == '4':
is_running = False
else:
print("無効な選択です")
print("ありがとうございます!良い一日を!")
# 銀行プログラム
# 1. 残高表示
# 2. 入金
# 3. 出金
# 4. 終了
# 選択してください (1-4): 1
# 銀行プログラム
# 1. 残高表示
# 2. 入金
# 3. 出金
# 4. 終了
# 選択してください (1-4): 4
# ありがとうございます!良い一日を!
def show_balance():
print(f"あなたの残高は ${balance:.2f} です")
def deposit():
amount = float(input("入金する金額を入力してください: "))
if amount < 0:
print("無効な金額です")
else:
return amount
def withdraw():
pass
balance = 0
is_running = True
while is_running:
print("銀行プログラム")
print("1. 残高表示")
print("2. 入金")
print("3. 出金")
print("4. 終了")
choice = input("選択してください (1-4): ")
if choice == '1':
show_balance()
elif choice == '2':
balance += deposit()
elif choice == '3':
withdraw()
elif choice == '4':
is_running = False
else:
print("無効な選択です")
print("ありがとうございます!良い一日を!")
# 銀行プログラム
# 1. 残高表示
# 2. 入金
# 3. 出金
# 4. 終了
# 選択してください (1-4): 1
# あなたの残高は $0.00 です
# 銀行プログラム
# 1. 残高表示
# 2. 入金
# 3. 出金
# 4. 終了
# 選択してください (1-4): 2
# 入金する金額を入力してください: 100
# 銀行プログラム
# 1. 残高表示
# 2. 入金
# 3. 出金
# 4. 終了
# 選択してください (1-4): 1
# あなたの残高は $100.00 です
# 銀行プログラム
# 1. 残高表示
# 2. 入金
# 3. 出金
# 4. 終了
# 選択してください (1-4): 2
# 入金する金額を入力してください: -420.69
# 無効な金額です
# TypeError: unsupported operand type(s) for +=: 'float' and 'NoneType'
def show_balance():
print(f"あなたの残高は ${balance:.2f} です")
def deposit():
amount = float(input("入金する金額を入力してください: "))
if amount < 0:
print("無効な金額です")
return 0
else:
return amount
def withdraw():
pass
balance = 0
is_running = True
while is_running:
print("銀行プログラム")
print("1. 残高表示")
print("2. 入金")
print("3. 出金")
print("4. 終了")
choice = input("選択してください (1-4): ")
if choice == '1':
show_balance()
elif choice == '2 ergo deposit():
balance += deposit()
elif choice == '3':
withdraw()
elif choice == '4':
is_running = False
else:
print("無効な選択です")
print("ありがとうございます!良い一日を!")
# 銀行プログラム
# 1. 残高表示
# 2. 入金
# 3. 出金
# 4. 終了
# 選択してください (1-4): 2
# 入金する金額を入力してください: -420.69
# 無効な金額です
# 銀行プログラム
# 1. 残高表示
# 2. 入金
# 3. 出金
# 4. 終了
# 選択してください (1-4): 2
# 入金する金額を入力してください: 50.01
# 銀行プログラム
# 1. 残高表示
# 2. 入金
# 3. 出金
# 4. 終了
# 選択してください (1-4): 1
# あなたの残高は $50.01 です
def show_balance():
print(f"あなたの残高は ${balance:.2f} です")
def deposit():
amount = float(input("入金する金額を入力してください: "))
if amount < 0:
print("無効な金額です")
return 0
else:
return amount
def withdraw():
amount = input("出金する金額を入力してください: ")
if amount > balance:
print("残高不足です")
return 0
elif amount < 0:
print("金額は0より大きくなければなりません")
return 0
else:
return amount
balance = 0
is_running = True
while is_running:
print("銀行プログラム")
print("1. 残高表示")
print("2. 入金")
print("3. 出金")
print("4. 終了")
choice = input("選択してください (1-4): ")
if choice == '1':
show_balance()
elif choice == '2':
balance += deposit()
elif choice == '3':
balance -= withdraw()
elif choice == '4':
is_running = False
else:
print("無効な選択です")
print("ありがとうございます!良い一日を!")
# 銀行プログラム
# 1. 残高表示
# 2. 入金
# 3. 出金
# 4. 終了
# 選択してください (1-4): 1
# あなたの残高は $0.00 です
# 銀行プログラム
# 1. 残高表示
# 2. 入金
# 3. 出金
# 4. 終了
# 選択してください (1-4): 2
# 入金する金額を入力してください: 100
# 銀行プログラム
# 1. 残高表示
# 2. 入金
# 3. 出金
# 4. 終了
# 選択してください (1-4): 1
# あなたの残高は $100.00 です
# 銀行プログラム
# 1. 残高表示
# 2. 入金
# 3. 出金
# 4. 終了
# 選択してください (1-4): 3
# 出金する金額を入力してください: 1000000000000000000000
# 残高不足です
# 銀行プログラム
# 1. 残高表示
# 2. 入金
# 3. 出金
# 4. 終了
# 選択してください (1-4): 3
# 出金する金額を入力してください: -420.69
# 金額は0より大きくなければなりません
# 銀行プログラム
# 1. 残高表示
# 2. 入金
# 3. 出金
# 4. 終了
# 選択してください (1-4): 3
# 出金する金額を入力してください: -49.99
# 銀行プログラム
# 1. 残高表示
# 2. 入金
# 3. 出金
# 4. 終了
# 選択してください (1-4): 1
# あなたの残高は $50.01 です
# 銀行プログラム
# 1. 残高表示
# 2. 入金
# 3. 出金
# 4. 終了
# 選択してください (1-4): 4
# ありがとうございます!良い一日を!
def show_balance(balance):
print("*********************")
print(f"あなたの残高は ${balance:.2f} です")
print("*********************")
def deposit():
print("*********************")
amount = float(input("入金する金額を入力してください: "))
print("*********************")
if amount < 0:
print("*********************")
print("無効な金額です")
print("*********************")
return 0
else:
return amount
def withdraw(balance):
print("*********************")
amount = input("出金する金額を入力してください: ")
print("*********************")
if amount > balance:
print("*********************")
print("残高不足です")
print("*********************")
return 0
elif amount < 0:
print("*********************")
print("金額は0より大きくなければなりません")
print("*********************")
return 0
else:
return amount
def main():
balance = 0
is_running = True
while is_running:
print("*********************")
print(" 銀行プログラム ")
print("*********************")
print("1. 残高表示")
print("2. 入金")
print("3. 出金")
print("4. 終了")
print("*********************")
choice = input("選択してください (1-4): ")
if choice == '1':
show_balance(balance)
elif choice == '2':
balance += deposit()
elif choice == '3':
balance -= withdraw(balance)
elif choice == '4':
is_running = False
else:
print("*********************")
print("無効な選択です")
print("*********************")
print("*********************")
print("ありがとうございます!良い一日を!")
print("*********************")
if __name__ == '__main__':
main()
# *********************
# 銀行プログラム
# *********************
# 1. 残高表示
# 2. 入金
# 3. 出金
# 4. 終了
# *********************
# 選択してください (1-4): 1
# *********************
# あなたの残高は $0.00 です
# *********************
# *********************
# 銀行プログラム
# *********************
# 1. 残高表示
# 2. 入金
# 3. 出金
# 4. 終了
# *********************
# 選択してください (1-4): 2
# *********************
# 入金する金額を入力してください: 100.01
# *********************
# *********************
# 銀行プログラム
# *********************
# 1. 残高表示
# 2. 入金
# 3. 出金
# 4. 終了
# *********************
# 選択してください (1-4): 1
# *********************
# あなたの残高は $100.01 です
# *********************
# *********************
# 銀行プログラム
# *********************
# 1. 残高表示
# 2. 入金
# 3. 出金
# 4. 終了
# *********************
# 選択してください (1-4): 3
# 出金する金額を入力してください: 1000
# *********************
# 残高不足です
# *********************
# *********************
# 銀行プログラム
# *********************
# 1. 残高表示
# 2. 入金
# 3. 出金
# 4. 終了
# *********************
# 選択してください (1-4): 3
# 出金する金額を入力してください: 50
# *********************
# 銀行プログラム
# *********************
# 1. 残高表示
# 2. 入金
# 3. 出金
# 4. 終了
# *********************
# 選択してください (1-4): 1
# *********************
# あなたの残高は $50.01 です
# *********************
# *********************
# 銀行プログラム
# *********************
# 1. 残高表示
# 2. 入金
# 3. 出金
# 4. 終了
# *********************
# 選択してください (1-4): 4
# *********************
# ありがとうございます!良い一日を!
# *********************
42. ⭐ スロットマシン 🎰
# Python スロットマシン
def spin_row():
pass
def print_row():
pass
def get_payout():
pass
def main():
pass
if __name__ == '__main__':
main()
def spin_row():
pass
def print_row():
pass
def get_payout():
pass
def main():
balance = 100
print("*************************")
print("Pythonスロットへようこそ")
print("シンボル: 🍒 🍉 🍋 🔔 ⭐️")
print("*************************")
while balance > 0:
print(f"現在の残高: ${balance}")
bet = input("ベット額を入力してください: ")
if not bet.isdigit():
print("有効な数字を入力してください")
continue
bet = int(bet)
if bet > balance:
print("残高が不足しています")
continue
if bet < 0:
print("ベット額は0より大きくなければなりません")
continue
balance -= bet
if __name__ == '__main__':
main()
# *************************
# Pythonスロットへようこそ
# シンボル: 🍒 🍉 🍋 🔔 ⭐️
# *************************
# 現在の残高: $100
# ベット額を入力してください: pizza
# 有効な数字を入力してください
# 現在の残高: $100
# ベット額を入力してください: 10000000000000000
# 残高が不足しています
# 現在の残高: $100
# ベット額を入力してください: 0
# ベット額は0より大きくなければなりません
# 現在の残高: $100
# ベット額を入力してください: 1
# 現在の残高: $99
# ベット額を入力してください: 10
# 現在の残高: $89
# ベット額を入力してください: 90
# 残高が不足しています
# 現在の残高: $89
# ベット額を入力してください: 89
import random
def spin_row():
symbols = ['🍒', '🍉', '🍋', '🔔', '⭐️']
# results =[]
# for symbols in range(3):
# results.append(random.choice(symbols))
# return results
return [random.choice(symbols) for _ in range(3)]
# return [random.choice(symbols) for symbols in range(3)]
def print_row():
pass
def get_payout():
pass
def main():
balance = 100
print("*************************")
print("Pythonスロットへようこそ")
print("シンボル: 🍒 🍉 🍋 🔔 ⭐️")
print("*************************")
while balance > 0:
print(f"現在の残高: ${balance}")
bet = input("ベット額を入力してください: ")
if not bet.isdigit():
print("有効な数字を入力してください")
continue
bet = int(bet)
if bet > balance:
print("残高が不足しています")
continue
if bet < 0:
print("ベット額は0より大きくなければなりません")
continue
balance -= bet
row = spin_row()
print(row)
if __name__ == '__main__':
main()
# *************************
# Pythonスロットへようこそ
# シンボル: 🍒 🍉 🍋 🔔 ⭐️
# *************************
# 現在の残高: $100
# ベット額を入力してください: 1
# ['⭐️', '🍋', '🍋']
# 現在の残高: $99
# ベット額を入力してください: 1
# ['🍉', '🍒', '⭐️']
# 現在の残高: $98
# ベット額を入力してください: 1
# ['🍒', '🍉', '🍒']
# 現在の残高: $97
# ベット額を入力してください: 1
# ['⭐️', '🍋', '⭐️']
# 現在の残高: $96
# ベット額を入力してください: 1
# ['🍋', '🍒', '🍋']
# 現在の残高: $95
# ベット額を入力してください:
import random
def spin_row():
symbols = ['🍒', '🍉', '🍋', '🔔', '⭐️']
# results =[]
# for symbols in range(3):
# results.append(random.choice(symbols))
# return results
return [random.choice(symbols) for _ in range(3)]
# return [random.choice(symbols) for symbols in range(3)]
def print_row(row):
print(" ".join(row))
def get_payout():
pass
def main():
balance = 100
print("*************************")
print("Pythonスロットへようこそ")
print("シンボル: 🍒 🍉 🍋 🔔 ⭐️")
print("*************************")
while balance > 0:
print(f"現在の残高: ${balance}")
bet = input("ベット額を入力してください: ")
if not bet.isdigitemans():
print("有効な数字を入力してください")
continue
bet = int(bet)
if bet > balance:
print("残高が不足しています")
continue
if bet < 0:
print("ベット額は0より大きくなければなりません")
continue
balance -= bet
row = spin_row()
print("スピン中...\n")
print_row(row)
if __name__ == '__main__':
main()
# *************************
# Pythonスロットへようこそ
# シンボル: 🍒 🍉 🍋 🔔 ⭐️
# *************************
# 現在の残高: $100
# ベット額を入力してください: 1
# スピン中...
#
# 🍋 ⭐️ 🔔
# 現在の残高: $99
# ベット額を入力してください:
import random
def spin_row():
symbols = ['🍒', '🍉', '🍋', '🔔', '⭐️']
# results =[]
# for symbols in range(3):
# results.append(random.choice(symbols))
# return results
return [random.choice(symbols) for _ in range(3)]
# return [random.choice(symbols) for symbols in range(3)]
def print_row(row):
print("*************")
print(" | ".join(row))
print("*************")
def get_payout():
pass
def main():
balance = 100
print("*************************")
print("Pythonスロットへようこそ")
print("シンボル: 🍒 🍉 🍋 🔔 ⭐️")
print("*************************")
while balance > 0:
print(f"現在の残高: ${balance}")
bet = input("ベット額を入力してください: ")
if not bet.isdigit():
print("有効な数字を入力してください")
continue
bet = int(bet)
if bet > balance:
print("残高が不足しています")
continue
if bet < 0:
print("ベット額は0より大きくなければなりません")
continue
balance -= bet
row = spin_row()
print("スピン中...\n")
print_row(row)
if __name__ == '__main__':
main()
# *************************
# Pythonスロットへようこそ
# シンボル: 🍒 🍉 🍋 🔔 ⭐️
# *************************
# 現在の残高: $100
# ベット額を入力してください: 1
# スピン中...
#
# *************
# 🔔 | 🍉 | ⭐️
# *************
# 現在の残高: $99
# ベット額を入力してください: 2
# スピン中...
#
# *************
# 🍒 | 🍒 | 🔔
# *************
# 現在の残高: $97
# ベット額を入力してください: 3
# スピン中...
#
# *************
# 🍒 | ⭐️ | ⭐️
# *************
# 現在の残高: $94
# ベット額を入力してください: 4
# スピン中...
#
# *************
# 🍉 | 🍉 | 🍉
# *************
# 現在の残高: $90
# ベット額を入力してください:
import random
def spin_row():
symbols = ['🍒', '🍉', '🍋', '🔔', '⭐️']
# results =[]
# for symbols in range(3):
# results.append(random.choice(symbols))
# return results
return [random.choice(symbols) for _ in range(3)]
# return [random.choice(symbols) for symbols in range(3)]
def print_row(row):
print("*************")
print(" | ".join(row))
print("*************")
def get_payout(row, bet):
if row[0] == row[1] == row[2]:
if row[0] == '🍒':
return bet * 3
elif row[0] == '🍉':
return bet * 4
elif row[0] == '🍋':
return bet * 5
elif row[0] == '🔔':
return bet * 10
elif row[0] == '⭐️':
return bet * 20
return 0
def main():
balance = 100
print("*************************")
print("Pythonスロットへようこそ")
print("シンボル: 🍒 🍉 🍋 🔔 ⭐️")
print("*************************")
while balance > 0:
print(f"現在の残高: ${balance}")
bet = input("ベット額を入力してください: ")
if not bet.isdigit():
print("有効な数字を入力してください")
continue
bet = int(bet)
if bet > balance:
print("残高が不足しています")
continue
if bet < 0:
print("ベット額は0より大きくなければなりません")
continue
balance -= bet
row = spin_row()
print("スピン中...\n")
print_row(row)
payout = get_payout(row, bet)
if payout > 0:
print(f"${payout}を獲得しました!")
else:
print("残念、このラウンドは負けました")
balance += payout
if __name__ == '__main__':
main()
# *************************
# Pythonスロットへようこそ
# シンボル: 🍒 🍉 🍋 🔔 ⭐️
# *************************
# 現在の残高: $100
# ベット額を入力してください: 1
# スピン中...
#
# *************
# 🔔 | 🍉 | ⭐️
# *************
# 残念、このラウンドは負けました
# 現在の残高: $99
# ベット額を入力してください: 2
# スピン中...
#
# *************
# 🍒 | 🍒 | 🔔
# *************
# 残念、このラウンドは負けました
# 現在の残高: $97
# ベット額を入力してください: 3
# スピン中...
#
# *************
# 🍒 | ⭐️ | ⭐️
# *************
# 残念、このラウンドは負けました
# 現在の残高: $94
# ベット額を入力してください: 1
# スピン中...
#
# *************
# 🍉 | 🍉 | 🍉
# *************
# $4を獲得しました!
# 現在の残高: $93
# ベット額を入力してください:
import random
def spin_row():
symbols = ['🍒', '🍉', '🍋', '🔔', '⭐️']
# results =[]
# for symbols in range(3):
# results.append(random.choice(symbols))
# return results
return [random.choice(symbols) for _ in range(3)]
# return [random.choice(symbols) for symbols in range(3)]
def print_row(row):
print("*************")
print(" | ".join(row))
print("*************")
def get_payout(row, bet):
if row[0] == row[1] == row[2]:
if row[0] == '🍒':
return bet * 3
elif row[0] == '🍉':
return bet * 4
elif row[0] == '🍋':
return bet * 5
elif row[0] == '🔔':
return bet * 10
elif row[0] == '⭐️':
return bet * 20
return 0
def main():
balance = 100
print("*************************")
print("Pythonスロットへようこそ")
print("シンボル: 🍒 🍉 🍋 🔔 ⭐️")
print("*************************")
while balance > 0:
print(f"現在の残高: ${balance}")
bet = input("ベット額を入力してください: ")
if not bet.isdigit():
print("有効な数字を入力してください")
continue
bet = int(bet)
if bet > balance:
print("残高が不足しています")
continue
if bet < 0:
print("ベット額は0より大きくなければなりません")
continue
balance -= bet
row = spin_row()
print("スピン中...\n")
print_row(row)
payout = get_payout(row, bet)
if payout > 0:
print(f"${payout}を獲得しました!")
else:
print("残念、このラウンドは負けました")
balance += payout
play_again = input("もう一度スピンしますか? (Y/N): ").upper()
if play_again != 'Y':
break
print("*******************************************")
print(f"ゲーム終了!最終残高は ${balance} です")
print("*******************************************")
if __name__ == '__main__':
main()
# *************************
# Pythonスロットへようこそ
# シンボル: 🍒 🍉 🍋 🔔 ⭐️
# *************************
# 現在の残高: $100
# ベット額を入力してください: 1
# スピン中...
#
# *************
# 🔔 | 🍉 | ⭐️
# *************
# 残念、このラウンドは負けました
# もう一度スピンしますか? (Y/N): y
# 現在の残高: $99
# ベット額を入力してください: 5
# スピン中...
#
# *************
# 🍒 | 🍒 | 🔔
# *************
# 残念、このラウンドは負けました
# もう一度スピンしますか? (Y/N): y
# 現在の残高: $94
# ベット額を入力してください: 90
# スピン中...
#
# *************
# 🍒 | ⭐️ | ⭐️
# *************
# 残念、このラウンドは負けました
# もう一度スピンしますか? (Y/N): y
# 現在の残高: $4
# ベット額を入力してください: 1
# スピン中...
#
# *************
# 🔔 | 🔔 | 🔔
# *************
# $10を獲得しました!
# もう一度スピンしますか? (Y/N): n
# ******************************************
# ゲーム終了!最終残高は $14 です
# ******************************************
43. ⭐ 暗号化プログラム 🔐
import string
# chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
chars = " " + string.punctuation + string.digits + string.ascii_letters
print(chars)
# !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
import string
chars = " " + string.punctuation + string.digits + string.ascii_letters
chars = list(chars)
print(chars)
# [' ', '!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_', '`', '{', '|', '}', '~', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
import string
chars = " " + string.punctuation + string.digits + string.ascii_letters
chars = list(chars)
key = chars.copy()
print(f"chars: {chars}")
print(f"key : {key}")
# chars: [' ', '!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_', '`', '{', '|', '}', '~', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
# key : [' ', '!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_', '`', '{', '|', '}', '~', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
import random
import string
chars = " " + string.punctuation + string.digits + string.ascii_letters
chars = list(chars)
key = chars.copy()
random.shuffle(key)
print(f"chars: {chars}")
print(f"key : {key}")
# chars: [' ', '!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_', '`', '{', '|', '}', '~', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
# key : ['k', '9', 'V', '=', '!', 'K', 'q', 'w', 'O', '}', 'Y', 'S', 'B', '*', 'm', '(', '[', 'G', '>', ' ', 'N', '^', ']', 'u', 'H', '/', 'l', 'z', 'v', 'c', ';', 'p', '_', 'M', '#', 'r', '3', 'J', 'e', 'D', 'I', '&', '2', '1', 'W', 't', 'j', '@', 'h', '6', 'i', '0', 'y', '.', 'Z', 'U', 'P', 'A', 'd', 'n', 'T', '4', 'E', 'x', 'Q', '7', 'f', '-', '"', 'o', 'b', '8', '|', '$', '~', 'C', 'X', 'R', ':', 'g', '?', ')', '+', 'F', '{', 's', '5', ',', 'L', '`', '%', 'a', '<', '\\', "'", 'T']
import random
import string
chars = " " + string.punctuation + string.digits + string.ascii_letters
chars = list(chars)
key = chars.copy()
random.shuffle(key)
print(f"chars: {chars}")
print(f"key : {key}")
# 暗号化
plain_text = input("暗号化するメッセージを入力してください: ")
cipher_text = ""
for letter in plain_text:
index = chars.index(letter)
cipher_text += key[index]
print(f"元のメッセージ : {plain_text}")
print(f"暗号化されたメッセージ: {cipher_text}")
# 暗号化するメッセージを入力してください: I like pizza!
# chars: [' ', '!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_', '`', '{', '|', '}', '~', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
# key : ['k', '9', 'V', '=', '!', 'K', 'q', 'w', 'O', '}', 'Y', 'S', 'B', '*', 'm', '(', '[', 'G', '>', 'R', ']', 'u', 'H', '/', 'l', 'z', 'c', ';', 'p', '_', 'M', '#', 'T', '4', '1', '2', '3', '0', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'y', 'L', 'x', 'n', 'o', 'p', 'q', 'r', 's', 't', 'A', 'v', 'W', 'X', 'Z', 't', 'J', 'C', 'P', 'Q', 'U', 'E', 'F', 'I', 'D', 'N', 'B', 'y', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
# 暗号化するメッセージを入力してください: I like pizza!
# 元のメッセージ : I like pizza!
# 暗号化されたメッセージ: D Liye piJJa9
import random
import string
chars = " " + string.punctuation + string.digits + string.ascii_letters
chars = list(chars)
key = chars.copy()
random.shuffle(key)
# print(f"chars: {chars}")
# print(f"key : {key}")
# 暗号化
plain_text = input("暗号化するメッセージを入力してください: ")
cipher_text = ""
for letter in plain_text:
index = chars.index(letter)
cipher_text += key[index]
print(f"元のメッセージ : {plain_text}")
print(f"暗号化されたメッセージ: {cipher_text}")
# 復号化
cipher_text = input("復号化するメッセージを入力してください: ")
plain_text = ""
for letter in cipher_text:
index = key.index(letter)
plain_text += chars[index]
print(f"暗号化されたメッセージ: {cipher_text}")
print(f"元のメッセージ : {plain_text}")
# 暗号化するメッセージを入力してください: I like pizza!
# 元のメッセージ : I like pizza!
# 暗号化されたメッセージ: NkLiyekpiJJa9
# 復号化するメッセージを入力してください: NkLiyekpiJJa9
# 暗号化されたメッセージ: NkLiyekpiJJa9
# 元のメッセージ : I like pizza!
44. ⭐ ハングマンゲーム 🕺
# Pythonでのハングマン
import random
words = ("apple", "orange", "banana", "coconut", "pineapple")
# キー:() の辞書
hangman_art = {0: (" ",
" ",
" "),
1: (" o ",
" ",
" ",
" "),
2: (" o ",
" | ",
" "),
3: (" o ",
"/| ",
" "),
4: (" o ",
"/|\\",
" "),
5: (" o ",
"/|\\",
"/ "),
6: (" o ",
"/|\\",
"/ \\")}
# print(hangman_art[3])
# (' o ', '/| ', ' ')
for line in hangman_art[3]:
print(line)
# o
# /|
#
import random
words = ("apple", "orange", "banana", "coconut", "pineapple")
# キー:() の辞書
hangman_art = {0: (" ",
" ",
" "),
1: (" o ",
" ",
" ",
" "),
2: (" o ",
" | ",
" "),
3: (" o ",
"/| ",
" "),
4: (" o ",
"/|\\",
" "),
5: (" o ",
"/|\\",
"/ "),
6: (" o ",
"/|\\",
"/ \\")}
def display_man(wrong_guesses):
print("**********")
for line in hangman_art[wrong_guesses]:
print(line)
print("**********")
def display_hint(hint):
pass
def display_answer(answer):
pass
def main():
answer = random.choice(words)
# print(answer)
# apple
hint = ["_"] * len(answer)
# print(hint)
# ['_', '_', '_', '_', '_']
wrong_guesses = 6
guessed_letters = set()
is_running = True
while is_running:
display_man(wrong_guesses)
display_hint(hint)
guess = input("文字を入力してください: ").lower()
if __name__ == '__main__':
main()
# **********
# o
# /|\
# / \
# **********
# 文字を入力してください:
# wordslist.py
words = ("apple", "orange", "banana", "coconut", "pineapple")
# main.py
from wordslist import words
import random
# キー:() の辞書
hangman_art = {0: (" ",
" ",
" "),
1: (" o ",
" ",
" ",
" "),
2: (" o ",
" | ",
" "),
3: (" o ",
"/| ",
" "),
4: (" o ",
"/|\\",
" "),
5: (" o ",
"/|\\",
"/ "),
6: (" o ",
"/|\\",
"/ \\")}
def display_man(wrong_guesses):
print("**********")
for line in hangman_art[wrong_guesses]:
print(line)
print("**********")
def display_hint(hint):
print(" ".join(hint))
def display_answer(answer):
print(" ".join(answer))
def main():
answer = random.choice(words)
hint = ["_"] * len(answer)
wrong_guesses = 0
guessed_letters = set()
is_running = True
while is_running:
display_man(wrong_guesses)
display_hint(hint)
guess = input("文字を入力してください: ").lower()
if len(guess) != 1 or not guess.isalpha():
print("無効な入力です")
continue
if guess in guessed_letters:
print(f"{guess} はすでに推測済みです")
continue
guessed_letters.add(guess)
if guess in answer:
for i in range(len(answer)):
if answer[i] == guess:
hint[i] = guess
else:
wrong_guesses += 1
if "_" not in hint:
display_man(wrong_guesses)
display_answer(answer)
print("勝利!")
is_running = False
elif wrong_guesses >= len(hangman_art) - 1:
display_man(wrong_guesses)
display_answer(answer)
print("敗北!")
is_running = False
if __name__ == '__main__':
main()
# **********
#
#
#
# **********
# _ _ _ _ _ _ _ _ _
# 文字を入力してください: p
# **********
#
#
#
# **********
# p _ _ _ _ p p _ _
# 文字を入力してください: &
# 無効な入力です
# **********
#
#
#
# **********
# p _ _ _ _ p p _ _
# 文字を入力してください: i
# **********
#
#
#
# **********
# p i _ _ _ p p _ _
# 文字を入力してください: n
# **********
#
#
#
# **********
# p i n _ _ p p _ _
# 文字を入力してください: p
# p はすでに推測済みです
# **********
#
#
#
# **********
# p i n _ _ p p _ _
# 文字を入力してください: x
# **********
# o
#
#
#
# **********
# p i n _ _ p p _ _
# 文字を入力してください: z
# **********
# o
# |
#
# **********
# p i n _ _ p p _ _
# 文字を入力してください: e
# **********
# o
# |
#
# **********
# p i n e _ p p _ e
# 文字を入力してください: a
# **********
# o
# |
#
# **********
# p i n e a p p _ e
# 文字を入力してください: l
# **********
# o
# |
#
# **********
# p i n e a p p l e
# 勝利!
45. Python オブジェクト指向プログラミング 🚗
object(オブジェクト) = 関連する属性(変数)とメソッド(関数)の「束」
例:電話、カップ、本
多くのオブジェクトを作成するには「クラス」が必要です。
class(クラス) = オブジェクトの構造とレイアウトを設計するための(設計図)
class Car:
def __init__(self, model, year, color, for_sale):
self.model = model
self.year = year
self.color = color
self.for_sale = for_sale
car1 = Car("Mustang", 2024, "red", False)
print(car1)
# <__main__.Car object at 0x000001AE490AE610>
print(car1.model)
# Mustang
print(car1.year)
# 2024
print(car1.color)
# red
print(car1.for_sale)
# False
# car.py
class Car:
def __init__(self, model, year, color, for_sale):
self.model = model
self.year = year
self.color = color
self.for_sale = for_sale
# main.py
from car import Car
car1 = Car("Mustang", 2024, "red", False)
car2 = Car("Corvette", 2025, "blue", True)
car3 = Car("Charger", 2026, "yellow", True)
print(car1.model)
# Mustang
print(car1.year)
# 2024
print(car1.color)
# red
print(car1.for_sale)
# False
# car.py
class Car:
def __init__(self, model, year, color, for_sale):
self.model = model
self.year = year
self.color = color
self.for_sale = for_sale
def drive(self):
print("あなたは車を運転します")
def stop(self):
print("あなたは車を止めます")
# main.py
from car import Car
car1 = Car("Mustang", 2024, "red", False)
car2 = Car("Corvette", 2025, "blue", True)
car3 = Car("Charger", 2026, "yellow", True)
car1.drive()
# あなたは車を運転します
car2.drive()
# あなたは車を運転します
car1.stop()
# あなたは車を止めます
car2.stop()
# あなたは車を止めます
# car.py
class Car:
def __init__(self, model, year, color, for_sale):
self.model = model
self.year = year
self.color = color
self.for_sale = for_sale
def drive(self):
print(f"あなたは{self.color}の{self.model}を運転します")
def stop(self):
print(f"あなたは{self.color}の{self.model}を止めます")
def describe(self):
print(f"{self.year}年 {self.color}の{self.model}")
# main.py
from car import Car
car1 = Car("Mustang", 2024, "red", False)
car2 = Car("Corvette", 2025, "blue", True)
car3 = Car("Charger", 2026, "yellow", True)
car1.drive()
# あなたはredのMustangを運転します
car1.stop()
# あなたはredのMustangを止めます
car1.describe()
# 2024年 redのMustang
46. クラス変数 🎓
クラス変数 = クラスのすべてのインスタンス間で共有される
コンストラクタの外で定義される
そのクラスから作成されたすべてのオブジェクト間でデータを共有できる
class Car:
wheels = 4 # クラス変数
def __init__(self, model, year):
self.model = model # インスタンス変数
self.year = year # インスタンス変数
class Student:
class_year = 2024 # クラス変数
def __init__(self, name, age):
self.name = name
self.age = age
student1 = Student("Spongebob", 30)
student2 = Student("Patrick", 35)
print(student1.name)
print(student1.age)
# Spongebob
# 30
print(student1.class_year)
print(student2.class_year)
print(Student.class_year)
# 2024
# 2024
# 2024
class Student:
class_year = 2024 # クラス変数
num_students = 0 # クラス変数
def __init__(self, name, age):
self.name = name
self.age = age
Student.num_students += 1
student1 = Student("Spongebob", 30)
student2 = Student("Patrick", 35)
student3 = Student("Squidward", 35)
student4 = Student("Sandy", 35)
print(Student.num_students)
# 4
print(f"{Student.class_year}年の私の卒業クラスには{Student.num_students}人の学生がいます")
print(student1.name)
print(student2.name)
print(student3.name)
print(student4.name)
# 2024年の私の卒業クラスには4人の学生がいます
# Spongebob
# Patrick
# Squidward
# Sandy
47. 継承 👨👦👦
継承 = あるクラスが別のクラスの属性やメソッドを引き継ぐことを可能にする
コードの再利用性と拡張性を向上させる
class Child(Parent)
class Sub(Super)
class Father:
height = 182
color = "pink"
class Son(Father):
pass
class Animal:
def __init__(self, name):
self.name = name
self.is_alive = True
def eat(self):
print(f"{self.name} が食べています")
def sleep(self):
print(f"{self.name} が寝ています")
class Dog(Animal):
pass
class Cat(Animal):
pass
class Mouse(Animal):
pass
dog = Dog("Scooby")
cat = Cat("Garfield")
mouse = Mouse("Mickey")
print(dog.name)
print(dog.is_alive)
dog.eat()
dog.sleep()
# Scooby
# True
# Scooby が食べています
# Scooby が寝ています
class Animal:
def __init__(self, name):
self.name = name
self.is_alive = True
def eat(self):
print(f"{self.name} が食べています")
def sleep(self):
print(f"{self.name} が寝ています")
class Dog(Animal):
def speak(self):
print("ワン!")
class Cat(Animal):
def speak(self):
print("ニャー!")
class Mouse(Animal):
def speak(self):
print("チューチュー!")
dog = Dog("Scooby")
cat = Cat("Garfield")
mouse = Mouse("Mickey")
dog.speak()
# ワン!
48. 多重継承 🐟
多重継承 = 複数の親クラスから継承する
C(A, B)
多重継承 = ある親クラスが別の親クラスから継承している場合に継承する
C(B) <- B(A) <- A
class Prey:
pass
class Predator:
pass
class Rabbit:
pass
class Hawk:
pass
class Fish:
pass
class Prey:
def flee(self):
print("この動物は逃げています")
class Predator:
def hunt(self):
print("この動物は狩りをしています")
class Rabbit(Prey):
pass
class Hawk(Predator):
pass
class Fish(Prey, Predator):
pass
rabbit = Rabbit()
hawk = Hawk()
fish = Fish()
rabbit.flee()
# この動物は逃げています
rabbit.hunt()
# AttributeError: 'Rabbit' オブジェクトには 'hunt' 属性がありません
hawk.hunt()
# この動物は狩りをしています
hawk.flee()
# AttributeError: 'Hawk' オブジェクトには 'flee' 属性がありません
fish.flee()
# この動物は逃げています
fish.hunt()
# この動物は狩りをしています
class Animal:
def __init__(self, name):
self.name = name
def eat(self):
print(f"{self.name} は食べています")
def sleep(self):
print(f"{self.name} は寝ています")
class Prey(Animal):
def flee(self):
print(f"{self.name} は逃げています")
class Predator(Animal):
def hunt(self):
print(f"{self.name} は狩りをしています")
class Rabbit(Prey):
pass
class Hawk(Predator):
pass
class Fish(Prey, Predator):
pass
rabbit = Rabbit("バッグス")
hawk = Hawk("トニー")
fish = Fish("ニモ")
rabbit.eat()
# バッグス は食べています
rabbit.sleep()
# バッグス は寝ています
rabbit.flee()
# バッグス は逃げています
hawk.flee()
# AttributeError: 'Hawk' オブジェクトには 'flee' 属性がありません
hawk.eat()
# トニー は食べています
hawk.hunt()
# トニー は狩りをしています
fish.eat()
fish.sleep()
fish.flee()
fish.hunt()
# ニモ は食べています
# ニモ は寝ています
# ニモ は逃げています
# ニモ は狩りをしています
49. super() 🔴
super() = 子クラス内で親クラス(スーパークラス)のメソッドを呼び出すために使用される関数。
継承したメソッドの機能を拡張することができます。
class Super: # 👨🏻
pass
class Sub(Super): # 👶🏻
pass
class super
class super(type, object_or_type=None)
親クラスまたは兄弟クラスのメソッド呼び出しを委譲するプロキシオブジェクトを返します。これは、クラス内でオーバーライドされた継承メソッドにアクセスする際に便利です。
object_or_typeは、検索されるメソッド解決順序(MRO)を決定します。検索はtypeの直後のクラスから始まります。
class Circle:
def __init__(self, color, is_filled, radius):
self.color = color
self.is_filled = is_filled
self.radius = radius
class Square:
def __init__(self, color, is_filled, width):
self.color = color
self.is_filled = is_filled
self.width = width
class Triangle:
def __init__(self, color, is_filled, width, height):
self.color = color
self.is_filled = is_filled
self.width = width
self.height = height
class Shape:
def __init__(self, color, is_filled):
self.color = color
self.is_filled = is_filled
class Circle(Shape):
def __init__(self, color, is_filled, radius):
super().__init__(color, is_filled)
self.radius = radius
class Square(Shape):
def __init__(self, color, is_filled, width):
super().__init__(color, is_filled)
self.width = width
class Triangle(Shape):
def __init__(self, color, is_filled, width, height):
super().__init__(color, is_filled)
self.width = width
self.height = height
circle = Circle(color="red", is_filled=True, radius=5)
square = Square(color="blue", is_filled=False, width=6)
triangle = Triangle(color="yellow", is_filled=True, width=7, height=8)
print(circle.color)
print(circle.is_filled)
print(f"{circle.radius}cm")
# 赤
# True
# 5cm
print(square.color)
print(square.is_filled)
print(f"{square.width}cm")
# 青
# False
# 6cm
print(triangle.color)
print(triangle.is_filled)
print(f"{triangle.width}cm")
print(f"{triangle.height}cm")
# 黄色
# True
# 7cm
# 8cm
class Shape:
def __init__(self, color, is_filled):
self.color = color
self.is_filled = is_filled
def describe(self):
print(f"それは{self.color}で、{'塗りつぶされている' if self.is_filled else '塗りつぶされていない'}")
class Circle(Shape):
def __init__(self, color, is_filled, radius):
super().__init__(color, is_filled)
self.radius = radius
class Square(Shape):
def __init__(self, color, is_filled, width):
super().__init__(color, is_filled)
self.width = width
class Triangle(Shape):
def __init__(self, color, is_filled, width, height):
super().__init__(color, is_filled)
self.width = width
self.height = height
circle = Circle(color="red", is_filled=True, radius=5)
square = Square(color="blue", is_filled=False, width=6)
triangle = Triangle(color="yellow", is_filled=True, width=7, height=8)
circle.describe()
# それは赤で、塗りつぶされている
square.describe()
# それは青で、塗りつぶされていない
triangle.describe()
# それは黄色で、塗りつぶされている
class Shape:
def __init__(self, color, is_filled):
self.color = color
self.is_filled = is_filled
def describe(self):
print(f"それは{self.color}で、{'塗りつぶされている' if self.is_filled else '塗りつぶされていない'}")
class Circle(Shape):
def __init__(self, color, is_filled, radius):
super().__init__(color, is_filled)
self.radius = radius
def describe(self):
super().describe()
print(f"これは面積が{3.14 * self.radius * self.radius}cm^2の円です")
class Square(Shape):
def __init__(self, color, is_filled, width):
super().__init__(color, is_filled)
self.width = width
def describe(self):
super().describe()
print(f"これは面積が{self.width * self.width}cm^2の正方形です")
class Triangle(Shape):
def __init__(self, color, is_filled, width, height):
super().__init__(color, is_filled)
self.width = width
self.height = height
def describe(self):
super().describe()
print(f"これは面積が{self.width * self.height / 2}cm^2の三角形です")
circle = Circle(color="red", is_filled=True, radius=5)
square = Square(color="blue", is_filled=False, width=6)
triangle = Triangle(color="yellow", is_filled=True, width=7, height=8)
circle.describe()
# それは赤で、塗りつぶされている
# これは面積が78.5cm^2の円です
square.describe()
# それは青で、塗りつぶされていない
# これは面積が36cm^2の正方形です
triangle.describe()
# それは黄色で、塗りつぶされている
# これは面積が28.0cm^2の三角形です
50. ポリモーフィズム 🎭
ポリモーフィズム (Polymorphism) = ギリシャ語で「多くの形や顔を持つ」という意味
Poly = 多く
Morphe = 形
ポリモーフィズムを実現する2つの方法
1. 継承 = オブジェクトを親クラスの型として扱うことができる
2. 「ダックタイピング」 = オブジェクトが必要な属性/メソッドを持っている必要がある
class Shape:
pass
class Circle(Shape):
pass
class Square(Shape):
pass
class Triangle(Shape):
pass
circle = Circle()
square = Square()
triangle = Triangle()
shapes = [Circle(), Square(), Triangle()]
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side ** 2
class Triangle(Shape):
def __init__(self, base, height):
self.base = base
self.height = height
def area(self):
return self.base * self.height * 0.5
shapes = [Circle(4), Square(5), Triangle(6, 7)]
for shape in shapes:
print(f"{shape.area()}cm²")
# 50.24cm²
# 25cm²
# 21.0cm²
(上付き文字²の入力方法):
Windows: Alt + 0178
Mac: Control + Command + Space
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side ** 2
class Triangle(Shape):
def __init__(self, base, height):
self.base = base
self.height = height
def area(self):
return self.base * self.height * 0.5
class Pizza:
def __init__(self, topping, radius):
self.topping = topping
self.radius = radius
shapes = [Circle(4), Square(5), Triangle(6, 7), Pizza("ペパロニ", 15)]
for shape in shapes:
print(f"{shape.area()}cm²")
# AttributeError: 'Pizza' オブジェクトには 'area' 属性がありません
# 50.24cm²
# 25cm²
# 21.0cm²
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side ** 2
class Triangle(Shape):
def __init__(self, base, height):
self.base = base
self.height = height
def area(self):
return self.base * self.height * 0.5
class Pizza(Circle):
def __init__(self, topping, radius):
super().__init__(radius)
self.topping = topping
shapes = [Circle(4), Square(5), Triangle(6, 7), Pizza("ペパロニ", 15)]
for shape in shapes:
print(f"{shape.area()}cm²")
# 50.24cm²
# 25cm²
# 21.0cm²
# 706.5cm²
51. ダックタイピング 🦆
「ダックタイピング」 = 継承以外のポリモーフィズムを実現するもう一つの方法
オブジェクトは必要最小限の属性/メソッドを持つ必要があります
「もしそれがアヒルのように見えて、アヒルのように鳴くなら、それはアヒルに違いない。」
class Animal:
alive = True
class Dog(Animal):
def speak(self):
print("WOOF!")
class Cat(Animal):
def speak(self):
print("MEOW!")
class Car():
def horn(self):
print("HONK!")
animals = [Dog(), Cat(), Car()]
for animal in animals:
animal.speak()
# AttributeError: 'Car' オブジェクトには 'speak' 属性がありません
# WOOF!
# MEOW!
class Animal:
alive = True
class Dog(Animal):
def speak(self):
print("WOOF!")
class Cat(Animal):
def speak(self):
print("MEOW!")
class Car():
def speak(self):
print("HONK!")
animals = [Dog(), Cat(), Car()]
for animal in animals:
animal.speak()
print(animal.alive)
# AttributeError: 'Car' オブジェクトには 'alive' 属性がありません
# WOOF!
# True
# MEOW!
# True
# HONK!
class Animal:
alive = True
class Dog(Animal):
def speak(self):
print("WOOF!")
class Cat(Animal):
def speak(self):
print("MEOW!")
class Car():
alive = False
def speak(self):
print("HONK!")
animals = [Dog(), Cat(), Car()]
for animal in animals:
animal.speak()
print(animal.alive)
# WOOF!
# True
# MEOW!
# True
# HONK!
# False
52. 静的メソッド ⚡
静的メソッド = クラスのインスタンス(オブジェクト)ではなく、クラス自体に属するメソッド
通常、汎用的なユーティリティ関数に使用される
インスタンスメソッド = クラスのインスタンス(オブジェクト)に対する操作に最適
# インスタンスメソッド
def get_info(self):
return f"{self.name} = {self.position}"
静的メソッド = クラスデータにアクセスする必要がないユーティリティ関数に最適
@staticmethod
def km_to_miles(kilometers):
return kilometers * 0.621371
class Employee:
def __init__(self, name, position):
self.name = name
self.position = position
def get_info(self):
return f"{self.name} = {self.position}"
@staticmethod
def is_valid_position(position):
valid_positions = ["マネージャー", "レジ係", "調理師", "清掃員"]
return position in valid_positions
print(Employee.is_valid_position("調理師"))
# True
print(Employee.is_valid_position("ロケット科学者"))
# False
class Employee:
def __init__(self, name, position):
self.name = name
self.position = position
def get_info(self):
return f"{self.name} = {self.position}"
@staticmethod
def is_valid_position(position):
valid_positions = ["マネージャー", "レジ係", "調理師", "清掃員"]
return position in valid_positions
employee1 = Employee("ユージン", "マネージャー")
employee2 = Employee("スクイッドワード", "レジ係")
employee3 = Employee("スポンジボブ", "調理師")
print(Employee.is_valid_position("ロケット科学者"))
# False
print(employee1.get_info())
print(employee2.get_info())
print(employee3.get_info())
# ユージン = マネージャー
# スクイッドワード = レジ係
# スポンジボブ = 調理師
53. クラスメソッド 🏫
クラスメソッド = クラス自体に関連する操作を可能にする
最初の引数として (cls) を受け取り、これはクラス自体を表す。
インスタンスメソッド = クラスのインスタンス(オブジェクト)に対する操作に最適
スタティックメソッド = クラスデータにアクセスする必要がないユーティリティ関数に最適
クラスメソッド = クラスレベルのデータやクラス自体へのアクセスが必要な場合に最適
class Student:
count = 0
def __init__(self, name, gpa):
self.name = name
self.gpa = gpa
Student.count += 1
# インスタンスメソッド
def get_info(self):
return f"{self.name} {self.gpa}"
@classmethod
def get_count(cls):
return f"生徒の総数: {cls.count}"
print(Student.get_count())
# 生徒の総数: 0
class Student:
count = 0
def __init__(self, name, gpa):
self.name = name
self.gpa = gpa
Student.count += 1
# インスタンスメソッド
def get_info(self):
return f"{self.name} {self.gpa}"
@classmethod
def get_count(cls):
return f"生徒の総数: {cls.count}"
student1 = Student("スポンジボブ", 3.2)
student2 = Student("パトリック", 2.0)
student3 = Student("サンディ", 4.0)
print(Student.get_count())
# 生徒の総数: 3
class Student:
count = 0
total_gpa = 0
def __init__(self, name, gpa):
self.name = name
self.gpa = gpa
Student.count += 1
Student.total_gpa += gpa # 修正: GPAを加算
# インスタンスメソッド
def get_info(self):
return f"{self.name} {self.gpa}"
@classmethod
def get_count(cls):
return f"生徒の総数: {cls.count}"
@classmethod
def get_average_gpa(cls):
if cls.count == 0:
return 0
else:
return f"平均GPA: {cls.total_gpa / cls.count:.2f}"
student1 = Student("スポンジボブ", 3.2)
student2 = Student("パトリック", 2.0)
student3 = Student("サンディ", 4.0)
print(Student.get_count())
# 生徒の総数: 3
print(Student.get_average_gpa())
# 平均GPA: 3.07
54. マジックメソッド 🌟
マジックメソッド = ダンダーメソッド(ダブルアンダースコア) __init__
, __str__
, __eq__
Pythonの多くの組み込み操作によって自動的に呼び出されます。
開発者がオブジェクトの振る舞いを定義またはカスタマイズすることができます。
class Student:
def __init__(self, name, gpa):
self.name = name
self.gpa = gpa
def __str__(self):
return f"名前: {self.name} GPA: {self.gpa}"
def __eq__(self, other):
return self.name == other.name
def __gt__(self, other):
return self.gpa > other.gpa
student1 = Student("Spongebob", 3.2)
student2 = Student("Patrick", 2.0)
print(student1)
print(student1 == student2)
print(student1 > student2)
# 名前: Spongebob GPA: 3.2
# False
# True
class Book:
def __init__(self, title, author, num_pages):
self.title = title
self.author = author
self.num_pages = num_pages
book1 = Book("ホビットの冒険", "J.R.R. Tolkien", 310)
book2 = Book("ハリー・ポッターと賢者の石", "J.K. Rowling", 223)
book3 = Book("ライオン、魔女、ワードローブ", "C.S. Lewis", 172)
print(book1)
# <__main__.Book object at 0x000001E78F76EE50>
class Book:
def __init__(self, title, author, num_pages):
self.title = title
self.author = author
self.num_pages = num_pages
def __str__(self):
return f"『{self.title}』 {self.author}著"
book1 = Book("ホビットの冒険", "J.R.R. Tolkien", 310)
book2 = Book("ハリー・ポッターと賢者の石", "J.K. Rowling", 223)
book3 = Book("ライオン、魔女、ワードローブ", "C.S. Lewis", 172)
book4 = Book("ライオン、魔女、ワードローブ", "C.S. Lewis", 172)
print(book1)
# 『ホビットの冒険』 J.R.R. Tolkien著
print(book3 == book4)
# False
class Book:
def __init__(self, title, author, num_pages):
self.title = title
self.author = author
self.num_pages = num_pages
def __str__(self):
return f"『{self.title}』 {self.author}著"
def __eq__(self, other):
return self.title == other.title and self.author == other.author
book1 = Book("ホビットの冒険", "J.R.R. Tolkien", 310)
book2 = Book("ハリー・ポッターと賢者の石", "J.K. Rowling", 223)
book3 = Book("ライオン、魔女、ワードローブ", "C.S. Lewis", 172)
book4 = Book("ライオン、魔女、ワードローブ", "C.S. Lewis", 17222)
print(book1)
# 『ホビットの冒険』 J.R.R. Tolkien著
print(book3 == book4)
# True
print(book2 < book3)
# TypeError: '<' not supported between instances of 'Book' and 'Book'
class Book:
def __init__(self, title, author, num_pages):
self.title = title
self.author = author
self.num_pages = num_pages
def __str__(self):
return f"『{self.title}』 {self.author}著"
def __eq__(self, other):
return self.title == other.title and self.author == other.author
def __lt__(self, other):
return self.num_pages < other.num_pages
def __gt__(self, other):
return self.num_pages > other.num_pages
book1 = Book("ホビットの冒険", "J.R.R. Tolkien", 310)
book2 = Book("ハリー・ポッターと賢者の石", "J.K. Rowling", 223)
book3 = Book("ライオン、魔女、ワードローブ", "C.S. Lewis", 172)
book4 = Book("ライオン、魔女、ワードローブ", "C.S. Lewis", 17222)
print(book2 < book3)
# False
print(book2 > book3)
# True
print(book2 + book3)
# TypeError: unsupported operand type(s) for +: 'Book' and 'Book'
class Book:
def __init__(self, title, author, num_pages):
self.title = title
self.author = author
self.num_pages = num_pages
def __str__(self):
return f"『{self.title}』 {self.author}著"
def __eq__(self, other):
return self.title == other.title and self.author == other.author
def __lt__(self, other):
return self.num_pages < other.num_pages
def __gt__(self, other):
return self.num_pages > other.num_pages
def __add__(self, other):
return f"{self.num_pages + other.num_pages} ページ"
book1 = Book("ホビットの冒険", "J.R.R. Tolkien", 310)
book2 = Book("ハリー・ポッターと賢者の石", "J.K. Rowling", 223)
book3 = Book("ライオン、魔女、ワードローブ", "C.S. Lewis", 172)
book4 = Book("ライオン、魔女、ワードローブ", "C.S. Lewis", 17222)
print(book2 + book3)
# 395 ページ
print("ライオン" in book3)
# TypeError: argument of type 'Book' is not iterable
class Book:
def __init__(self, title, author, num_pages):
self.title = title
self.author = author
self.num_pages = num_pages
def __str__(self):
return f"『{self.title}』 {self.author}著"
def __eq__(self, other):
return self.title == other.title and self.author == other.author
def __lt__(self, other):
return self.num_pages < other.num_pages
def __gt__(self, other):
return self.num_pages > other.num_pages
def __add__(self, other):
return f"{self.num_pages + other.num_pages} ページ"
def __contains__(self, keyword):
return keyword in self.title or keyword in self.author
book1 = Book("ホビットの冒険", "J.R.R. Tolkien", 310)
book2 = Book("ハリー・ポッターと賢者の石", "J.K. Rowling", 223)
book3 = Book("ライオン、魔女、ワードローブ", "C.S. Lewis", 172)
print("ライオン" in book3)
# True
print("ライオン" in book1)
# False
print("Rowling" in book2)
# True
print("Rowling" in book3)
# False
print(book1['title'])
# TypeError: 'Book' object is not subscriptable
class Book:
def __init__(self, title, author, num_pages):
self.title = title
self.author = author
self.num_pages = num_pages
def __str__(self):
return f"『{self.title}』 {self.author}著"
def __eq__(self, other):
return self.title == other.title and self.author == other.author
def __lt__(self, other):
return self.num_pages < other.num_pages
def __gt__(self, other):
return self.num_pages > other.num_pages
def __add__(self, other):
return f"{self.num_pages + other.num_pages} ページ"
def __contains__(self, keyword):
return keyword in self.title or keyword in self.author
def __getitem__(self, key):
if key == "title":
return self.title
book1 = Book("ホビットの冒険", "J.R.R. Tolkien", 310)
book2 = Book("ハリー・ポッターと賢者の石", "J.K. Rowling", 223)
book3 = Book("ライオン、魔女、ワードローブ", "C.S. Lewis", 172)
print(book1['title'])
# ホビットの冒険
print(book2['title'])
# ハリー・ポッターと賢者の石
print(book3['title'])
# ライオン、魔女、ワードローブ
print(book3['author'])
# None
class Book:
def __init__(self, title, author, num_pages):
self.title = title
self.author = author
self.num_pages = num_pages
def __str__(self):
return f"『{self.title}』 {self.author}著"
def __eq__(self, other):
return self.title == other.title and self.author == other.author
def __lt__(self, other):
return self.num_pages < other.num_pages
def __gt__(self, other):
return self.num_pages > other.num_pages
def __add__(self, other):
return f"{self.num_pages + other.num_pages} ページ"
def __contains__(self, keyword):
return keyword in self.title or keyword in self.author
def __getitem__(self, key):
if key == "title":
return self.title
elif key == "author":
return self.author
book1 = Book("ホビットの冒険", "J.R.R. Tolkien", 310)
book2 = Book("ハリー・ポッターと賢者の石", "J.K. Rowling", 223)
book3 = Book("ライオン、魔女、ワードローブ", "C.S. Lewis", 172)
print(book3['author'])
# C.S. Lewis
print(book2['author'])
# J.K. Rowling
print(book1['author'])
# J.R.R. Tolkien
print(book1['num_pages'])
# None
class Book:
def __init__(self, title, author, num_pages):
self.title = title
self.author = author
self.num_pages = num_pages
def __str__(self):
return f"『{self.title}』 {self.author}著"
def __eq__(self, other):
return self.title == other.title and self.author == other.author
def __lt__(self, other):
return self.num_pages < other.num_pages
def __gt__(self, other):
return self.num_pages > other.num_pages
def __add__(self, other):
return f"{self.num_pages + other.num_pages} ページ"
def __contains__(self, keyword):
return keyword in self.title or keyword in self.author
def __getitem__(self, key):
if key == "title":
return self.title
elif key == "author":
return self.author
elif key == "num_pages":
return self.num_pages
else:
return f"キー '{key}' が見つかりませんでした"
book1 = Book("ホビットの冒険", "J.R.R. Tolkien", 310)
book2 = Book("ハリー・ポッターと賢者の石", "J.K. Rowling", 223)
book3 = Book("ライオン、魔女、ワードローブ", "C.S. Lewis", 172)
print(book1['num_pages'])
# 310
print(book2['num_pages'])
# 223
print(book3['num_pages'])
# 172
print(book3['audio'])
# キー 'audio' が見つかりませんでした
55. @property ⚙️
@property
= メソッドをプロパティとして定義するために使用されるデコレーター(属性のようにアクセス可能)
利点:属性の読み取り、書き込み、削除時に追加のロジックを適用できる
ゲッター、セッター、デリーターメソッドを提供する
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
rectangle = Rectangle(3, 4)
print(rectangle.width)
print(rectangle.height)
# 3
# 4
class Rectangle:
def __init__(self, width, height):
self._width = width
self._height = height
@property
def width(self):
pass
@property
def height(self):
pass
rectangle = Rectangle(3, 4)
print(rectangle.width)
print(rectangle.height)
# 3
# 4
class Rectangle:
def __init__(self, width, height):
self._width = width
self._height = height
@property
def width(self):
return f"{self._width:.1f}cm"
@property
def height(self):
return f"{self._height:.1f}cm"
rectangle = Rectangle(3, 4)
print(rectangle.width)
print(rectangle.height)
# 3.0cm
# 4.0cm
print(rectangle._width)
print(rectangle._height)
# 3
# 4
class Rectangle:
def __init__(self, width, height):
self._width = width
self._height = height
@property
def width(self):
return f"{self._width:.1f}cm"
@property
def height(self):
return f"{self._height:.1f}cm"
@width.setter
def width(self, new_width):
if new_width > 0:
self._width = new_width
else:
print("幅は0より大きくする必要があります")
@height.setter
def height(self, new_height):
if new_height > 0:
self._height = new_height
else:
print("高さは0より大きくする必要があります")
rectangle = Rectangle(3, 4)
rectangle.width = 0
rectangle.height = -1
print(rectangle.width)
print(rectangle.height)
# 幅は0より大きくする必要があります
# 高さは0より大きくする必要があります
# 3.0cm
# 4.0cm
class Rectangle:
def __init__(self, width, height):
self._width = width
self._height = height
@property
def width(self):
return f"{self._width:.1f}cm"
@property
def height(self):
return f"{self._height:.1f}cm"
@width.setter
def width(self, new_width):
if new_width > 0:
self._width = new_width
else:
print("幅は0より大きくする必要があります")
@height.setter
def height(self, new_height):
if new_height > 0:
self._height = new_height
else:
print("高さは0より大きくする必要があります")
rectangle = Rectangle(3, 4)
rectangle.width = 5
rectangle.height = 6
print(rectangle.width)
print(rectangle.height)
# 5.0cm
# 6.0cm
class Rectangle:
def __init__(self, width, height):
self._width = width
self._height = height
@property
def width(self):
return f"{self._width:.1f}cm"
@property
def height(self):
return f"{self._height:.1f}cm"
@width.setter
def width(self, new_width):
if new_width > 0:
self._width = new_width
else:
print("幅は0より大きくする必要があります")
@height.setter
def height(self, new_height):
if new_height > 0:
self._height = new_height
else:
print("高さは0より大きくする必要があります")
@width.deleter
def width(self):
del self._width
print("幅が削除されました")
@height.deleter
def height(self):
del self._height
print("高さが削除されました")
rectangle = Rectangle(3, 4)
rectangle.width = 5
rectangle.height = 6
del rectangle.width
del rectangle.height
# 幅が削除されました
# 高さが削除されました
56. デコレータ 🎊
デコレータ = 別の関数の振る舞いを拡張する関数
基本関数を変更せずに
基本関数をデコレータに引数として渡す
@add_sprinkles
get_ice_cream(“vanilla”)
def get_ice_cream():
print("こちらはあなたのアイスクリームです 🍨")
get_ice_cream()
# こちらはあなたのアイスクリームです 🍨
def add_sprinkles(func):
def wrapper():
func() # print("こちらはあなたのアイスクリームです 🍨")
return wrapper
@add_sprinkles
def get_ice_cream():
print("こちらはあなたのアイスクリームです 🍨")
get_ice_cream()
# こちらはあなたのアイスクリームです 🍨
def add_sprinkles(func):
def wrapper():
print("*スプリンクルを追加しました 🎊*")
func()
return wrapper
@add_sprinkles
def get_ice_cream():
print("こちらはあなたのアイスクリームです 🍨")
get_ice_cream()
# *スプリンクルを追加しました 🎊*
# こちらはあなたのアイスクリームです 🍨
def add_sprinkles(func):
print("*スプリンクルを追加しました 🎊*")
func()
@add_sprinkles
def get_ice_cream():
print("こちらはあなたのアイスクリームです 🍨")
# *スプリンクルを追加しました 🎊*
# こちらはあなたのアイスクリームです 🍨
def add_sprinkles(func):
def wrapper():
print("*スプリンクルを追加しました 🎊*")
func()
return wrapper
def add_fudge(func):
def wrapper():
print("*ファッジを追加しました 🍫*")
func()
return wrapper
@add_sprinkles
@add_fudge
def get_ice_cream():
print("こちらはあなたのアイスクリームです 🍨")
get_ice_cream()
# *スプリンクルを追加しました 🎊*
# *ファッジを追加しました 🍫*
# こちらはあなたのアイスクリームです 🍨
def add_sprinkles(func):
def wrapper():
print("*スプリンクルを追加しました 🎊*")
func()
return wrapper
def add_fudge(func):
def wrapper():
print("*ファッジを追加しました 🍫*")
func()
return wrapper
@add_sprinkles
@add_fudge
def get_ice_cream(flavo):
print(f"こちらはあなたの{flavo}アイスクリームです 🍨")
get_ice_cream("vanilla")
# TypeError: add_sprinkles.<locals>.wrapper() takes 0 positional arguments but 1 was given
def add_sprinkles(func):
def wrapper(*args, **kwargs):
print("*スプリンクルを追加しました 🎊*")
func(*args, **kwargs)
return wrapper
def add_fudge(func):
def wrapper(*args, **kwargs):
print("*ファッジを追加しました 🍫*")
func(*args, **kwargs)
return wrapper
@add_sprinkles
@add_fudge
def get_ice_cream(flavo):
print(f"こちらはあなたの{flavo}アイスクリームです 🍨")
get_ice_cream("vanilla")
# *スプリンクルを追加しました 🎊*
# *ファッジを追加しました 🍫*
# こちらはあなたのvanillaアイスクリームです 🍨
57. 例外処理 🚦
例外 = プログラムの流れを中断するイベント
(例:ZeroDivisionError、TypeError、ValueError)
1. try、2. except、3. finally
1 / 0
# ZeroDivisionError: division by zero
1 + "1"
# TypeError: unsupported operand type(s) for +: 'int' and 'str'
int("pizza")
# ValueError: invalid literal for int() with base 10: 'pizza'
try:
# コードを試す
except Exception:
# 例外を処理する
finally:
# 後処理を行う
number = int(input("数を入力してください: "))
print(1 / number)
# 数を入力してください: 0
# ZeroDivisionError: division by zero
# 数を入力してください: pizza
# ValueError: invalid literal for int() with base 10: 'pizza'
try:
number = int(input("数を入力してください: "))
print(1 / number)
except ZeroDivisionError:
print("0で割ることはできません!")
except ValueError:
print("数字だけを入力してください!")
# 数を入力してください: 0
# 0で割ることはできません!
# 数を入力してください: pizza
# 数字だけを入力してください!
try:
number = int(input("数を入力してください: "))
print(1 / number)
except ZeroDivisionError:
print("0で割ることはできません!")
except ValueError:
print("数字だけを入力してください!")
except Exception: # 広すぎる例外処理
print("何か問題が発生しました!")
finally:
print("後処理を行います")
# 数を入力してください: 0
# 0で割ることはできません!
# 後処理を行います
# 数を入力してください: 1
# 1.0
# 後処理を行います
例外にはさまざまな種類があります。詳細なリストは公式Pythonドキュメントを参照してください。これでPythonの例外処理についての説明は終わりです!
58. ファイル検出 🕵️♂️
<!-- test.txt -->
like pizza
# main.py
import os
file_path = "test.txt"
if os.path.exists(file_path):
print(f"'{file_path}' の場所は存在します")
else:
print("その場所は存在しません")
# 'test.txt' の場所は存在します
# main.py
import os
file_path = "test.txt"
if os.path.exists(file_path):
print(f"'{file_path}' の場所は存在します")
if os.path.isfile(file_path):
print("それはファイルです")
elif os.path.isdir(file_path):
print("それはディレクトリです")
else:
print("その場所は存在しません")
# 'test.txt' の場所は存在します
# それはファイルです
59. ファイルの書き込み ✍
Pythonでのファイル書き込み(.txt、.json、.csv)
txt_data = "I like pizza!"
file_path = "output.txt"
with open(file_path, "w") as file:
file.write(txt_data)
print(f"テキストファイル '{file_path}' が作成されました")
# テキストファイル 'output.txt' が作成されました
# <!-- output.txt -->
# I like pizza!
txt_data = "I like pizza!"
file_path = "output.txt"
try:
with open(file_path, "x") as file:
file.write(txt_data)
print(f"テキストファイル '{file_path}' が作成されました")
except FileExistsError:
print("そのファイルは既に存在します!")
# そのファイルは既に存在します!
<!-- output.txt -->
I like pizza!
txt_data = "I like pizza!"
file_path = "output.txt"
try:
with open(file_path, "a") as file:
file.write(txt_data)
print(f"テキストファイル '{file_path}' が作成されました")
except FileExistsError:
print("そのファイルは既に存在します!")
# テキストファイル 'output.txt' が作成されました
# <!-- output.txt -->
# I like pizza!I like pizza!
<!-- output.txt -->
I like pizza!I like pizza!
txt_data = "I like pizza!"
file_path = "output.txt"
try:
with open(file_path, "a") as file:
file.write(txt_data)
print(f"テキストファイル '{file_path}' が作成されました")
except FileExistsError:
print("そのファイルは既に存在します!")
# テキストファイル 'output.txt' が作成されました
# <!-- output.txt -->
# I like pizza!
<!-- output.txt -->
I like pizza!
txt_data = "I like pizza!"
file_path = "output.txt"
try:
with open(file_path, "a") as file:
file.write("\n" + txt_data)
print(f"テキストファイル '{file_path}' が作成されました")
except FileExistsError:
print("そのファイルは既に存在します!")
# テキストファイル 'output.txt' が作成されました
# <!-- output.txt -->
# I like pizza!
# I like pizza!
employees = ["Eugene", "Squidward", "Spongebob", "Patrick"]
file_path = "output.txt"
try:
with open(file_path, "w") as file:
file.write(employees)
print(f"テキストファイル '{file_path}' が作成されました")
except FileExistsError:
print("そのファイルは既に存在します!")
# TypeError: write() 引数は文字列でなければなりません。リストは不可です。
employees = ["Eugene", "Squidward", "Spongebob", "Patrick"]
file_path = "output.txt"
try:
with open(file_path, "w") as file:
for employee in employees:
file.write(employee)
print(f"テキストファイル '{file_path}' が作成されました")
except FileExistsError:
print("そのファイルは既に存在します!")
# テキストファイル 'output.txt' が作成されました
# <!-- output.txt -->
# EugeneSquidwardSpongebobPatrick
employees = ["Eugene", "Squidward", "Spongebob", "Patrick"]
file_path = "output.txt"
try:
with open(file_path, "w") as file:
for employee in employees:
file.write(employee + "\n")
print(f"テキストファイル '{file_path}' が作成されました")
except FileExistsError:
print("そのファイルは既に存在します!")
# テキストファイル 'output.txt' が作成されました
# <!-- output.txt -->
# Eugene
# Squidward
# Spongebob
# Patrick
import json
employee = {
"name": "Spongebob",
"age": 30,
"job": "cook"
}
file_path = "output.json"
try:
with open(file_path, "w") as file:
json.dump(employee, file)
print(f"JSONファイル '{file_path}' が作成されました")
except FileExistsError:
print("そのファイルは既に存在します!")
# JSONファイル 'output.json' が作成されました
# <!-- output.json -->
# {"name": "Spongebob", "age": 30, "job": "cook"}
import json
employee = {
"name": "Spongebob",
"age": 30,
"job": "cook"
}
file_path = "output.json"
try:
with open(file_path, "w") as file:
json.dump(employee, file, indent=4)
print(f"JSONファイル '{file_path}' が作成されました")
except FileExistsError:
print("そのファイルは既に存在します!")
# JSONファイル 'output.json' が作成されました
# <!-- output.json -->
# {
# "name": "Spongebob",
# "age": 30,
# "job": "cook"
# }
import json
import csv
employees = [["Name", "Age", "Job"],
["Spongebob", 30, "Cook"],
["Patrick", 37, "Unemployed"],
["Sandy", 27, "Scientist"]]
file_path = "output.csv"
try:
with open(file_path, "w") as file:
writer = csv.writer(file)
for row in employees:
writer.writerow(row)
print(f"CSVファイル '{file_path}' が作成されました")
except FileExistsError:
print("そのファイルは既に存在します!")
# CSVファイル 'output.csv' が作成されました
# <!-- output.csv -->
# Name,Age,Job
#
# Spongebob,30,Cook
#
# Patrick,37,Unemployed
#
# Sandy,27,Scientist
import json
import csv
employees = [["Name", "Age", "Job"],
["Spongebob", 30, "Cook"],
["Patrick", 37, "Unemployed"],
["Sandy", 27, "Scientist"]]
file_path = "output.csv"
try:
with open(file_path, "w", newline="") as file:
writer = csv.writer(file)
for row in employees:
writer.writerow(row)
print(f"CSVファイル '{file_path}' が作成されました")
except FileExistsError:
print("そのファイルは既に存在します!")
# CSVファイル 'output.csv' が作成されました
# <!-- output.csv -->
# Name,Age,Job
# Spongebob,30,Cook
# Patrick,37,Unemployed
# Sandy,27,Scientist
60. ファイルの読み込み 🔍
Pythonでのファイル読み込み(.txt、.json、csv)
<!-- input.txt -->
ピザが好き!
本当に美味しい!
// input.json
{
"name": "スポンジ・ボブ",
"age": 30,
"job": "シェフ"
}
<!-- input.csv -->
名前,年齢,職業
スポンジ・ボブ,30,シェフ
パトリック,37,無職
サンディ,27,科学者
file_path = "input.txt"
with open(file_path, "r") as file:
content = file.read()
print(content)
# ピザが好き!
# 本当に美味しい!
with
文は、コンテキストマネージャによって定義されたメソッドでブロックの実行をラップするために使用されます(「With文のコンテキストマネージャ」のセクションを参照)。これにより、一般的なtry...except...finally
の使用パターンをカプセル化し、便利に再利用できます。
import json
file_path = "input.json"
try:
with open(file_path, "r") as file:
content = json.load(file)
print(content)
print(content["name"])
except FileNotFoundError:
print("ファイルが見つかりませんでした")
except PermissionError:
print("そのファイルを読む権限がありません")
# {"name": "スポンジ・ボブ", "age": 30, "job": "シェフ"}
# スポンジ・ボブ
import csv
file_path = "input.csv"
try:
with open(file_path, "r") as file:
content = csv.reader(file)
print(content)
except FileNotFoundError:
print("ファイルが見つかりませんでした")
except PermissionError:
print("そのファイルを読む権限がありません")
# <_csv.reader object at 0x0000017D81C4EAA0>
import csv
file_path = "input.csv"
try:
with open(file_path, "r") as file:
content = csv.reader(file)
for line in content:
print(line)
except FileNotFoundError:
print("ファイルが見つかりませんでした")
except PermissionError:
print("そのファイルを読む権限がありません")
# ['名前', '年齢', '職業']
# ['スポンジ・ボブ', '30', 'シェフ']
# ['パトリック', '37', '無職']
# ['サンディ', '27', '科学者']
import csv
file_path = "input.csv"
try:
with open(file_path, "r") as file:
content = csv.reader(file)
for line in content:
print(line[0])
except FileNotFoundError:
print("ファイルが見つかりませんでした")
except PermissionError:
print("そのファイルを読む権限がありません")
# 名前
# スポンジ・ボブ
# パトリック
# サンディ
61. 日付と時刻 📅
import datetime
date = datetime.date(2025, 1, 2)
print(date)
# 2025-01-02
today = datetime.date.today()
print(today)
# 2025-05-02
time = datetime.time(12, 30, 0)
print(time)
# 12:30:00
now = datetime.datetime.now()
print(now)
# 2025-05-02 09:41:55.409676
now = now.strftime("%H %M %S")
print(now)
# 09 41 55
now = now.strftime("%H:%M:%S")
print(now)
# 09:41:55
now = now.strftime("%H:%M:%S %m-%d-%Y")
print(now)
# 09:41:55 05-02-2025
ディレクティブ | 意味 | 例 | 備考 |
---|---|---|---|
%a |
ロケールに基づく曜日の短縮名。 | Sun, Mon, …, Sat (en_US); 日, 月, …, 土 (ja_JP) |
(1) |
%A |
ロケールに基づく曜日の完全名。 | Sunday, Monday, …, Saturday (en_US); 日曜日, 月曜日, …, 土曜日 (ja_JP) |
(1) |
%w |
曜日を10進数で表記(0が日曜日、6が土曜日)。 | 0, 1, …, 6 | |
%d |
月の日をゼロ埋めした10進数で表記。 | 01, 02, …, 31 | (9) |
%b |
ロケールに基づく月の短縮名。 | Jan, Feb, …, Dec (en_US); 1月, 2月, …, 12月 (ja_JP) |
(1) |
%B |
ロケールに基づく月の完全名。 | January, February, …, December (en_US); 1月, 2月, …, 12月 (ja_JP) |
(1) |
%m |
月をゼロ埋めした10進数で表記。 | 01, 02, …, 12 | (9) |
%y |
世紀なしの年をゼロ埋めした10進数で表記。 | 00, 01, …, 99 | (9) |
%Y |
世紀を含む年を10進数で表記。 | 0001, 0002, …, 2013, 2014, …, 9998, 9999 | (2) |
strftime
で使用できるフォーマットコードは他にも多く存在します。詳細なリストと説明は Python strftime ドキュメント を参照してください。
import datetime
date = datetime.date(2025, 1, 2)
today = datetime.date.today()
time = datetime.time(12, 30, 0)
now = datetime.datetime.now()
now = now.strftime("%H:%M:%S %m-%d-%Y")
target_datetime = datetime.datetime(2030, 1, 2, 12, 12, 30, 1)
current_datetime = datetime.datetime.now()
if target_datetime < current_datetime:
print("目標日時を過ぎています")
else:
print("目標日時はまだ過ぎていません")
# 目標日時はまだ過ぎていません
62. ⭐ アラームクロック ⏰
# Python アラームクロック
import time
import datetime
import pygame # pip install pygame
def set_alarm(alarm_time): # 例: "23:00:00"
pass
if __name__ == '__main__':
alarm_time = input("アラーム時刻を入力してください (HH:MM:SS): ")
set_alarm(alarm_time)
# Python アラームクロック
import time
import datetime
import pygame
def set_alarm(alarm_time):
print(f"アラームを {alarm_time} に設定しました")
sound_file = "my_music.mp3"
if __name__ == '__main__':
alarm_time = input("アラーム時刻を入力してください (HH:MM:SS): ")
set_alarm(alarm_time)
# pygame 2.6.0 (SDL 2.28.4, Python 3.12.5)
# pygameコミュニティからのご挨拶。 https://www.pygame.org/contribute.html
👆"この機能の実装は、pygameライブラリの初期化ファイル(/.venv/Lib/site-packages/pygame/__init__.py 338-342行目)に記載されています。"
# アラーム時刻を入力してください (HH:MM:SS): 09:00:00
# アラームを 09:00:00 に設定しました
# Python アラームクロック
import time
import datetime
import pygame
def set_alarm(alarm_time):
print(f"アラームを {alarm_time} に設定しました")
sound_file = "my_music.mp3"
is_running = True
while is_running:
current_datetime = datetime.datetime.now().strftime("%H:%M:%S")
print(current_datetime)
is_running = False
if __name__ == '__main__':
alarm_time = input("アラーム時刻を入力してください (HH:MM:SS): ")
set_alarm(alarm_time)
# アラーム時刻を入力してください (HH:MM:SS): 10:00:00
# アラームを 10:00:00 に設定しました
# 09:42:16
# Python アラームクロック
import time
import datetime
import pygame
def set_alarm(alarm_time):
print(f"アラームを {alarm_time} に設定しました")
sound_file = "my_music.mp3"
is_running = True
while is_running:
current_datetime = datetime.datetime.now().strftime("%H:%M:%S")
print(current_datetime)
time.sleep(1)
if __name__ == '__main__':
alarm_time = input("アラーム時刻を入力してください (HH:MM:SS): ")
set_alarm(alarm_time)
# アラーム時刻を入力してください (HH:MM:SS): 10:00:00
# アラームを 10:00:00 に設定しました
# 09:42:16
# 09:42:17
# 09:42:18
# ...
# Python アラームクロック
import time
import datetime
import pygame
def set_alarm(alarm_time):
print(f"アラームを {alarm_time} に設定しました")
sound_file = "my_music.mp3"
is_running = True
while is_running:
current_datetime = datetime.datetime.now().strftime("%H:%M:%S")
print(current_datetime)
if current_datetime == alarm_time:
print("起きて! ")
is_running = False
time.sleep(1)
if __name__ == '__main__':
alarm_time = input("アラーム時刻を入力してください (HH:MM:SS): ")
set_alarm(alarm_time)
# アラーム時刻を入力してください (HH:MM:SS): 09:45:00
# アラームを 09:45:00 に設定しました
# ...
# 09:44:58
# 09:44:59
# 09:45:00
# 起きて!
# プロセスが終了コード0で終了しました
# Python アラームクロック
import time
import datetime
import pygame
def set_alarm(alarm_time):
print(f"アラームを {alarm_time} に設定しました")
sound_file = "my_music.mp3"
is_running = True
while is_running:
current_datetime = datetime.datetime.now().strftime("%H:%M:%S")
print(current_datetime)
if current_datetime == alarm_time:
print("起きて! ")
pygame.mixer.init()
pygame.mixer.music.load(sound_file)
pygame.mixer.music.play()
is_running = False
time.sleep(1)
if __name__ == '__main__':
alarm_time = input("アラーム時刻を入力してください (HH:MM:SS): ")
set_alarm(alarm_time)
# アラーム時刻を入力してください (HH:MM:SS): 09:45:00
# アラームを 09:45:00 に設定しました
# ...
# 09:44:58
# 09:44:59
# 09:45:00
# 起きて!
# プロセスが終了コード0で終了しました
モジュール pygame.mixer
: サウンドの読み込みと再生のためのpygameモジュール
# pygame.mixer
def init(frequency: int = 44100,
size: int = -16,
channels: int = 2,
buffer: int = 512,
devicename: str | None = None,
allowedchanges: int = 5) -> None
# Python アラームクロック
import time
import datetime
import pygame
def set_alarm(alarm_time):
print(f"アラームを {alarm_time} に設定しました")
sound_file = "my_music.mp3"
is_running = True
while is_running:
current_datetime = datetime.datetime.now().strftime("%H:%M:%S")
print(current_datetime)
if current_datetime == alarm_time:
print("起きて! ")
pygame.mixer.init()
pygame.mixer.music.load(sound_file)
pygame.mixer.music.play()
while pygame.mixer.music.get_busy():
time.sleep(1)
is_running = False
time.sleep(1)
if __name__ == '__main__':
alarm_time = input("アラーム時刻を入力してください (HH:MM:SS): ")
set_alarm(alarm_time)
# アラーム時刻を入力してください (HH:MM:SS): 09:45:00
# アラームを 09:45:00 に設定しました
# ...
# 09:44:58
# 09:44:59
# 09:45:00
# 起きて!
👆これがPythonでアラームクロックを作成する方法です。
63. マルチスレッド 🧵
マルチスレッド = 複数のタスクを同時に実行するために使用される(マルチスレッド)
ファイルの読み込みやAPIからのデータ取得などのI/Oバウンドタスクに適している
threading.Thread(target=my_function)
import threading
import time
def walk_dog():
time.sleep(8)
print("犬の散歩が終わりました")
def take_out_trash():
time.sleep(2)
print("ゴミを出しました")
def get_mail():
time.sleep(4)
print("郵便を受け取りました")
walk_dog()
take_out_trash()
get_mail()
# 犬の散歩が終わりました
# ゴミを出しました
# 郵便を受け取りました
import threading
import time
def walk_dog():
time.sleep(8)
print("犬の散歩が終わりました")
def take_out_trash():
time.sleep(2)
print("ゴミを出しました")
def get_mail():
time.sleep(4)
print("郵便を受け取りました")
chore1 = threading.Thread(target=walk_dog)
chore1.start()
chore2 = threading.Thread(target=take_out_trash)
chore2.start()
chore3 = threading.Thread(target=get_mail)
chore3.start()
print("すべての家事が完了しました!")
# すべての家事が完了しました!
# ゴミを出しました
# 郵便を受け取りました
# 犬の散歩が終わりました
import threading
import time
def walk_dog():
time.sleep(8)
print("犬の散歩が終わりました")
def take_out_trash():
time.sleep(2)
print("ゴミを出しました")
def get_mail():
time.sleep(4)
print("郵便を受け取りました")
chore1 = threading.Thread(target=walk_dog)
chore1.start()
chore2 = threading.Thread(target=take_out_trash)
chore2.start()
chore3 = threading.Thread(target=get_mail)
chore3.start()
print("すべての家事が完了しました!")
chore1.join()
chore2.join()
chore3.join()
# ゴミを出しました
# 郵便を受け取りました
# 犬の散歩が終わりました
# すべての家事が完了しました!
import threading
import time
def walk_dog(first):
time.sleep(8)
print(f"{first}の散歩が終わりました")
def take_out_trash():
time.sleep(2)
print("ゴミを出しました")
def get_mail():
time.sleep(4)
print("郵便を受け取りました")
# 括弧で囲まれた文字列として解釈される
chore1 = threading.Thread(target=walk_dog, args=("Scooby",))
chore1.start()
chore2 = threading.Thread(target=take_out_trash)
chore2.start()
chore3 = threading.Thread(target=get_mail)
chore3.start()
print("すべての家事が完了しました!")
chore1.join()
chore2.join()
chore3.join()
# ゴミを出しました
# 郵便を受け取りました
# Scoobyの散歩が終わりました
# すべての家事が完了しました!
import threading
import time
def walk_dog(first):
time.sleep(8)
print(f"{first}の散歩が終わりました")
def take_out_trash():
time.sleep(2)
print("ゴミを出しました")
def get_mail():
time.sleep(4)
print("郵便を受け取りました")
# 括弧で囲まれた文字列として解釈される
chore1 = threading.Thread(target=walk_dog, args=("Scooby"))
chore1.start()
chore2 = threading.Thread(target=take_out_trash)
chore2.start()
chore3 = threading.Thread(target=get_mail)
chore3.start()
print("すべての家事が完了しました!")
chore1.join()
chore2.join()
chore3.join()
# TypeError: walk_dog() takes 1 positional argument but 6 were given
# ゴミを出しました
# 郵便を受け取りました
# Scoobyの散歩が終わりました
# すべての家事が完了しました!
import threading
import time
def walk_dog(first, last):
time.sleep(8)
print(f"{first} {last}の散歩が終わりました")
def take_out_trash():
time.sleep(2)
print("ゴミを出しました")
def get_mail():
time.sleep(4)
print("郵便を受け取りました")
# 括弧で囲まれた文字列として解釈される
chore1 = threading.Thread(target=walk_dog, args=("Scooby", "Doo"))
chore1.start()
chore2 = threading.Thread(target=take_out_trash)
chore2.start()
chore3 = threading.Thread(target=get_mail)
chore3.start()
print("すべての家事が完了しました!")
chore1.join()
chore2.join()
chore3.join()
# ゴミを出しました
# 郵便を受け取りました
# Scooby Dooの散歩が終わりました
# すべての家事が完了しました!
64. APIデータの取得 ↩️
PokéAPI
例: https://pokeapi.co/api/v2/pokemon/pikachu
# PythonでAPIに接続する方法
import requests # pip install requests
base_url = "https://pokeapi.co/api/v2/"
def get_pokemon_info(name):
pass
pokemon_name = "pikachu"
get_pokemon_info(pokemon_name)
import requests
base_url = "https://pokeapi.co/api/v2/"
def get_pokemon_info(name):
url = f"{base_url}/pokemon/{name}"
response = requests.get(url)
print(response)
pokemon_name = "pikachu"
get_pokemon_info(pokemon_name)
# <Response [200]>
import requests
base_url = "https://pokeapi.co/api/v2/"
def get_pokemon_info(name):
url = f"{base_url}/pokemon/{name}"
response = requests.get(url)
if response.status_code == 200:
print("データ取得成功!")
else:
print(f"データ取得失敗 {response.status_code}")
pokemon_name = "pikachu"
get_pokemon_info(pokemon_name)
# データ取得成功!
import requests
base_url = "https://pokeapi.co/api/v2/"
def get_pokemon_info(name):
url = f"{base_url}/pokemon/{name}"
response = requests.get(url)
if response.status_code == 200:
pokemon_data = response.json()
print(pokemon_data)
else:
print(f"データ取得失敗 {response.status_code}")
pokemon_name = "pikachu"
get_pokemon_info(pokemon_name)
# {
# "abilities": [
# {
# "ability": {
# "name": "static",
# "url": "https://pokeapi.co/api/v2/ability/9/"
# },
# "is_hidden": false,
# "slot": 1
# },
# {
# "ability": {
# "name": "lightning-rod",
# "url": "https://pokeapi.co/api/v2/ability/31/"
# },
# "is_hidden": true,
# "slot": 3
# }
# ],
# "base_experience": 112,
# "height": 4,
# "id": 25,
# "name": "pikachu",
# "types": [
# {
# "slot": 1,
# "type": {
# "name": "electric",
# "url": "https://pokeapi.co/api/v2/type/13/"
# }
# }
# ],
# "weight": 60
# }
import requests
base_url = "https://pokeapi.co/api/v2/"
def get_pokemon_info(name):
url = f"{base_url}/pokemon/{name}"
response = requests.get(url)
if response.status_code == 200:
pokemon_data = response.json()
return pokemon_data
else:
print(f"データ取得失敗 {response.status_code}")
pokemon_name = "pikachu"
pokemon_info = get_pokemon_info(pokemon_name)
if pokemon_info:
print(f"名前: {pokemon_info['name'].capitalize()}")
print(f"ID: {pokemon_info['id']}")
print(f"高さ: {pokemon_info['height']}")
print(f"重さ: {pokemon_info['weight']}")
# 名前: Pikachu
# ID: 25
# 高さ: 4
# 重さ: 60
65. PyQt5 GUI 入門 🖥️
グラフィカルユーザーインターフェース
# PyQt5 入門
import sys
# pip install PyQt5
from PyQt5.QtWidgets import QApplication, QMainWindow
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
def main():
pass
if __name__ == '__main__':
main()
sys
— システム固有のパラメータと関数
このモジュールは、インタプリタが使用または管理するいくつかの変数や、インタプリタと強く相互作用する関数へのアクセスを提供します。このモジュールは常に利用可能です。
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
def main():
app = QApplication(sys.argv)
window = MainWindow()
window.show()
if __name__ == '__main__':
main()
#
# プロセスが終了コード0で終了しました
sys.argv
Pythonスクリプトに渡されるコマンドライン引数のリスト。argv[0]
はスクリプト名です(これが完全なパス名かどうかはオペレーティングシステムに依存します)。コマンドがインタプリタの-c
コマンドラインオプションを使用して実行された場合、argv[0]
は文字列'-c'
に設定されます。Pythonインタプリタにスクリプト名が渡されなかった場合、argv[0]
は空の文字列になります。
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtGui import QIcon
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("私のクールな最初のGUI")
self.setGeometry(700, 300, 500, 500)
# self.setGeometry(x, y, 幅, 高さ)
self.setWindowIcon(QIcon("profile_pic.jpg"))
def main():
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
66. PyQt5 ラベル 🏷️
# PyQt5 QLabel
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setGeometry(700, 300, 500, 500)
label = QLabel("こんにちは", self) # (ウィンドウが親ウィジェットになります)
def main():
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel
from PyQt5.QtGui import QFont
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setGeometry(700, 300, 500, 500)
label = QLabel("こんにちは", self)
label.setFont(QFont("Arial", 40))
label.setGeometry(0, 0, 500, 100)
label.setStyleSheet("color: #1fff5a;"
"background-color: #6fdcf7;"
"font-weight: bold;"
"font-style: italic;"
"text-decoration: underline;") # Googleで「カラー ピッカー」を検索
def main():
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel
from PyQt5.QtGui import QFont
from PyQt5.QtCore import Qt
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setGeometry(700, 300, 500, 500)
label = QLabel("こんにちは", self)
label.setFont(QFont("Arial", 40))
label.setGeometry(0, 0, 500, 100)
label.setStyleSheet("color: #1fff5a;"
"background-color: #6fdcf7;"
"font-weight: bold;"
"font-style: italic;"
"text-decoration: underline;")
# label.setAlignment(Qt.AlignTop) # 垂直方向 上
# label.setAlignment(Qt.AlignBottom) # 垂直方向 下
# label.setAlignment(Qt.AlignVCenter) # 垂直方向 中央
# label.setAlignment(Qt.AlignRight) # 水平方向 右
# label.setAlignment(Qt.AlignHCenter) # 水平方向 中央
# label.setAlignment(Qt.AlignLeft) # 水平方向 左
# label.setAlignment(Qt.AlignHCenter | Qt.AlignTop) # 中央 & 上
# label.setAlignment(Qt.AlignHCenter | Qt.AlignBottom) # 中央 & 下
# label.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter) # 中央 & 中央
label.setAlignment(Qt.AlignCenter) # 中央 & 中央
def main():
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
67. PyQt5 画像 📷
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setGeometry(700, 300, 500, 500)
def main():
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel
from PyQt5.QtGui import QPixmap
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setGeometry(700, 300, 500, 500)
label = QLabel(self)
label.setGeometry(0, 0, 250, 250)
# label.setGeometry(x, y, 幅, 高さ)
pixmap = QPixmap("profile_pic.jpg")
label.setPixmap(pixmap)
def main():
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel
from PyQt5.QtGui import QPixmap
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setGeometry(700, 300, 500, 500)
label = QLabel(self)
label.setGeometry(0, 0, 250, 250)
# label.setGeometry(x, y, 幅, 高さ)
pixmap = QPixmap("profile_pic.jpg")
label.setPixmap(pixmap)
label.setScaledContents(True)
label.setGeometry((self.width() - label.width()) // 2,
(self.height() - label.height()) // 2,
label.width(),
label.height())
def main():
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
68. PyQt5 レイアウトマネージャー 🧲
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setGeometry(700, 300, 500, 500)
def main():
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
import sys
from PyQt5.QtWidgets import (QApplication, QMainWindow, QLabel,
QWidget, QVBoxLayout, QHBoxLayout, QGridLayout)
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setGeometry(700, 300, 500, 500)
self.initUI()
def initUI(self):
central_widget = QWidget()
self.setCentralWidget(central_widget)
label1 = QLabel("#1", self)
label2 = QLabel("#2", self)
label3 = QLabel("#3", self)
label4 = QLabel("#4", self)
label5 = QLabel("#5", self)
label1.setStyleSheet("background-color: red;")
label2.setStyleSheet("background-color: yellow;")
label3.setStyleSheet("background-color: green;")
label4.setStyleSheet("background-color: blue;")
label5.setStyleSheet("background-color: purple;")
# vbox = QVBoxLayout()
# vbox.addWidget(label1)
# vbox.addWidget(label2)
# vbox.addWidget(label3)
# vbox.addWidget(label4)
# vbox.addWidget(label5)
# central_widget.setLayout(vbox)
# hbox = QHBoxLayout()
# hbox.addWidget(label1)
# hbox.addWidget(label2)
# hbox.addWidget(label3)
# hbox.addWidget(label4)
# hbox.addWidget(label5)
# central_widget.setLayout(hbox)
grid = QGridLayout()
grid.addWidget(label1, 0, 0)
grid.addWidget(label2, 0, 1)
grid.addWidget(label3, 1, 0)
grid.addWidget(label4, 1, 1)
grid.addWidget(label5, 2, 2)
central_widget.setLayout(grid)
def main():
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
69. PyQt5 ボタン 🛎️
import sys
from PyQt5.QtWidgets import QMainWindow, QApplication
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setGeometry(700, 300, 500, 500)
self.initUI()
def initUI(self):
pass
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QPushButton, QLabel
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setGeometry(700, 300, 500, 500)
self.button = QPushButton("クリックしてください!", self)
self.initUI()
def initUI(self):
self.button.setGeometry(150, 200, 200, 100)
self.button.setStyleSheet("font-size: 30px;")
self.button.clicked.connect(self.on_click)
def on_click(self):
print("ボタンがクリックされました!")
self.button.setText("クリック済み!")
self.button.setDisabled(True)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QPushButton, QLabel
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setGeometry(700, 300, 500, 500)
self.button = QPushButton("クリックしてください!", self)
self.label = QLabel("こんにちは", self)
self.initUI()
def initUI(self):
self.button.setGeometry(150, 200, 200, 100)
self.button.setStyleSheet("font-size: 30px;")
self.button.clicked.connect(self.on_click)
self.label.setGeometry(150, 300, 200, 100)
self.label.setStyleSheet("font-size: 50px;")
def on_click(self):
self.label.setText("さようなら")
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())