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
# 勝利!