
This course includes our updated coding exercises so you can practice your skills as you learn.
See a demo
このレクチャーで書いたプログラムです(書いた順)。コピーして手元で動かせます。
プログラム 1(main.py)
# 変数と代入
score = 80
name = 'Guest'
rate = 0.5
print(type(score))
print(type(name))
print(type(rate))
プログラム 2(main.py)
# 変数と代入
score = 80
print(score)
score = 95
print(score)
score += 5
print(score)
プログラム 3(main.py)
# 変数と代入
price = 120
count = 3
total = price * count
print(total)
tax_rate = 1.1
payment = round(total * tax_rate)
print(payment)
プログラム 4(main.py)
# 変数と代入
items = ['apple', 'banana']
linked = items
copied = items.copy()
items.append('melon')
print(items)
print(linked)
print(copied)
プログラム 5(main.py)
# 変数と代入
left, right = 'A', 'B'
left, right = right, left
print(left)
print(right)
プログラム 6(main.py)
# 変数と代入
item = 'note'
price = 150
count = 4
subtotal = price * count
tax_rate = 1.1
total = round(subtotal * tax_rate)
print(f'{item} x {count}')
print(f'subtotal: {subtotal}')
print(f'total: {total}')
このレクチャーで書いたプログラムです(書いた順)。コピーして手元で動かせます。
プログラム 1(main.py)
# 数値と算術演算子
apples = 12
boxes = 5
print(apples + boxes)
print(apples - boxes)
print(apples * boxes)
print(apples / boxes)
print(10 / 5)
プログラム 2(main.py)
# 数値と算術演算子
candies = 17
per_bag = 5
print(candies // per_bag)
print(candies % per_bag)
プログラム 3(main.py)
# 数値と算術演算子
print(7 // 2)
print(-7 // 2)
print(-7 % 2)
プログラム 4(main.py)
# 数値と算術演算子
print(2 ** 10)
print(9 ** 0.5)
print(2 ** 100)
population = 1_000_000
print(population * 3)
プログラム 5(main.py)
# 数値と算術演算子
print(2 + 3 * 4)
print((2 + 3) * 4)
print(20 - 8 / 2)
プログラム 6(main.py)
# 数値と算術演算子
print(2 ** 3 ** 2)
print(-2 ** 2)
print((-2) ** 2)
プログラム 7(main.py)
# 数値と算術演算子
print(3 + 2.0)
print(4 * 2.5)
print(7 // 2.0)
プログラム 8(main.py)
# 数値と算術演算子
print(0.1 + 0.2)
print(0.5 + 0.25)
プログラム 9(main.py)
# 数値と算術演算子
total = 0.1 + 0.2
print(round(total, 2))
print(round(2.5))
print(round(3.5))
プログラム 10(main.py)
# 数値と算術演算子
items = 10
people = 0
print(items / people)
プログラム 11(main.py)
# 数値と算術演算子
price = 480
count = 3
subtotal = price * count
tax = subtotal * 10 // 100
total = subtotal + tax
print(subtotal)
print(tax)
print(total)
people = 5
print(total // people)
print(total % people)
プログラム 12(main.py)
# 数値と算術演算子
total_seconds = 4000
hours = total_seconds // 3600
rest = total_seconds % 3600
minutes = rest // 60
seconds = rest % 60
print(hours)
print(minutes)
print(seconds)
このレクチャーで書いたプログラムです(書いた順)。コピーして手元で動かせます。
プログラム 1(main.py)
# 文字列の基本とインデックス・スライス
fruit = 'lemon'
juice = fruit + 'ade'
print(fruit)
print(juice)
line = '=' * 8
print(line)
プログラム 2(main.py)
# 文字列の基本とインデックス・スライス
fruit = 'lemon'
print(fruit[0])
print(fruit[1])
print(fruit[4])
print(fruit[-1])
print(fruit[-5])
print(fruit[len(fruit) - 1])
プログラム 3(main.py)
# 文字列の基本とインデックス・スライス
fruit = 'lemon'
print(fruit[1:4])
print(fruit[0:2])
print(fruit[2:5])
print(fruit[:3])
print(fruit[3:])
print(fruit[:3] + fruit[3:])
プログラム 4(main.py)
# 文字列の基本とインデックス・スライス
fruit = 'lemon'
print(fruit[-3:])
print(fruit[1:100])
drink = 'lemonade'
print(drink[::2])
print(drink[::-1])
プログラム 5(main.py)
# 文字列の基本とインデックス・スライス
fruit = 'lemon'
melon = 'm' + fruit[1] + 'l' + fruit[3:]
print(melon)
print(fruit)
プログラム 6(main.py)
# 文字列の基本とインデックス・スライス
date = '2026-09-25'
year = date[:4]
month = date[5:7]
day = date[8:]
file_name = 'photo_2026.png'
ext = file_name[-3:]
base = file_name[:-4]
print(year)
print(month)
print(day)
print(ext)
print(base)
print(day + '/' + month + '/' + year)
このレクチャーで書いたプログラムです(書いた順)。コピーして手元で動かせます。
プログラム 1(main.py)
# 文字列のメソッド(分割・結合・置換)
colors = 'red,green,blue'
parts = colors.split(',')
print(parts)
print(parts[1])
プログラム 2(main.py)
# 文字列のメソッド(分割・結合・置換)
words = 'cat dog bird'
print(words.split())
print(words.split(' '))
プログラム 3(main.py)
# 文字列のメソッド(分割・結合・置換)
note = 'alarm:wake at 6:30'
print(note.split(':'))
print(note.split(':', 1))
プログラム 4(main.py)
# 文字列のメソッド(分割・結合・置換)
steps = 'wash cut boil'.split()
print(steps.join(' '))
プログラム 5(main.py)
# 文字列のメソッド(分割・結合・置換)
memo = 'hot tea and iced tea'
print(memo.replace('tea', 'coffee'))
print(memo.replace('tea', 'milk', 1))
プログラム 6(main.py)
# 文字列のメソッド(分割・結合・置換)
item_id = 'A-100'
item_id = item_id.replace('-', '_')
print(item_id)
print(item_id.replace('_', ''))
プログラム 7(main.py)
# 文字列のメソッド(分割・結合・置換)
messy = 'see you soon'
clean = ' '.join(messy.split())
print(clean)
print('_'.join(messy.split()))
プログラム 8(main.py)
# 文字列のメソッド(分割・結合・置換)
line = 'menu: tea / cake / juice'
label, body = line.split(': ')
items = body.split(' / ')
print(label)
print(', '.join(items))
print(body.replace(' / ', ' | '))
このレクチャーで書いたプログラムです(書いた順)。コピーして手元で動かせます。
プログラム 1(main.py)
# f文字列と書式指定
item = 'coffee'
price = 450
print(f'{item} is {price} yen')
print('{item} is {price} yen')
プログラム 2(main.py)
# f文字列と書式指定
item = 'coffee'
price = 450
count = 3
print(f'{count} cups: {price * count} yen')
print(f'{item} has {len(item)} letters')
print(f'{{count}} is {count}')
プログラム 3(main.py)
# f文字列と書式指定
ratio = 2 / 3
print(f'{ratio}')
print(f'{ratio:.2f}')
print(f'{ratio:.0f}')
プログラム 4(main.py)
# f文字列と書式指定
visitors = 1234567
print(f'{visitors:,}')
print(f'{visitors:_}')
sales = 98765.4321
print(f'{sales:,.2f}')
rate = 7 / 8
print(f'{rate:.1%}')
プログラム 5(main.py)
# f文字列と書式指定
drink = 'tea'
print(f'[{drink:<10}]')
print(f'[{drink:^10}]')
print(f'[{drink:>10}]')
プログラム 6(main.py)
# f文字列と書式指定
drink = 'tea'
score = 450
print(f'[{drink:10}]')
print(f'[{score:10}]')
print(f'[{drink:*^10}]')
number = 7
minutes = 3
seconds = 5
print(f'{number:03}')
print(f'{minutes:02}:{seconds:02}')
プログラム 7(main.py)
# f文字列と書式指定
amount = '450'
print(f'{amount:.2f}')
プログラム 8(main.py)
# f文字列と書式指定
a_name = 'bread'
a_price = 1280
b_name = 'milk'
b_price = 198
total = a_price + b_price
label = 'total'
print(f'{a_name:<8}{a_price:>7,}')
print(f'{b_name:<8}{b_price:>7,}')
print('-' * 15)
print(f'{label:<8}{total:>7,}')
print(f'{a_name} share: {a_price / total:.1%}')
このレクチャーで書いたプログラムです(書いた順)。コピーして手元で動かせます。
プログラム 1(main.py)
# 型変換と input による入力
fruit = input('好きな果物: ')
print(fruit + ' を選びました')
プログラム 2(main.py)
# 型変換と input による入力
cups = input('コーヒーの杯数: ')
count = int(cups)
print(count + 1)
print(type(count))
プログラム 3(main.py)
# 型変換と input による入力
cups = int(input('コーヒーの杯数: '))
price = cups * 450
print(f'合計 {price} 円')
プログラム 4(main.py)
# 型変換と input による入力
km = float(input('走った距離(km): '))
print(km * 1000)
print(int(km))
プログラム 5(main.py)
# 型変換と input による入力
level = int(input('今のレベル: '))
level += 1
message = 'レベル ' + str(level) + ' になりました'
print(message)
プログラム 6(main.py)
# 型変換と input による入力
code = input('会員番号: ')
print(code)
print(int(code))
プログラム 7(main.py)
# 型変換と input による入力
bill = int(input('合計金額: '))
people = int(input('人数: '))
each = bill // people
rest = bill % people
print(f'1人 {each} 円')
print(f'あまり {rest} 円')
このレクチャーで書いたプログラムです(書いた順)。コピーして手元で動かせます。
プログラム 1(main.py)
# print の使いこなし(sep・end・複数の値)
print('apple', 3, 2.5)
item = 'pen'
stock = 12
print('item', item, 'stock', stock)
プログラム 2(main.py)
# print の使いこなし(sep・end・複数の値)
print(2026, 9, 27)
print(2026, 9, 27, sep='-')
print(10, 30, 45, sep=':')
プログラム 3(main.py)
# print の使いこなし(sep・end・複数の値)
print('py', 'thon', sep='')
print('red', 'green', 'blue', sep=', ')
print('red', 'green', 'blue', sep='\n')
プログラム 4(main.py)
# print の使いこなし(sep・end・複数の値)
print('Loading', end='...')
print('done')
print('step1', end=' > ')
print('step2', end=' > ')
print('step3')
プログラム 5(main.py)
# print の使いこなし(sep・end・複数の値)
print('Hello', end='!\n')
print('Next line')
print()
print('Bye')
プログラム 6(main.py)
# print の使いこなし(sep・end・複数の値)
print('A', 'B', 'C', sep='-', end='.\n')
print(1, 2, 3, sep=' + ', end=' = ')
print(1 + 2 + 3)
プログラム 7(main.py)
# print の使いこなし(sep・end・複数の値)
item = 'coffee'
price = 450
count = 2
print('=' * 20)
print('item', item, sep=': ')
print('price', price, sep=': ', end=' yen\n')
print('count', count, sep=': ')
print('total', price * count, sep=': ', end=' yen\n')
print('=' * 20)
プログラム 8(main.py)
# print の使いこなし(sep・end・複数の値)
item = 'coffee'
price = 450
count = 2
print('=' * 20)
print('date', end=': ')
print(2026, 9, 27, sep='/')
print('item', item, sep=': ')
print('price', price, sep=': ', end=' yen\n')
print('count', count, sep=': ')
print('total', price * count, sep=': ', end=' yen\n')
print('=' * 20)
このレクチャーで書いたプログラムです(書いた順)。コピーして手元で動かせます。
プログラム 1(main.py)
# 真偽値と比較演算子
is_open = True
is_empty = False
print(is_open)
print(is_empty)
print(type(is_open))
プログラム 2(main.py)
# 真偽値と比較演算子
stock = 12
print(stock > 10)
print(stock < 10)
print(stock >= 12)
print(stock <= 11)
print(stock == 12)
print(stock != 12)
プログラム 3(main.py)
# 真偽値と比較演算子
stock = 12
is_enough = stock >= 10
print(is_enough)
stock = 4
print(is_enough)
is_enough = stock >= 10
print(is_enough)
プログラム 4(main.py)
# 真偽値と比較演算子
print(3 == 3.0)
print(0.1 + 0.2 == 0.3)
print(round(0.1 + 0.2, 1) == 0.3)
プログラム 5(main.py)
# 真偽値と比較演算子
print('cat' == 'cat')
print('cat' == 'Cat')
print('apple' < 'banana')
print('Zoo' < 'apple')
print('10' < '9')
プログラム 6(main.py)
# 真偽値と比較演算子
print('5' == 5)
print(int('5') == 5)
print(int('5') < 7)
プログラム 7(main.py)
# 真偽値と比較演算子
temp = 23
print(18 <= temp <= 25)
temp = 30
print(18 <= temp <= 25)
プログラム 8(main.py)
# 真偽値と比較演算子
print(True == 1)
print(True + True)
print(int(False))
プログラム 9(main.py)
# 真偽値と比較演算子
print(bool(0))
print(bool(5))
print(bool(''))
print(bool('0'))
プログラム 10(main.py)
# 真偽値と比較演算子
line = 60
a = 72
b = 55
c = 90
print(f'a: {a >= line}')
print(f'b: {b >= line}')
print(f'c: {c >= line}')
count = (a >= line) + (b >= line) + (c >= line)
print(f'合格者: {count}人')
プログラム 11(main.py)
# 真偽値と比較演算子
line = 60
a = 72
b = 65
c = 90
print(f'a: {a >= line}')
print(f'b: {b >= line}')
print(f'c: {c >= line}')
count = (a >= line) + (b >= line) + (c >= line)
print(f'合格者: {count}人')
print(f'全員合格: {count == 3}')
このレクチャーで書いたプログラムです(書いた順)。コピーして手元で動かせます。
プログラム 1(main.py)
# 論理演算子(and・or・not)
has_ticket = True
has_seat = True
print(has_ticket and has_seat)
has_seat = False
print(has_ticket and has_seat)
プログラム 2(main.py)
# 論理演算子(and・or・not)
has_coupon = False
is_member = True
print(has_coupon or is_member)
is_member = False
print(has_coupon or is_member)
プログラム 3(main.py)
# 論理演算子(and・or・not)
is_raining = True
can_dry = not is_raining
print(can_dry)
print(not can_dry)
プログラム 4(main.py)
# 論理演算子(and・or・not)
temp = 28
humidity = 75
is_muggy = temp >= 25 and humidity >= 70
print(is_muggy)
print(temp >= 30 and humidity >= 70)
print(temp >= 30 or humidity >= 70)
プログラム 5(main.py)
# 論理演算子(and・or・not)
is_weekend = True
is_holiday = False
has_work = True
print(is_weekend or is_holiday and not has_work)
print((is_weekend or is_holiday) and not has_work)
プログラム 6(main.py)
# 論理演算子(and・or・not)
user_name = ''
display_name = user_name or 'Guest'
print(display_name)
print(0 or 10)
print(0 and 10)
プログラム 7(main.py)
# 論理演算子(and・or・not)
answer = 'no'
print(answer == 'y' or 'yes')
print(answer == 'y' or answer == 'yes')
プログラム 8(main.py)
# 論理演算子(and・or・not)
total = 300
count = 0
print(count != 0 and total / count > 50)
プログラム 9(main.py)
# 論理演算子(and・or・not)
score_sum = 240
tests = 3
is_absent = True
has_retry = True
average_ok = tests != 0 and score_sum / tests >= 60
passed = average_ok and not is_absent or has_retry
print(f'average_ok: {average_ok}')
print(f'passed: {passed}')
このレクチャーで書いたプログラムです(書いた順)。コピーして手元で動かせます。
プログラム 1(main.py)
# if・elif・else による条件分岐
battery = 15
if battery < 20:
print('Charge now')
print('Done')
プログラム 2(main.py)
# if・elif・else による条件分岐
battery = 60
if battery < 20:
print('Charge now')
else:
print('Battery OK')
print('Done')
プログラム 3(main.py)
# if・elif・else による条件分岐
weight = 3.5
if weight <= 1:
fee = 500
elif weight <= 5:
fee = 800
else:
fee = 1200
print(f'Fee: {fee} yen')
プログラム 4(main.py)
# if・elif・else による条件分岐
weight = 0.5
if weight <= 5:
fee = 800
elif weight <= 1:
fee = 500
else:
fee = 1200
print(f'Fee: {fee} yen')
プログラム 5(main.py)
# if・elif・else による条件分岐
weight = 0.5
if weight <= 1:
fee = 500
elif weight <= 5:
fee = 800
else:
fee = 1200
print(f'Fee: {fee} yen')
プログラム 6(main.py)
# if・elif・else による条件分岐
stamps = 12
if stamps >= 10:
print('Free drink')
elif stamps >= 5:
print('Free cookie')
プログラム 7(main.py)
# if・elif・else による条件分岐
hour = 20
is_holiday = False
if is_holiday:
print('Closed today')
elif hour >= 10 and hour < 19:
print('Open')
else:
print('Closed now')
プログラム 8(main.py)
# if・elif・else による条件分岐
hour = 14
is_holiday = False
has_coupon = True
if is_holiday:
print('Closed today')
elif hour >= 10 and hour < 19:
print('Open')
if has_coupon:
print('10% off')
else:
print('Closed now')
プログラム 9(main.py)
# if・elif・else による条件分岐
year = 2024
if year % 400 == 0:
print(f'{year} is a leap year')
elif year % 100 == 0:
print(f'{year} is not a leap year')
elif year % 4 == 0:
print(f'{year} is a leap year')
else:
print(f'{year} is not a leap year')
プログラム 10(main.py)
# if・elif・else による条件分岐
year = 1900
if year % 400 == 0:
print(f'{year} is a leap year')
elif year % 100 == 0:
print(f'{year} is not a leap year')
elif year % 4 == 0:
print(f'{year} is a leap year')
else:
print(f'{year} is not a leap year')
このレクチャーで書いたプログラムです(書いた順)。コピーして手元で動かせます。
プログラム 1(main.py)
# 条件式(三項演算子)と match 文
stock = 3
if stock > 0:
label = 'in stock'
else:
label = 'sold out'
print(label)
プログラム 2(main.py)
# 条件式(三項演算子)と match 文
stock = 3
label = 'in stock' if stock > 0 else 'sold out'
print(label)
プログラム 3(main.py)
# 条件式(三項演算子)と match 文
count = 1
print(count, 'item' if count == 1 else 'items')
count = 5
print(count, 'item' if count == 1 else 'items')
プログラム 4(main.py)
# 条件式(三項演算子)と match 文
count = 5
unit = 'items' if count > 1
print(count, unit)
プログラム 5(main.py)
# 条件式(三項演算子)と match 文
weight = 80
size = 'S' if weight < 50 else 'M' if weight < 100 else 'L'
print(size)
プログラム 6(main.py)
# 条件式(三項演算子)と match 文
command = 'stop'
match command:
case 'start':
print('starting')
case 'stop':
print('stopping')
case 'quit' | 'exit':
print('bye')
print('end')
プログラム 7(main.py)
# 条件式(三項演算子)と match 文
command = 'jump'
match command:
case 'start':
print('starting')
case 'stop':
print('stopping')
case 'quit' | 'exit':
print('bye')
case _:
print('unknown:', command)
print('end')
プログラム 8(main.py)
# 条件式(三項演算子)と match 文
status = 404
match status:
case 200:
print('OK')
case 404:
print('Not Found')
プログラム 9(main.py)
# 条件式(三項演算子)と match 文
status = 503
match status:
case 200:
print('OK')
case 404:
print('Not Found')
case code if code >= 500:
print('server error', code)
case _:
print('other status')
プログラム 10(main.py)
# 条件式(三項演算子)と match 文
target = 'stop'
command = 'start'
match command:
case c if c == target:
print('matched')
case _:
print('other')
プログラム 11(main.py)
# 条件式(三項演算子)と match 文
color = 'amber'
seconds = 2
match color:
case 'green':
action = 'go'
case 'yellow' | 'amber':
action = 'slow down'
case 'red':
action = 'stop'
case _:
action = 'check signal'
note = 'hurry' if seconds <= 2 else 'wait'
print(f'{action}: {note}')
このレクチャーで書いたプログラムです(書いた順)。コピーして手元で動かせます。
プログラム 1(main.py)
# for 文と range
print('Hello')
print('Hello')
print('Hello')
プログラム 2(main.py)
# for 文と range
for i in range(2, 11, 2):
print(i)
プログラム 3(main.py)
# for 文と range
for n in range(3, 0, -1):
print(n)
print('Go')
プログラム 4(main.py)
# for 文と range
for n in range(1, 11):
total = 0
total += n
print(total)
プログラム 5(main.py)
# for 文と range
for i in range(1, 5):
print('*' * i)
プログラム 6(main.py)
# for 文と range
for _ in range(3):
print('-' * 8)
プログラム 7(main.py)
# for 文と range
word = 'mint'
for i in range(len(word)):
print(i, word[i])
プログラム 8(main.py)
# for 文と range
count = '3'
for i in range(int(count)):
print(i + 1, '回目')
プログラム 9(main.py)
# for 文と range
for i in range(3)
print(i)
プログラム 10(main.py)
# for 文と range
count = 0
total = 0
for n in range(1, 21):
if n % 3 == 0:
count += 1
total += n
print(f'3の倍数: {count}個')
print(f'合計: {total}')
プログラム 11(main.py)
# for 文と range
count = 0
total = 0
for n in range(3, 21, 3):
count += 1
total += n
print(f'3の倍数: {count}個')
print(f'合計: {total}')
プログラム 12(main.py)
# for 文と range
savings = 0
for month in range(1, 7):
savings += 1500
print(f'{month}か月目: {savings}円')
print(f'合計: {savings}円')
このレクチャーで書いたプログラムです(書いた順)。コピーして手元で動かせます。
プログラム 1(main.py)
# while 文
energy = 0
while energy <= 100:
energy += 25
print('充電中:', energy)
print('充電完了')
プログラム 2(main.py)
# while 文
steps = 0
while steps < 3:
steps += 1
print('歩いた歩数:', steps)
プログラム 3(main.py)
# while 文
savings = 0
month = 0
while savings < 10000:
savings += 1500
month += 1
print(month, 'か月で', savings, '円')
プログラム 4(main.py)
# while 文
number = 0
digits = 0
while number > 0:
number //= 10
digits += 1
print(number)
print('桁数:', digits)
プログラム 5(main.py)
# while 文
slime_hp = 50
turn = 1
while slime_hp > 0 and turn <= 4:
damage = 12
if turn % 3 == 0:
damage = 20
slime_hp -= damage
print(turn, 'ターン目 残りHP', slime_hp)
turn += 1
if slime_hp > 0:
print('逃げられた')
else:
print('討伐成功')
このレクチャーで書いたプログラムです(書いた順)。コピーして手元で動かせます。
プログラム 1(main.py)
# break・continue とループの else
for n in range(1, 10):
if n == 4:
break
print(n)
print('end')
プログラム 2(main.py)
# break・continue とループの else
coins = 1
days = 0
while True:
coins *= 2
days += 1
if coins >= 1000:
break
print(days, coins)
プログラム 3(main.py)
# break・continue とループの else
text = 'to be or not'
count = 0
joined = ''
for ch in text:
if ch == ' ':
continue
count += 1
joined += ch
print(count)
print(joined)
プログラム 4(main.py)
# break・continue とループの else
n = 0
while n < 6:
n += 1
if n % 2 == 0:
continue
print(n)
プログラム 5(main.py)
# break・continue とループの else
num = 9
for d in range(2, num):
if num % d == 0:
print(num, 'は', d, 'で割り切れます')
break
else:
print(num, 'は素数です')
プログラム 6(main.py)
# break・continue とループの else
energy = 5
while energy > 0:
energy -= 2
print('energy', energy)
else:
print('empty')
プログラム 7(main.py)
# break・continue とループの else
serial = '12-34-56'
count = 0
for ch in serial:
if ch == '-':
continue
if not ch.isdigit():
print('NG:', ch)
break
count += 1
else:
print('OK:', count, 'digits')
このレクチャーで書いたプログラムです(書いた順)。コピーして手元で動かせます。
プログラム 1(main.py)
# 入れ子のループ
for row in range(1, 4):
print('row', row)
for seat in range(1, 3):
print('seat', seat)
プログラム 2(main.py)
# 入れ子のループ
count = 0
for row in range(1, 4):
for seat in range(1, 3):
print(f'{row}列{seat}番')
count += 1
print('合計', count, '席')
プログラム 3(main.py)
# 入れ子のループ
for row in range(1, 3):
for seat in range(1, 4):
print(f'[{row}-{seat}]', end='')
print()
プログラム 4(main.py)
# 入れ子のループ
for i in range(1, 3):
for i in range(1, 4):
print(i, end='')
print(' outer', i)
プログラム 5(main.py)
# 入れ子のループ
for row in range(1, 3):
for col in range(1, 4):
print(col, end='')
print(' row', row)
プログラム 6(main.py)
# 入れ子のループ
for row in range(1, 5):
for n in range(row):
print('*', end='')
print()
プログラム 7(main.py)
# 入れ子のループ
for row in range(1, 4):
for seat in range(1, 6):
if seat == 3:
break
print(f'[{row}-{seat}]', end='')
print()
プログラム 8(main.py)
# 入れ子のループ
size = int(input('大きさ: '))
for row in range(1, size + 1):
line = str(row)
for col in range(2, size + 1):
line += f'{row * col:3}'
print(line)
このレクチャーで書いたプログラムです(書いた順)。コピーして手元で動かせます。
プログラム 1(main.py)
# リストの基本(作成・参照・変更)
score1 = 72
score2 = 85
score3 = 90
score4 = 64
プログラム 2(main.py)
# リストの基本(作成・参照・変更)
scores = [72, 85, 90, 64]
print(scores)
プログラム 3(main.py)
# リストの基本(作成・参照・変更)
colors = ['red', 'green', 'blue']
empty = []
print(colors)
print(len(colors))
print(len(empty))
bag = ['potion', 3, 1.5, True]
プログラム 4(main.py)
# リストの基本(作成・参照・変更)
scores = [72, 85, 90, 64]
print(scores)
scores[2] = 95
print(scores)
scores[0] += 5
scores[-1] -= 4
print(scores)
プログラム 5(main.py)
# リストの基本(作成・参照・変更)
scores = [72, 85, 90, 64]
scores[1:3] = [80, 88]
print(scores)
プログラム 6(main.py)
# リストの基本(作成・参照・変更)
items = ['sword', 'shield', 'potion']
counts = [1, 2, 5]
counts[2] -= 1
items[0] = 'axe'
slot = int(input('使う番号: '))
counts[slot] -= 1
for i in range(len(items)):
print(f'{i}: {items[i]} x{counts[i]}')
このレクチャーで書いたプログラムです(書いた順)。コピーして手元で動かせます。
プログラム 1(main.py)
# リストの追加・削除・並べ替え
cart = ['milk', 'bread']
cart.append(['tea', 'jam'])
print(cart)
print(len(cart))
プログラム 2(main.py)
# リストの追加・削除・並べ替え
todo = ['wash', 'cook', 'read', 'cook', 'shop']
todo.remove('cook')
print(todo)
プログラム 3(main.py)
# リストの追加・削除・並べ替え
todo = ['wash', 'read', 'shop']
done = todo.pop()
print(done)
print(todo)
first = todo.pop(0)
print(first)
print(todo)
プログラム 4(main.py)
# リストの追加・削除・並べ替え
scores = [72, 85, 64, 90, 58]
scores.sort()
print(scores)
scores.sort(reverse=True)
print(scores)
プログラム 5(main.py)
# リストの追加・削除・並べ替え
animals = ['owl', 'Cat', 'dog', 'ant']
animals.reverse()
print(animals)
animals.sort()
print(animals)
プログラム 6(main.py)
# リストの追加・削除・並べ替え
scores = [72, 85, 64, 90, 58]
result = scores.sort()
print(result)
print(scores)
プログラム 7(main.py)
# リストの追加・削除・並べ替え
ranking = [80, 65, 92]
score = int(input('点数: '))
ranking.append(score)
ranking.sort(reverse=True)
dropped = ranking.pop()
print(f'上位3つ: {ranking}')
print(f'圏外: {dropped}')
このレクチャーで書いたプログラムです(書いた順)。コピーして手元で動かせます。
プログラム 1(main.py)
# リストの検索と in 演算子
fridge = ['milk', 'egg', 'tofu', 'carrot', 'egg']
print('eg' in fridge)
print('eg' in 'egg')
print('Egg' in fridge)
プログラム 2(main.py)
# リストの検索と in 演算子
scores = [70, 85, 90]
answer = int(input('点数: '))
print(answer in scores)
プログラム 3(main.py)
# リストの検索と in 演算子
fridge = ['milk', 'egg', 'tofu', 'carrot', 'egg']
item = input('探す食材: ')
if item in fridge:
print(item, 'は', fridge.index(item), '番目')
else:
print(item, 'はありません')
プログラム 4(main.py)
# リストの検索と in 演算子
fridge = ['milk', 'egg', 'tofu', 'carrot', 'egg']
print(fridge.count('egg'))
print(fridge.count('fish'))
プログラム 5(main.py)
# リストの検索と in 演算子
prices = [120, 480, 650, 300, 980]
for p in prices:
if p >= 500:
print('500円以上:', p)
break
else:
print('見つかりません')
プログラム 6(main.py)
# リストの検索と in 演算子
fridge = ['milk', 'egg', 'tofu', 'carrot', 'egg']
need = ['egg', 'onion', 'tofu']
extra = input('追加の食材: ')
need.append(extra)
buy = []
for food in need:
if food in fridge:
print(food, 'は', fridge.count(food), '個')
else:
buy.append(food)
print('買う物:', buy)
このレクチャーで書いたプログラムです(書いた順)。コピーして手元で動かせます。
プログラム 1(main.py)
# タプルとアンパック
point = (3, 7)
print(point)
print(type(point))
print(point[0])
print(len(point))
プログラム 2(main.py)
# タプルとアンパック
point = (3, 7)
temp = list(point)
temp[0] = 5
point = tuple(temp)
print(point)
プログラム 3(main.py)
# タプルとアンパック
a = (5)
b = (5,)
print(type(a))
print(type(b))
size = 1920, 1080
print(size)
プログラム 4(main.py)
# タプルとアンパック
color = (255, 128)
r, g, b = color
print(r)
print(g)
print(b)
プログラム 5(main.py)
# タプルとアンパック
color = (255, 128, 0)
r, _, b = color
print(r, b)
scores = (90, 75, 82, 68)
first, *rest = scores
print(first)
print(rest)
head, *middle, tail = scores
print(middle)
プログラム 6(main.py)
# タプルとアンパック
width, height = input('幅と高さ: ').split()
area = int(width) * int(height)
print(f'面積: {area}')
プログラム 7(main.py)
# タプルとアンパック
cart = [('pen', 120), ('note', 250), ('eraser', 80)]
for name, price in cart:
print(f'{name} は {price}円')
プログラム 8(main.py)
# タプルとアンパック
cart = [('pen', 120, 3), ('note', 250, 2), ('eraser', 80, 1)]
total = 0
for name, price, qty in cart:
cost = price * qty
total += cost
print(f'{name}: {cost}円')
print(f'合計: {total}円')
このレクチャーで書いたプログラムです(書いた順)。コピーして手元で動かせます。
プログラム 1(main.py)
# 辞書の基本
stock = {'pen': 12, 'eraser': 5, 'note': 30}
stock['pen'] = 20
stock['note'] -= 4
stock['ruler'] = 7
del stock['eraser']
print(stock)
print(len(stock))
プログラム 2(main.py)
# 辞書の基本
stock = {'pen': 20, 'note': 26, 'ruler': 7}
item = 'eraser'
if item in stock:
print(stock[item])
else:
print(item, 'は在庫表にありません')
プログラム 3(main.py)
# 辞書の基本
seats = {(1, 2): 'A', (3, 4): 'B'}
print(seats[(3, 4)])
プログラム 4(main.py)
# 辞書の基本
seats = {[1, 2]: 'A'}
プログラム 5(main.py)
# 辞書の基本
colors = {'red': 3, 'blue': 8, 'red': 5}
print(colors)
print(len(colors))
プログラム 6(main.py)
# 辞書の基本
notebook = {'size': 'A5', 'price': 180, 'colors': ['white', 'gray']}
print(notebook['colors'][1])
print(notebook['price'] * 3)
プログラム 7(main.py)
# 辞書の基本
cart = {}
cart['pen'] = 2
cart['ruler'] = 1
プログラム 8(main.py)
# 辞書の基本
prices = {'pen': 120, 'note': 150, 'ruler': 90}
prices['eraser'] = 80
prices['pen'] = 100
item = input('商品名: ')
if item in prices:
count = int(input('個数: '))
total = prices[item] * count
print(f'{item} を {count} 個で {total} 円です')
else:
print(f'{item} は扱っていません')
このレクチャーで書いたプログラムです(書いた順)。コピーして手元で動かせます。
プログラム 1(main.py)
# 辞書のループと便利なメソッド
menu = {'coffee': 300, 'tea': 250, 'cake': 450}
order = input('注文: ')
print(order, menu.get(order, 'メニューにありません'))
プログラム 2(main.py)
# 辞書のループと便利なメソッド
votes = ['tea', 'coffee', 'tea', 'cake', 'coffee', 'tea']
count = {}
for drink in votes:
count[drink] = count.get(drink, 0) + 1
print(count)
for drink, num in count.items():
print(f'{drink}: {num}票')
プログラム 3(main.py)
# 辞書のループと便利なメソッド
menu = {'coffee': 300, 'tea': 250, 'cake': 450}
menu.update({'tea': 270, 'juice': 280})
print(menu)
sold = menu.pop('cake')
print(sold)
print(menu.pop('donut', 0))
print(menu)
プログラム 4(main.py)
# 辞書のループと便利なメソッド
menu = {'coffee': 300, 'tea': 250, 'cake': 450}
cart = {'coffee': 2, 'cake': 1, 'juice': 1}
total = 0
for name, qty in cart.items():
price = menu.get(name, 0)
if price == 0:
print(f'{name} はありません')
continue
subtotal = price * qty
total += subtotal
print(f'{name} x{qty} = {subtotal}円')
print(f'合計: {total}円')
このレクチャーで書いたプログラムです(書いた順)。コピーして手元で動かせます。
プログラム 1(main.py)
# 集合(set)と集合演算
dice = {3, 1, 3, 2, 1}
print(dice[0])
プログラム 2(main.py)
# 集合(set)と集合演算
votes = [2, 5, 2, 4, 5, 2]
kinds = set(votes)
print(kinds)
print(len(votes), len(kinds))
プログラム 3(main.py)
# 集合(set)と集合演算
stamps = set()
print(type({}))
stamps.add(1)
stamps.add(3)
stamps.add(3)
print(stamps)
stamps.discard(1)
stamps.discard(7)
print(stamps)
プログラム 4(main.py)
# 集合(set)と集合演算
stamps = {3, 4}
stamps.remove(4)
stamps.remove(7)
プログラム 5(main.py)
# 集合(set)と集合演算
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a | [7])
プログラム 6(main.py)
# 集合(set)と集合演算
recipe = {'egg', 'milk', 'flour', 'sugar'}
fridge = {'egg', 'milk', 'butter'}
print(sorted(recipe - fridge))
while not recipe <= fridge:
item = input('買った材料: ')
fridge.add(item)
print('残り:', sorted(recipe - fridge))
print('全部そろいました')
このレクチャーで書いたプログラムです(書いた順)。コピーして手元で動かせます。
プログラム 1(main.py)
# 内包表記(リスト・辞書・集合)
prices = [120, 80, 250, 40]
taxed = []
for p in prices:
taxed.append(p * 11 // 10)
print(taxed)
quick = [p * 11 // 10 for p in prices]
print(quick)
プログラム 2(main.py)
# 内包表記(リスト・辞書・集合)
squares = [n * n for n in range(1, 6)]
print(squares)
colors = ['red', 'blue', 'green']
upper = [c.upper() for c in colors]
sizes = [len(c) for c in colors]
print(upper)
print(sizes)
プログラム 3(main.py)
# 内包表記(リスト・辞書・集合)
temps = [18, 25, 31, 22, 34, 29]
hot = [t for t in temps if t >= 30]
print(hot)
over = [t - 25 for t in temps if t > 25]
print(over)
labels = ['hot' if t >= 30 else 'ok' for t in temps]
print(labels)
プログラム 4(main.py)
# 内包表記(リスト・辞書・集合)
temps = [18, 25, 31, 22, 34, 29]
labels = ['hot' if t >= 30 for t in temps]
print(labels)
プログラム 5(main.py)
# 内包表記(リスト・辞書・集合)
colors = ['red', 'blue', 'green']
size_of = {c: len(c) for c in colors}
print(size_of)
cafe = {'tea': 150, 'cake': 420, 'juice': 180}
with_tax = {k: v * 11 // 10 for k, v in cafe.items()}
print(with_tax)
pricey = {k: v for k, v in cafe.items() if v >= 200}
print(pricey)
by_price = {v: k for k, v in cafe.items()}
print(by_price)
プログラム 6(main.py)
# 内包表記(リスト・辞書・集合)
words = ['sun', 'moon', 'star', 'sky', 'cloud']
lengths = [len(w) for w in words]
kinds = {len(w) for w in words}
print(lengths)
print(kinds)
print(type(kinds))
print(type({w: len(w) for w in words}))
プログラム 7(main.py)
# 内包表記(リスト・辞書・集合)
seats = [(r, c) for r in range(2) for c in range(3)]
print(seats)
プログラム 8(main.py)
# 内包表記(リスト・辞書・集合)
prices = [120, 80, 250, 40]
quick = [p * 2 for p in prices]
print(p)
プログラム 9(main.py)
# 内包表記(リスト・辞書・集合)
cafe = {'tea': 150, 'cake': 420, 'juice': 180}
line = input('注文: ')
orders = line.split()
valid = [o for o in orders if o in cafe]
print(valid)
bill = [cafe[o] for o in valid]
print(bill)
kinds = {o for o in valid}
print(f'合計: {sum(bill)}円')
print(f'種類: {len(kinds)}')
このレクチャーで書いたプログラムです(書いた順)。コピーして手元で動かせます。
プログラム 1(main.py)
# enumerate と zip
tasks = ['mail', 'shop', 'gym']
for no, task in tasks:
print(no, task)
プログラム 2(main.py)
# enumerate と zip
items = ['cup', 'plate', 'spoon']
prices = [400, 650, 180]
stocks = [5, 0, 12]
for item, price, stock in zip(items, prices, stocks):
print(f'{item}: {price}円 在庫{stock}')
プログラム 3(main.py)
# enumerate と zip
sizes = ['S', 'M', 'L', 'XL']
counts = [3, 8, 2]
for size, count in zip(sizes, counts):
print(size, count)
プログラム 4(main.py)
# enumerate と zip
days = ['mon', 'tue', 'wed']
menus = ['curry', 'ramen', 'soba']
lunch = dict(zip(days, menus))
print(lunch)
print(lunch['tue'])
プログラム 5(main.py)
# enumerate と zip
teams = ['Hawks', 'Lions', 'Bears']
times = [52.3, 54.1, 55.8]
for rank, (team, sec) in enumerate(zip(teams, times), start=1):
mark = ' 新記録' if sec < 53 else ''
print(f'{rank}位 {team} {sec}秒{mark}')
このレクチャーで書いたプログラムです(書いた順)。コピーして手元で動かせます。
プログラム 1(main.py)
# 関数の定義と戻り値
coffee = 120
print(coffee * 11 // 10)
cake = 480
print(cake * 11 // 10)
プログラム 2(main.py)
# 関数の定義と戻り値
def show_line():
print('-' * 12)
show_line()
print('本日のメニュー')
show_line()
プログラム 3(main.py)
# 関数の定義と戻り値
def show_tax(price):
print(price * 11 // 10)
result = show_tax(120)
print(result)
プログラム 4(main.py)
# 関数の定義と戻り値
def with_tax(price):
return price * 11 // 10
total = with_tax(120) + with_tax(480)
print(total)
print(with_tax(300) > 300)
プログラム 5(main.py)
# 関数の定義と戻り値
def shipping_fee(total):
if total >= 3000:
return 0
return 500
print('送料を計算しました')
print(shipping_fee(3200))
print(shipping_fee(1800))
プログラム 6(main.py)
# 関数の定義と戻り値
def shipping_fee(total):
print('送料を計算します')
if total >= 3000:
return 0
return 500
print(shipping_fee(3200))
print(shipping_fee(1800))
プログラム 7(main.py)
# 関数の定義と戻り値
def split_bill(total, people):
each = total // people
rest = total % people
return each, rest
pay, extra = split_bill(1000, 3)
print(pay)
print(extra)
プログラム 8(main.py)
# 関数の定義と戻り値
print(to_minutes(3))
def to_minutes(hours):
return hours * 60
プログラム 9(main.py)
# 関数の定義と戻り値
def to_minutes(hours):
minutes = hours * 60
return minutes
print(to_minutes(3))
プログラム 10(main.py)
# 関数の定義と戻り値
def with_tax(price):
return price * 11 // 10
def shipping_fee(total):
if total >= 3000:
return 0
return 500
def checkout(price):
taxed = with_tax(price)
return taxed + shipping_fee(taxed)
price = int(input('商品の値段: '))
print(f'お支払い: {checkout(price)}円')
プログラム 11(main.py)
# 関数の定義と戻り値
def with_tax(price):
return price * 108 // 100
def shipping_fee(total):
if total >= 3000:
return 0
return 500
def checkout(price):
taxed = with_tax(price)
return taxed + shipping_fee(taxed)
price = int(input('商品の値段: '))
print(f'お支払い: {checkout(price)}円')
このレクチャーで書いたプログラムです(書いた順)。コピーして手元で動かせます。
プログラム 1(main.py)
# 引数の種類(位置・キーワード・既定値)
def make_tea(kind, cups):
print(f'{kind} tea x {cups}')
make_tea('green', kind='black')
プログラム 2(main.py)
# 引数の種類(位置・キーワード・既定値)
print('tea', 'time')
print('tea', 'time', sep='-')
プログラム 3(main.py)
# 引数の種類(位置・キーワード・既定値)
def make_tea(kind, cups=1):
print(f'{kind} tea x {cups}')
make_tea('green')
make_tea('green', 4)
プログラム 4(main.py)
# 引数の種類(位置・キーワード・既定値)
def make_tea(kind, cups=1, sugar=0):
print(f'{kind} tea x {cups} sugar {sugar}')
make_tea('black')
make_tea('black', sugar=2)
make_tea('black', 2, 1)
プログラム 5(main.py)
# 引数の種類(位置・キーワード・既定値)
def add_item(item, bag=None):
if bag is None:
bag = []
bag.append(item)
return bag
print(add_item('cup'))
print(add_item('spoon'))
プログラム 6(main.py)
# 引数の種類(位置・キーワード・既定値)
def ship_fee(weight, express=False, rate=300):
fee = weight * rate
if express:
fee += 500
return fee
kg = int(input('重さ: '))
print(ship_fee(kg))
print(ship_fee(kg, express=True))
print(ship_fee(kg, rate=200, express=True))
このレクチャーで書いたプログラムです(書いた順)。コピーして手元で動かせます。
プログラム 1(main.py)
# 可変長引数(*args・**kwargs)
def add_points(a, b):
return a + b
print(add_points(10, 20))
print(add_points(10, 20, 30))
プログラム 2(main.py)
# 可変長引数(*args・**kwargs)
def add_points(*points):
total = 0
for p in points:
total += p
return total
print(add_points(10, 20, 30))
print(add_points(5))
print(add_points())
プログラム 3(main.py)
# 可変長引数(*args・**kwargs)
def make_label(title, *tags, sep='/'):
print(title + ': ' + sep.join(tags))
make_label('新商品', 'セール', '限定', sep=' | ')
make_label('新商品', 'セール', '-')
プログラム 4(main.py)
# 可変長引数(*args・**kwargs)
def add_points(*points):
total = 0
for p in points:
total += p
return total
scores = [70, 85, 90]
print(add_points(*scores))
print(*scores)
プログラム 5(main.py)
# 可変長引数(*args・**kwargs)
def show_settings(**settings):
for key, value in settings.items():
print(f'{key} = {value}')
saved = {'volume': 3, 'theme': 'light'}
show_settings(**saved)
プログラム 6(main.py)
# 可変長引数(*args・**kwargs)
def order(drink, *toppings, **notes):
print('注文:', drink)
if toppings:
print('トッピング:', ', '.join(toppings))
for key, value in notes.items():
print(f'- {key}: {value}')
extras = ['シナモン', 'ナッツ']
memo = {'size': 'L', 'hot': True}
order('カフェモカ', *extras, **memo)
このレクチャーで書いたプログラムです(書いた順)。コピーして手元で動かせます。
プログラム 1(main.py)
# スコープ(ローカル・グローバル・nonlocal)
def make_tea():
water = 200
make_tea()
print(water)
プログラム 2(main.py)
# スコープ(ローカル・グローバル・nonlocal)
tax_rate = 10
def show_rate():
tax_rate = 8
print(tax_rate)
show_rate()
print(tax_rate)
プログラム 3(main.py)
# スコープ(ローカル・グローバル・nonlocal)
visits = 0
def add_visit():
visits += 1
try:
add_visit()
print(visits)
except UnboundLocalError as e:
print(type(e).__name__)
print(e)
プログラム 4(main.py)
# スコープ(ローカル・グローバル・nonlocal)
visits = 0
def add_visit():
global visits
visits += 1
add_visit()
add_visit()
add_visit()
print(visits)
プログラム 5(main.py)
# スコープ(ローカル・グローバル・nonlocal)
def add_visit(count):
return count + 1
visits = 0
visits = add_visit(visits)
visits = add_visit(visits)
print(visits)
プログラム 6(main.py)
# スコープ(ローカル・グローバル・nonlocal)
logs = []
def write_log(text):
logs.append(text)
write_log('start')
write_log('stop')
print(logs)
プログラム 7(main.py)
# スコープ(ローカル・グローバル・nonlocal)
def count_stamps():
stamps = 0
def press():
stamps += 1
press()
press()
print(stamps)
try:
count_stamps()
except UnboundLocalError as e:
print(type(e).__name__)
print(e)
プログラム 8(main.py)
# スコープ(ローカル・グローバル・nonlocal)
def count_stamps():
stamps = 0
def press():
nonlocal stamps
stamps += 1
press()
press()
print(stamps)
count_stamps()
プログラム 9(main.py)
# スコープ(ローカル・グローバル・nonlocal)
def make_counter():
total = 0
def add(amount):
nonlocal total
total += amount
return total
return add
cart = make_counter()
print(cart(300))
print(cart(150))
other = make_counter()
print(other(500))
print(cart(20))
このレクチャーで書いたプログラムです(書いた順)。コピーして手元で動かせます。
プログラム 1(main.py)
# 再帰関数
def launch(n):
if n == 0:
print('Go!')
return
print(n)
launch(n - 1)
launch(3)
プログラム 2(main.py)
# 再帰関数
def launch(n):
launch(n - 1)
try:
launch(3)
except RecursionError as e:
print(type(e).__name__)
print(e)
プログラム 3(main.py)
# 再帰関数
def fact(n):
print(f'行き {n}')
if n == 1:
return 1
result = n * fact(n - 1)
print(f'帰り {n} -> {result}')
return result
print(fact(4))
プログラム 4(main.py)
# 再帰関数
def fact(n):
if n == 1:
return 1
return n * fact(n - 1)
try:
print(fact(0))
except RecursionError as e:
print(type(e).__name__)
プログラム 5(main.py)
# 再帰関数
def fact(n):
if n <= 1:
return 1
return n * fact(n - 1)
def fact_loop(n):
result = 1
for i in range(2, n + 1):
result *= i
return result
print(fact(5))
print(fact_loop(5))
プログラム 6(main.py)
# 再帰関数
boxes = [3, [4, 5], [6, [7]]]
def total(items):
result = 0
for item in items:
if type(item) == list:
result += total(item)
else:
result += item
return result
print(total(boxes))
プログラム 7(main.py)
# 再帰関数
tree = {'docs': {'memo.txt': 3, 'img': {'cat.png': 12}}, 'app.py': 5}
def show(folder, depth):
for name, value in folder.items():
if type(value) == dict:
print('--' * depth + name + '/')
show(value, depth + 1)
else:
print('--' * depth + f'{name} {value}KB')
show(tree, 0)
プログラム 8(main.py)
# 再帰関数
tree = {'docs': {'memo.txt': 3, 'img': {'cat.png': 12}}, 'app.py': 5}
def show(folder, depth):
size = 0
for name, value in folder.items():
if type(value) == dict:
print('--' * depth + name + '/')
size += show(value, depth + 1)
else:
print('--' * depth + f'{name} {value}KB')
size += value
return size
print(f'合計 {show(tree, 0)}KB')
このレクチャーで書いたプログラムです(書いた順)。コピーして手元で動かせます。
プログラム 1(main.py)
# lambda と sorted・map・filter
def triple(n):
return n * 3
print(triple(4))
triple_l = lambda n: n * 3
print(triple_l(4))
area = lambda w, h: w * h
print(area(3, 5))
プログラム 2(main.py)
# lambda と sorted・map・filter
nums = [42, 7, 19, 3]
result = sorted(nums)
print(result)
print(nums)
プログラム 3(main.py)
# lambda と sorted・map・filter
words = ['kiwi', 'banana', 'fig', 'cherry']
print(sorted(words))
print(sorted(words, key=len))
プログラム 4(main.py)
# lambda と sorted・map・filter
items = [('pen', 120), ('note', 80), ('bag', 950)]
by_price = sorted(items, key=lambda item: item[1])
print(by_price)
expensive = sorted(items, key=lambda item: item[1], reverse=True)
print(expensive[0])
プログラム 5(main.py)
# lambda と sorted・map・filter
items = [('pen', 120), ('note', 80), ('bag', 950)]
print(sorted(items, lambda item: item[1]))
プログラム 6(main.py)
# lambda と sorted・map・filter
prices = [100, 250, 480]
doubled = map(lambda p: p * 2, prices)
print(type(doubled))
print(list(doubled))
print(list(doubled))
プログラム 7(main.py)
# lambda と sorted・map・filter
text = input('数字: ')
nums = list(map(int, text.split()))
print(nums)
print(sum(nums))
プログラム 8(main.py)
# lambda と sorted・map・filter
scores = [72, 45, 90, 38, 65]
passed = filter(lambda s: s >= 60, scores)
print(list(passed))
print(list(map(lambda s: s >= 60, scores)))
プログラム 9(main.py)
# lambda と sorted・map・filter
goods = [('cup', 300), ('spoon', 90), ('plate', 540), ('fork', 70)]
limit = int(input('上限: '))
cheap = filter(lambda g: g[1] <= limit, goods)
names = map(lambda g: g[0], cheap)
print(sorted(names, reverse=True))
このレクチャーで書いたプログラムです(書いた順)。コピーして手元で動かせます。
プログラム 1(main.py)
# 例外の基本と try・except
text = 'abc'
try:
num = int(text)
print(num * 2)
except ValueError:
print('数字に変換できません')
print('おわり')
プログラム 2(main.py)
# 例外の基本と try・except
try:
people = int(input('人数: '))
print(f'1人 {1200 / people} 円')
except (ValueError, ZeroDivisionError) as e:
print('入力エラー:', e)
print('おわり')
プログラム 3(main.py)
# 例外の基本と try・except
scores = [70, 85, 90]
try:
average = sum(scorse) / len(scores)
print('平均:', average)
except ZeroDivisionError:
print('点数がありません')
プログラム 4(main.py)
# 例外の基本と try・except
while True:
try:
qty = int(input('個数: '))
break
except ValueError:
print('数字で入力してください')
print(f'{qty} 個を注文しました')
プログラム 5(main.py)
# 例外の基本と try・except
data = ['12', '7', 'none', '30', '5.5']
total = 0
for item in data:
try:
total += int(item)
except ValueError:
print(item, 'は飛ばします')
print('合計:', total)
プログラム 6(main.py)
# 例外の基本と try・except
menu = {'coffee': 300, 'tea': 250}
name = input('商品: ')
try:
price = menu[name]
qty = int(input('個数: '))
print(f'合計 {price * qty} 円')
except KeyError:
print(name, 'はメニューにありません')
except ValueError:
print('個数は数字で入力してください')
print('ご利用ありがとうございました')
このレクチャーで書いたプログラムです(書いた順)。コピーして手元で動かせます。
プログラム 1(main.py)
# else・finally と raise
text = 'eight'
try:
count = int(text)
except ValueError:
print('数字ではありません')
else:
print('変換成功:', count)
finally:
print('チェック終了')
プログラム 2(main.py)
# else・finally と raise
items = ['pen', 'note']
try:
print('取り出し開始')
print(items[5])
finally:
print('後片付け')
プログラム 3(main.py)
# else・finally と raise
def set_volume(level):
if level < 0 or level > 10:
raise ValueError('音量は 0 から 10 です')
print('音量を', level, 'にしました')
set_volume(7)
try:
set_volume(15)
except ValueError as e:
print('エラー:', e)
print('プログラムは続きます')
プログラム 4(main.py)
# else・finally と raise
level = 15
if level > 10:
raise '音量が大きすぎます'
プログラム 5(main.py)
# else・finally と raise
def set_volume(level):
if level < 0 or level > 10:
raise ValueError('音量は 0 から 10 です')
print('音量を', level, 'にしました')
try:
set_volume(-1)
except ValueError:
print('記録: 音量の設定に失敗')
raise
プログラム 6(main.py)
# else・finally と raise
def set_volume(level):
if level < 0 or level > 10:
raise ValueError('音量は 0 から 10 です')
print('音量を', level, 'にしました')
try:
try:
set_volume(-1)
except ValueError:
print('記録: 音量の設定に失敗')
raise
except ValueError as e:
print(type(e).__name__)
プログラム 7(main.py)
# else・finally と raise
def read_count(text):
count = int(text)
if count < 1:
raise ValueError('1 枚以上を指定してください')
return count
entry = input('枚数: ')
try:
count = read_count(entry)
except ValueError as e:
print('入力エラー:', e)
else:
print('合計', count * 500, '円です')
finally: print('受付を終わります')
このレクチャーで書いたプログラムです(書いた順)。コピーして手元で動かせます。
プログラム 1(main.py)
# 自作の例外クラス
class StockError(Exception):
pass
def take_item(stock, count):
if count > stock:
raise StockError('在庫が足りません')
return stock - count
print(take_item(10, 4))
try:
left = take_item(3, 5)
print('残り', left)
except StockError as e:
print('受け止めた:', e)
プログラム 2(main.py)
# 自作の例外クラス
class StockError(Exception):
pass
class CountError(Exception):
pass
def take_item(stock, count):
if count <= 0:
raise CountError('個数は1以上にしてください')
if count > stock:
raise StockError('在庫が足りません')
return stock - count
プログラム 3(main.py)
# 自作の例外クラス
class StockError(Exception): pass
class CountError(Exception): pass
def take_item(stock, count):
if count <= 0: raise CountError('個数は1以上にしてください')
if count > stock: raise StockError('在庫が足りません')
return stock - count
for count in [2, 0, 9]:
try:
print('残り', take_item(5, count))
except StockError as e:
print('在庫エラー:', e)
except CountError as e:
print('個数エラー:', e)
プログラム 4(main.py)
# 自作の例外クラス
class PriceError(Exception):
pass
raise PriceError('値段がマイナスです')
プログラム 5(main.py)
# 自作の例外クラス
class ShopError(Exception):
pass
class StockError(ShopError):
pass
class CountError(ShopError):
pass
def order(count):
if count <= 0:
raise CountError('個数は1以上にしてください')
if count > 5:
raise StockError('在庫が足りません')
return 5 - count
プログラム 6(main.py)
# 自作の例外クラス
for count in [0, 8]:
try:
order(count)
except ShopError as e:
print(type(e))
print('受け止めた:', e)
プログラム 7(main.py)
# 自作の例外クラス
class ShopError(Exception): pass
class StockError(ShopError): pass
class CountError(ShopError): pass
def order(count):
if count <= 0: raise CountError('個数は1以上にしてください')
if count > 5: raise StockError('在庫が足りません')
return 5 - count
for count in [0, 8]:
try: order(count)
except StockError as e:
print('在庫エラー:', e)
except ShopError as e:
print('お店のエラー:', e)
プログラム 8(main.py)
# 自作の例外クラス
class ShopError(Exception):
pass
class StockError(ShopError):
pass
class CountError(ShopError):
pass
stock = 5
def order(count):
if count <= 0:
raise CountError('個数は1以上にしてください')
if count > stock:
raise StockError(f'在庫は {stock} 個しかありません')
プログラム 9(main.py)
# 自作の例外クラス
class ShopError(Exception): pass
class StockError(ShopError): pass
class CountError(ShopError): pass
stock = 5
def order(count):
if count <= 0: raise CountError('個数は1以上にしてください')
if count > stock: raise StockError(f'在庫は {stock} 個しかありません')
return stock - count
while True:
try:
count = int(input('個数: ')); left = order(count)
except ValueError: print('数字で入力してください')
except ShopError as e: print('注文できません:', e)
プログラム 10(main.py)
# 自作の例外クラス
class ShopError(Exception): pass
class StockError(ShopError): pass
class CountError(ShopError): pass
def order(count, stock=5):
if count <= 0: raise CountError('個数は1以上にしてください')
if count > stock: raise StockError(f'在庫は {stock} 個しかありません')
return stock - count
while True:
try:
left = order(int(input('個数: ')))
except ValueError: print('数字で入力してください')
except ShopError as e: print('注文できません:', e)
else: print('注文しました。残り', left); break
プログラム 11(main.py)
# 自作の例外クラス
class ShopError(Exception):
pass
class StockError(ShopError):
pass
try:
raise StockError('在庫が足りません')
except StockError as e:
print('在庫不足:', e)
except ShopError as e:
print('注文できません:', e)
このレクチャーで書いたプログラムです(書いた順)。コピーして手元で動かせます。
プログラム 1(main.py)
# クラスとインスタンス
class Robot:
pass
r1 = Robot()
r2 = Robot()
print(r1 is r2)
print(r1 == r2)
print(isinstance(r1, Robot))
print(isinstance('R-01', Robot))
プログラム 2(main.py)
# クラスとインスタンス
class Robot:
pass
r1 = Robot()
r1.model = 'R-01'
r1.battery = 80
r2 = Robot()
r2.model = 'R-02'
r2.battery = 35
r1.battery -= 30
print(vars(r1))
print(vars(r2))
プログラム 3(main.py)
# クラスとインスタンス
class Robot:
pass
r3 = Robot()
r3.model = 'R-03'
r3.batery = 60
print(vars(r3))
プログラム 4(main.py)
# クラスとインスタンス
class Robot:
pass
r1 = Robot()
r1.battery = 90
spare = r1
spare.battery = 10
print(r1.battery)
print(spare is r1)
プログラム 5(main.py)
# クラスとインスタンス
class Robot:
pass
def make_robot(model, battery):
robot = Robot()
robot.model = model
robot.battery = battery
return robot
def charge(robot, amount):
robot.battery = min(robot.battery + amount, 100)
robots = [make_robot('R-01', 80),
make_robot('R-02', 15),
make_robot('R-03', 95)]
プログラム 6(main.py)
# クラスとインスタンス
class Robot:
pass
def make_robot(model, battery):
robot = Robot()
robot.model = model
robot.battery = battery
return robot
def charge(robot, amount):
robot.battery = min(robot.battery + amount, 100)
robots = [make_robot('R-01', 80), make_robot('R-02', 15), make_robot('R-03', 95)]
for robot in robots:
charge(robot, 20)
print(f'{robot.model}: {robot.battery}%')
プログラム 7(main.py)
# クラスとインスタンス
class Robot: pass
def make_robot(model, battery):
robot = Robot()
robot.model = model
robot.battery = battery
return robot
def charge(robot, amount):
robot.battery = min(robot.battery + amount, 100)
robots = [make_robot('R-01', 80), make_robot('R-02', 15), make_robot('R-03', 95)]
for robot in robots:
charge(robot, 20)
print(f'{robot.model}: {robot.battery}%')
print([robot.model for robot in robots if robot.battery < 50])
このレクチャーで書いたプログラムです(書いた順)。コピーして手元で動かせます。
プログラム 1(main.py)
# __init__ とインスタンス変数・メソッド
class Plant:
def __init__(self, kind, height):
self.kind = kind
self.height = height
self.watered = 0
def water(self):
self.watered += 1
self.height += 2
a = Plant('cactus', 5)
b = Plant('tulip', 10)
プログラム 2(main.py)
# __init__ とインスタンス変数・メソッド
class Plant:
def __init__(self, height):
self.height = height
self.watered = 0
def water():
self.watered += 1
self.height += 2
a = Plant(5)
b = Plant(10)
a.water()
a.water()
print(a.height, a.watered)
print(b.height, b.watered)
プログラム 3(main.py)
# __init__ とインスタンス変数・メソッド
class Plant:
def __init__(self, kind, height):
self.kind = kind
self.height = height
self.watered = 0
def water(self, amount):
self.watered += 1
self.height += amount
def report(self):
return f'{self.kind}: {self.height}cm 水やり{self.watered}回'
a, b = Plant('cactus', 5), Plant('tulip', 10)
print(a.report())
print(b.report())
プログラム 4(main.py)
# __init__ とインスタンス変数・メソッド
class Plant:
def __init__(self, kind, height):
self.kind, self.height = kind, height
self.watered = 0
def water(self, amount):
self.watered += 1
self.height += amount
print(self.report())
def report(self):
return f'{self.kind}: {self.height}cm 水やり{self.watered}回'
a = Plant('cactus', 5)
a.water(3)
a.water(4)
プログラム 5(main.py)
# __init__ とインスタンス変数・メソッド
class Bottle:
def __init__(self, capacity):
self.capacity = capacity
self.amount = 0
def pour(self, ml):
space = self.capacity - self.amount
if ml > space:
ml = space
self.amount += ml
return ml
def status(self):
return f'{self.amount} / {self.capacity} ml'
プログラム 6(main.py)
# __init__ とインスタンス変数・メソッド
class Bottle:
def __init__(self, capacity):
self.capacity, self.amount = capacity, 0
def pour(self, ml):
ml = min(ml, self.capacity - self.amount)
self.amount += ml
return ml
def status(self): return f'{self.amount} / {self.capacity} ml'
bottle = Bottle(500)
ml = int(input('注ぐ量: '))
for _ in range(2):
print(f'{bottle.pour(ml)} ml 入りました')
print(bottle.status())
このレクチャーで書いたプログラムです(書いた順)。コピーして手元で動かせます。
プログラム 1(main.py)
# クラス変数・クラスメソッド・静的メソッド
class Ticket:
price = 1800
def __init__(self, seat):
self.seat = seat
a = Ticket('A1')
b = Ticket('B5')
a.price = 1500
print(a.price, b.price, Ticket.price)
print(vars(a))
プログラム 2(main.py)
# クラス変数・クラスメソッド・静的メソッド
class Ticket:
price = 1800
count = 0
def __init__(self, seat):
self.seat = seat
Ticket.count += 1
@classmethod
def show_count(cls):
print(f'発行枚数: {cls.count}')
プログラム 3(main.py)
# クラス変数・クラスメソッド・静的メソッド
class Ticket:
price = 1800
count = 0
def __init__(self, seat):
self.seat = seat
Ticket.count += 1
@classmethod
def set_price(cls, new_price):
cls.price = new_price
a = Ticket('A1')
b = Ticket('B5')
Ticket.set_price(2200)
print(a.price, b.price)
プログラム 4(main.py)
# クラス変数・クラスメソッド・静的メソッド
class Ticket:
price = 1800
count = 0
def __init__(self, seat):
self.seat = seat
Ticket.count += 1
@classmethod
def from_text(cls, text):
row, num = text.split('-')
return cls(row + num)
プログラム 5(main.py)
# クラス変数・クラスメソッド・静的メソッド
class Ticket:
count = 0
def __init__(self, seat):
self.seat = seat
Ticket.count += 1
@classmethod
def from_text(cls, text):
row, num = text.split('-')
return cls(row + num)
d = Ticket.from_text('C-7')
print(d.seat)
print('発行枚数:', Ticket.count)
プログラム 6(main.py)
# クラス変数・クラスメソッド・静的メソッド
class Ticket:
count = 0
def __init__(self, seat):
self.seat = seat
Ticket.count += 1
@classmethod
def show_count():
print(f'発行枚数: {cls.count}')
Ticket.show_count()
プログラム 7(main.py)
# クラス変数・クラスメソッド・静的メソッド
class Ticket:
count = 0
def __init__(self, seat):
self.seat = seat
Ticket.count += 1
@classmethod
def show_count(cls):
print(f'発行枚数: {cls.count}')
@staticmethod
def is_row_ok(row):
return row in ['A', 'B', 'C']
プログラム 8(main.py)
# クラス変数・クラスメソッド・静的メソッド
class Ticket:
@staticmethod
def is_row_ok(row):
return row in ['A', 'B', 'C']
print(Ticket.is_row_ok('B'))
print(Ticket.is_row_ok('Z'))
プログラム 9(main.py)
# クラス変数・クラスメソッド・静的メソッド
class Ticket:
def __init__(self, seat):
self.seat = seat
@classmethod
def from_text(cls, text):
row, num = text.split('-')
if not cls.is_row_ok(row):
raise ValueError(f'その列はありません: {row}')
return cls(row + num)
@staticmethod
def is_row_ok(row):
return row in ['A', 'B', 'C']
プログラム 10(main.py)
# クラス変数・クラスメソッド・静的メソッド
texts = ['A-3', 'B-12', 'Z-1']
for text in texts:
try:
t = Ticket.from_text(text)
print(f'{t.seat} を発行しました')
except ValueError as e:
print(e)
プログラム 11(main.py)
# クラス変数・クラスメソッド・静的メソッド
class Ticket:
price, count = 1800, 0
def __init__(self, seat):
self.seat = seat; Ticket.count += 1
@classmethod
def from_text(cls, text):
row, num = text.split('-')
if row not in ['A', 'B', 'C']: raise ValueError(f'その列はありません: {row}')
return cls(row + num)
for text in ['A-3', 'B-12', 'Z-1']:
try: print(f'{Ticket.from_text(text).seat} を発行しました')
except ValueError as e: print(e)
print(f'発行枚数: {Ticket.count}\n売上: {Ticket.count * Ticket.price}円')
このレクチャーで書いたプログラムです(書いた順)。コピーして手元で動かせます。
プログラム 1(main.py)
# 継承とメソッドのオーバーライド
class Vehicle:
def __init__(self, name, speed):
self.name = name
self.speed = speed
def move(self, hours):
km = self.speed * hours
print(f'{self.name}: {km} km')
class Bicycle(Vehicle):
def ring_bell(self):
print(f'{self.name}: チリン')
car = Vehicle('car', 60)
bike = Bicycle('bike', 15)
car.ring_bell()
プログラム 2(main.py)
# 継承とメソッドのオーバーライド
class Vehicle:
def __init__(self, name, rate):
self.name = name
self.rate = rate
def fare(self, km):
return km * self.rate
def show(self, km):
print(f'{self.name}: {self.fare(km)} 円')
class Taxi(Vehicle):
def fare(self, km):
return 500 + km * self.rate
プログラム 3(main.py)
# 継承とメソッドのオーバーライド
class Vehicle:
def __init__(self, name, rate):
self.name = name
self.rate = rate
def fare(self, km):
return km * self.rate
def show(self, km):
print(f'{self.name}: {self.fare(km)} 円')
class Taxi(Vehicle):
def fare(self, km):
return 500 + km * self.rate
Vehicle('train', 20).show(5)
Taxi('taxi', 80).show(5)
プログラム 4(main.py)
# 継承とメソッドのオーバーライド
class Taxi(Vehicle):
def __init__(self, name, rate, night):
self.night = night
def fare(self, km):
base = 500 + km * self.rate
if self.night:
return base + base // 5
return base
taxi = Taxi('taxi', 80, True)
taxi.show(5)
プログラム 5(main.py)
# 継承とメソッドのオーバーライド
class Vehicle:
def __init__(self, name, rate):
self.name = name
self.rate = rate
def show(self, km):
print(self.name, km * self.rate)
class Taxi(Vehicle):
def __init__(self, name, rate, night):
super().__init__(name, rate)
self.night = night
taxi = Taxi('taxi', 80, True)
taxi.show(5)
print(taxi.night)
プログラム 6(main.py)
# 継承とメソッドのオーバーライド
class Vehicle:
def __init__(self, name, rate):
self.name = name
self.rate = rate
def fare(self, km):
return km * self.rate
class Bus(Vehicle):
def fare(self, km):
return super().fare(km) + 100
bus = Bus('bus', 30)
print('bus:', bus.fare(5), '円')
プログラム 7(main.py)
# 継承とメソッドのオーバーライド
class Vehicle:
def __init__(self, name, rate):
self.name = name
self.rate = rate
def fare(self, km):
return km * self.rate
class Bus(Vehicle):
def fare(self, km):
return super().fare(km) + 100
プログラム 8(main.py)
# 継承とメソッドのオーバーライド
class Vehicle:
def __init__(self, name, rate):
self.name, self.rate = name, rate
def fare(self, km):
return km * self.rate
class Taxi(Vehicle):
def fare(self, km):
return 500 + km * self.rate
class Bus(Vehicle):
def fare(self, km):
return super().fare(km) + 100
for v in [Vehicle('train', 20), Taxi('taxi', 80), Bus('bus', 30)]:
print(f'{v.name}: {v.fare(10)} 円')
プログラム 9(main.py)
# 継承とメソッドのオーバーライド
class Vehicle:
def __init__(self, name, rate):
self.name, self.rate = name, rate
def show(self, km):
print(f'{self.name}: {self.fare(km)} 円')
class Taxi(Vehicle):
def __init__(self, name, rate, night):
super().__init__(name, rate)
self.night = night
def fare(self, km):
base = 500 + km * self.rate
return base + base // 5 if self.night else base
for t in [Taxi('taxi', 80, True), Taxi('day', 80, False)]: t.show(10)
このレクチャーで書いたプログラムです(書いた順)。コピーして手元で動かせます。
プログラム 1(main.py)
# 特殊メソッド(__str__・__eq__・__len__)
class Book:
def __init__(self, title, pages):
self.title = title
self.pages = pages
def __eq__(self, other):
if not isinstance(other, Book):
return False
return self.title == other.title and self.pages == other.pages
shelf = [Book('Cat Diary', 120), Book('Python Note', 240)]
print(Book('Python Note', 240) in shelf)
プログラム 2(main.py)
# 特殊メソッド(__str__・__eq__・__len__)
class Playlist:
def __init__(self, name, songs):
self.name = name
self.songs = songs
def _len_(self):
return len(self.songs)
drive = Playlist('drive', ['Blue Sky', 'Night Road', 'Sunrise'])
empty = Playlist('empty', [])
print(len(drive), len(empty))
if not empty:
print('empty は曲がありません')
プログラム 3(main.py)
# 特殊メソッド(__str__・__eq__・__len__)
class Playlist:
def __init__(self, name, songs):
self.name = name
self.songs = songs
def __str__(self):
return f'{self.name}: {len(self)}曲'
def __len__(self):
return len(self.songs)
def __eq__(self, other):
return isinstance(other, Playlist) and self.songs == other.songs
a = Playlist('drive', ['Blue Sky', 'Sunrise'])
b = Playlist('walk', ['Blue Sky', 'Sunrise', 'Rain'])
print(a, b, a == b, sep=' / ')
このレクチャーで書いたプログラムです(書いた順)。コピーして手元で動かせます。
プログラム 1(main.py)
# プロパティ(@property)とカプセル化
class Battery:
def __init__(self, level):
self._level = level
def get_level(self):
return self._level
def set_level(self, value):
if 0 <= value <= 100:
self._level = value
b = Battery(80)
b._level = 150
print(b.get_level())
プログラム 2(main.py)
# プロパティ(@property)とカプセル化
class Battery:
def __init__(self, level):
self.level = level
@property
def level(self):
return self._level
@level.setter
def level(self, value):
if not 0 <= value <= 100:
raise ValueError('0から100で指定してください')
self._level = value
try: Battery(150)
except ValueError as e: print(e)
プログラム 3(main.py)
# プロパティ(@property)とカプセル化
class Battery:
def __init__(self, level):
self._level = level
@property
def level(self):
return self.level
b = Battery(15)
try:
print(b.level)
except RecursionError:
print('RecursionError')
プログラム 4(main.py)
# プロパティ(@property)とカプセル化
class Speaker:
def __init__(self):
self._volume = 5
@property
def volume(self):
return self._volume
@volume.setter
def volume(self, value):
self._volume = max(0, min(value, 10))
sp = Speaker()
sp.volume = int(input('音量: '))
print(f'音量は {sp.volume} です')
このレクチャーで書いたプログラムです(書いた順)。コピーして手元で動かせます。
プログラム 1(main.py)
# データクラス(dataclass)
class Book:
def __init__(self, title, pages):
self.title = title
self.pages = pages
プログラム 2(main.py)
# データクラス(dataclass)
from dataclasses import dataclass
@dataclass
class Book:
title: str
pages: int
price: int = 1500
a = Book('Tea', 120)
b = Book('Cats', 80, price=900)
print(a)
print(b)
プログラム 3(main.py)
# データクラス(dataclass)
from dataclasses import dataclass
try:
@dataclass
class Book:
title: str
price: int = 1500
pages: int
except TypeError as e:
print(type(e).__name__)
プログラム 4(main.py)
# データクラス(dataclass)
from dataclasses import dataclass
class Shelf:
place: str
books: list = []
try:
dataclass(Shelf)
except ValueError as e:
print(type(e).__name__)
print(e)
プログラム 5(main.py)
# データクラス(dataclass)
from dataclasses import dataclass, field
@dataclass
class Shelf:
place: str
books: list = field(default_factory=list)
s1 = Shelf('home')
s2 = Shelf('office')
s1.books.append('Tea')
print(s1)
print(s2)
プログラム 6(main.py)
# データクラス(dataclass)
from dataclasses import dataclass
@dataclass
class Book:
title: str
pages: int
def days(self, per_day):
return self.pages // per_day
b = Book('Tea', 120)
print(b.days(30))
プログラム 7(main.py)
# データクラス(dataclass)
from dataclasses import dataclass
@dataclass(frozen=True)
class Book:
title: str
pages: int
b = Book('Tea', 120)
try:
b.pages = 200
except AttributeError as e:
print(e)
プログラム 8(main.py)
# データクラス(dataclass)
from dataclasses import dataclass
@dataclass(order=True)
class Book:
pages: int
title: str
books = [Book(300, 'Sea'), Book(120, 'Tea'), Book(120, 'Cats')]
for b in sorted(books):
print(b)
プログラム 9(main.py)
# データクラス(dataclass)
from dataclasses import dataclass
@dataclass
class Item:
name: str
price: int
qty: int = 1
def subtotal(self):
return self.price * self.qty
cart = [Item('milk', 180, 2), Item('bread', 250)]
for item in cart:
print(f'{item.name}: {item.subtotal()}')
print(f'合計: {sum([i.subtotal() for i in cart])}')
このレクチャーで書いたプログラムです(書いた順)。コピーして手元で動かせます。
プログラム 1(main.py)
# イテレータとジェネレータ(yield)
colors = ['red', 'green', 'blue']
it = iter(colors)
print(type(it))
print(next(it))
print(next(it))
print(next(it))
プログラム 2(main.py)
# イテレータとジェネレータ(yield)
it = iter(['red', 'green'])
next(it)
next(it)
try:
next(it)
except StopIteration:
print('StopIteration')
プログラム 3(main.py)
# イテレータとジェネレータ(yield)
it = iter(['red', 'green'])
for c in it:
print(c)
print(list(it))
プログラム 4(main.py)
# イテレータとジェネレータ(yield)
def steps():
yield 'start'
yield 'middle'
yield 'end'
g = steps()
print(type(g))
print(next(g))
print(next(g))
print(next(g))
プログラム 5(main.py)
# イテレータとジェネレータ(yield)
def steps():
print('A')
yield 1
print('B')
yield 2
print('C')
for v in steps():
print(v)
プログラム 6(main.py)
# イテレータとジェネレータ(yield)
def evens(limit):
n = 0
while n <= limit:
yield n
n += 2
print(sum(evens(4)))
print(sum(evens(4)))
プログラム 7(main.py)
# イテレータとジェネレータ(yield)
nums = (n * n for n in range(1, 6))
print(type(nums))
print(sum(nums))
print(sum(n * n for n in range(1, 6)))
プログラム 8(main.py)
# イテレータとジェネレータ(yield)
def serial():
n = 1
while True:
yield f'ID-{n:03}'
n += 1
gen = serial()
for i in range(3):
print(next(gen))
プログラム 9(main.py)
# イテレータとジェネレータ(yield)
def passed(scores, border):
for s in scores:
if s >= border:
yield s
data = [72, 45, 90, 58, 81]
border = int(input('基準点: '))
for s in passed(data, border):
print(s)
このレクチャーで書いたプログラムです(書いた順)。コピーして手元で動かせます。
プログラム 1(main.py)
# デコレータ
def wash():
print('洗濯します')
f = wash
f()
print(f.__name__)
def twice(func):
func()
func()
twice(wash)
プログラム 2(main.py)
# デコレータ
def announce(func):
def wrapper(*args, **kwargs):
print('--開始--')
result = func(*args, **kwargs)
print('--終了--')
return result
return wrapper
@announce
def fee(kg):
return kg * 300
print(fee.__name__)
プログラム 3(main.py)
# デコレータ
import functools
def announce(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print('--開始--')
return func(*args, **kwargs)
return wrapper
@announce
def fee(kg):
return kg * 300
print(fee.__name__)
プログラム 4(main.py)
# デコレータ
def repeat(times):
def decorator(func):
def wrapper(*args, **kwargs):
for _ in range(times):
func(*args, **kwargs)
return wrapper
return decorator
@repeat(3)
def rinse(item):
print(f'{item} をすすぎます')
rinse('shirt')
プログラム 5(main.py)
# デコレータ
def box(func):
def wrapper():
return f'[{func()}]'
return wrapper
def star(func):
def wrapper():
return f'*{func()}*'
return wrapper
@star
@box
def label():
return 'towel'
print(label())
プログラム 6(main.py)
# デコレータ
def count_calls(func):
calls = 0
def wrapper(*args, **kwargs):
nonlocal calls
calls += 1
print(f'{func.__name__}: {calls} 回目')
return func(*args, **kwargs)
return wrapper
@count_calls
def spin():
print('脱水します')
spin()
spin()
このレクチャーで書いたプログラムです(書いた順)。コピーして手元で動かせます。
プログラム 1(main.py)
# モジュールと import
import textkit
print(textkit.shout('hello'))
print(textkit.frame('menu'))
print(textkit.MARK)
プログラム 2(main.py)
# モジュールと import
from textkit import shout, frame
print(textkit.MARK)
プログラム 3(main.py)
# モジュールと import
import textkit as tk
from textkit import frame as box
print(tk.shout('bye'))
print(box('soup'))
プログラム 4(main.py)
# モジュールと import
import textkits
print(textkits.shout('oops'))
プログラム 5(main.py)
# モジュールと import
from textkit import shout
def shout(word):
return word + '?'
print(shout('hi'))
プログラム 6(main.py)
# モジュールと import
import textkit
import textkit
print('main:', __name__)
プログラム 7(main.py)
# モジュールと import
import string
print(string.ascii_uppercase)
print(string.digits)
プログラム 8(main.py)
# モジュールと import
from grade import judge, PASS_LINE
import textkit as tk
score = int(input('点数: '))
result = judge(score)
print(tk.frame(result))
print('合格ライン:', PASS_LINE)
プログラム 9(textkit.py)
# モジュールと import
MARK = '*'
def shout(word):
return word.upper() + '!'
def frame(word):
return MARK * 3 + word + MARK * 3
if __name__ == '__main__':
print(shout('test'))
プログラム 10(grade.py)
# モジュールと import
PASS_LINE = 80
def judge(score):
if score >= PASS_LINE:
return '合格'
return '不合格'
このレクチャーで書いたプログラムです(書いた順)。コピーして手元で動かせます。
プログラム 1(main.py)
# 標準ライブラリ:math と random
import math
x = 3.2
print(math.floor(x))
print(math.ceil(x))
y = -3.2
print(math.floor(y))
print(math.ceil(y))
プログラム 2(main.py)
# 標準ライブラリ:math と random
import math
items = 23
per_page = 5
print(items // per_page)
print(math.ceil(items / per_page))
プログラム 3(main.py)
# 標準ライブラリ:math と random
import math
r = float(input('半径: '))
area = math.pi * r ** 2
length = 2 * math.pi * r
print(f'面積: {area:.2f}')
print(f'円周: {length:.2f}')
プログラム 4(main.py)
# 標準ライブラリ:math と random
import math
print(math.gcd(12, 18))
print(math.lcm(4, 6))
print(0.1 + 0.2 == 0.3)
print(math.isclose(0.1 + 0.2, 0.3))
print(math.hypot(3, 4))
プログラム 5(main.py)
# 標準ライブラリ:math と random
import random
rolls = [random.randint(1, 6) for _ in range(1000)]
print(min(rolls), max(rolls))
others = [random.randrange(1, 6) for _ in range(1000)]
print(min(others), max(others))
プログラム 6(main.py)
# 標準ライブラリ:math と random
import random
random.seed(0)
print(random.random())
random.seed(0)
print(random.random())
プログラム 7(main.py)
# 標準ライブラリ:math と random
import random
colors = ['red', 'blue', 'green']
pick = random.choice(colors)
print(pick in colors)
cards = [1, 2, 3, 4, 5]
result = random.shuffle(cards)
print(result)
print(sorted(cards))
プログラム 8(main.py)
# 標準ライブラリ:math と random
import random
nums = random.sample(range(1, 44), 6)
print(len(nums))
print(len(set(nums)))
print(min(nums) >= 1 and max(nums) <= 43)
プログラム 9(main.py)
# 標準ライブラリ:math と random
import math
import random
total = 1000000
inside = 0
for _ in range(total):
x = random.random()
y = random.random()
if math.hypot(x, y) <= 1:
inside += 1
estimate = inside / total * 4
print(f'{estimate:.1f}')
print(f'{math.pi:.1f}')
このレクチャーで書いたプログラムです(書いた順)。コピーして手元で動かせます。
プログラム 1(main.py)
# 標準ライブラリ:datetime で日付と時刻
from datetime import date
release = date(2026, 4, 1)
print(release)
print(release.year, release.month, release.day)
print(release.weekday())
プログラム 2(main.py)
# 標準ライブラリ:datetime で日付と時刻
from datetime import datetime
start = datetime(2026, 12, 24, 18, 15)
end = datetime(2026, 12, 25, 1, 30)
print(start)
print(start.hour, start.minute)
span = end - start
print(span)
print(span.total_seconds() / 3600)
プログラム 3(main.py)
# 標準ライブラリ:datetime で日付と時刻
from datetime import datetime
start = datetime(2026, 12, 24, 18, 15)
print(start.strftime('%Y/%m/%d'))
print(start.strftime('%H:%M'))
print(f'開始 {start:%m/%d %H:%M}')
プログラム 4(main.py)
# 標準ライブラリ:datetime で日付と時刻
from datetime import datetime
text = '2026/12/24 18:15'
try:
party = datetime.strptime(text, '%Y-%m-%d %H:%M')
print(party)
except ValueError as e:
print(type(e).__name__)
print(text)
プログラム 5(main.py)
# 標準ライブラリ:datetime で日付と時刻
from datetime import datetime, date
base = date(2026, 10, 9)
text = input('締め切り (YYYY-MM-DD): ')
deadline = datetime.strptime(text, '%Y-%m-%d').date()
left = (deadline - base).days
names = ['月', '火', '水', '木', '金', '土', '日']
print(f'{deadline:%m/%d}', names[deadline.weekday()])
if left < 0:
print(f'{-left} 日過ぎています')
else:
print(f'あと {left} 日')
このレクチャーで書いたプログラムです(書いた順)。コピーして手元で動かせます。
プログラム 1(main.py)
# ファイルの読み書きと with 文
f = open('memo.txt', 'w', encoding='utf-8')
f.write('Buy milk')
f.close()
f = open('memo.txt', 'r', encoding='utf-8')
text = f.read()
f.close()
print(text)
プログラム 2(main.py)
# ファイルの読み書きと with 文
with open('memo.txt', 'w', encoding='utf-8') as f:
f.write('Buy eggs')
with open('memo.txt', encoding='utf-8') as f:
text = f.read()
print(text)
print(f.closed)
プログラム 3(main.py)
# ファイルの読み書きと with 文
with open('todo.txt', 'w', encoding='utf-8') as f:
f.write('wash\n')
with open('todo.txt', 'a', encoding='utf-8') as f:
f.write('cook\n')
with open('todo.txt', encoding='utf-8') as f:
print(f.read(), end='')
プログラム 4(main.py)
# ファイルの読み書きと with 文
with open('fruits.txt', 'w', encoding='utf-8') as f:
f.write('melon\npeach\ngrape')
with open('fruits.txt', encoding='utf-8') as f:
for line in f:
print(line.strip())
プログラム 5(main.py)
# ファイルの読み書きと with 文
count = 3
with open('count.txt', 'w', encoding='utf-8') as f:
f.write(str(count))
プログラム 6(main.py)
# ファイルの読み書きと with 文
with open('nothing.txt', encoding='utf-8') as f:
print(f.read())
プログラム 7(main.py)
# ファイルの読み書きと with 文
item1 = input('1つ目: ')
item2 = input('2つ目: ')
with open('shop.txt', 'w', encoding='utf-8') as f:
f.write(item1 + '\n')
f.write(item2 + '\n')
with open('shop.txt', encoding='utf-8') as f:
for line in f:
print('-', line.strip())
プログラム 8(main.py)
# ファイルの読み書きと with 文
with open('scores.txt', 'w', encoding='utf-8') as f:
for s in [72, 85, 90]:
f.write(str(s) + '\n')
total = 0
count = 0
with open('scores.txt', encoding='utf-8') as f:
for line in f:
total += int(line)
count += 1
print('合計:', total)
print(f'平均: {total / count:.1f}')
このレクチャーで書いたプログラムです(書いた順)。コピーして手元で動かせます。
プログラム 1(main.py)
# JSON と CSV の読み書き
import json
profile = {'name': 'Player1', 'level': 5, 'items': ['sword', 'shield']}
text = json.dumps(profile)
print(text)
print(type(text))
プログラム 2(main.py)
# JSON と CSV の読み書き
import json
pet = {'kind': 'ねこ', 'age': 3}
print(json.dumps(pet, ensure_ascii=False, indent=2))
プログラム 3(main.py)
# JSON と CSV の読み書き
import json
profile = {'name': 'Player1', 'level': 5, 'items': ['sword', 'shield']}
with open('save.json', 'w', encoding='utf-8') as f:
json.dump(profile, f, indent=2)
print('save.json に保存しました')
with open('save.json', encoding='utf-8') as f:
loaded = json.load(f)
print(loaded['items'][0])
print(loaded['level'] + 1)
プログラム 4(main.py)
# JSON と CSV の読み書き
import json
tags = {'red', 'blue'}
try:
print(json.dumps(tags))
except TypeError:
print('set は変換できません')
print(json.dumps(sorted(tags)))
プログラム 5(main.py)
# JSON と CSV の読み書き
import json
with open('settings.json', encoding='utf-8') as f:
settings = json.load(f)
print(settings)
print(settings['goal'] * 7)
プログラム 6(main.py)
# JSON と CSV の読み書き
import csv
with open('steps.csv', encoding='utf-8', newline='') as f:
reader = csv.reader(f)
for row in reader:
print(row)
プログラム 7(main.py)
# JSON と CSV の読み書き
import csv
total = 0
with open('steps.csv', encoding='utf-8', newline='') as f:
reader = csv.reader(f)
header = next(reader)
for row in reader:
total += int(row[1])
print(header)
print(f'合計: {total} 歩')
プログラム 8(main.py)
# JSON と CSV の読み書き
import csv
with open('steps.csv', encoding='utf-8', newline='') as f:
for row in csv.DictReader(f):
day = row['day']
steps = int(row['steps'])
print(f'{day}: {steps:,} 歩')
プログラム 9(main.py)
# JSON と CSV の読み書き
import csv
goal = 7000
rows = [['day', 'result']]
with open('steps.csv', encoding='utf-8', newline='') as f:
for r in csv.DictReader(f):
result = 'OK' if int(r['steps']) >= goal else 'NG'
rows.append([r['day'], result])
with open('report.csv', 'w', encoding='utf-8', newline='') as f:
writer = csv.writer(f)
writer.writerows(rows)
with open('report.csv', encoding='utf-8') as f:
print(f.read(), end='')
プログラム 10(main.py)
# JSON と CSV の読み書き
import csv
import json
with open('settings.json', encoding='utf-8') as f:
goal = json.load(f)['goal']
with open('steps.csv', encoding='utf-8', newline='') as f:
records = list(csv.DictReader(f))
for r in records:
r['steps'] = int(r['steps'])
r['ok'] = r['steps'] >= goal
with open('result.json', 'w', encoding='utf-8') as f:
json.dump(records, f, indent=2)
print(json.dumps(records[0]))
プログラム 11(settings.json)
{
"goal": 7000,
"unit": "steps"
}
プログラム 12(steps.csv)
day,steps
mon,6200
tue,8400
wed,5100
このレクチャーで書いたプログラムです(書いた順)。コピーして手元で動かせます。
プログラム 1(main.py)
# 正規表現(re)
import re
memo = 'Room 12, floor 3, ext 4051'
numbers = re.findall(r'\d+', memo)
print(numbers)
values = [int(n) for n in numbers]
print(sum(values))
プログラム 2(main.py)
# 正規表現(re)
import re
codes = 'A1 B22 C333 D4444'
print(re.findall(r'[A-Z]\d+', codes))
print(re.findall(r'[A-Z]\d{3}', codes))
words = 'color colour colouur'
print(re.findall(r'colou?r', words))
プログラム 3(main.py)
# 正規表現(re)
import re
note = 'no digits here'
found = re.search(r'\d+', note)
if found:
print(found.group())
else:
print('数字はありません')
プログラム 4(main.py)
# 正規表現(re)
import re
pattern = r'\d{3}-\d{4}'
for text in ['zip 123-4567', '123-4567', '123-45678']:
s = bool(re.search(pattern, text))
m = bool(re.match(pattern, text))
f = bool(re.fullmatch(pattern, text))
print(text, s, m, f)
プログラム 5(main.py)
# 正規表現(re)
import re
stamp = 'saved at 2025-03-18'
m = re.search(r'(\d{4})-(\d{2})-(\d{2})', stamp)
print(m.group())
print(m.group(1))
print(m.groups())
プログラム 6(main.py)
# 正規表現(re)
import re
pin = 'PIN 4821, room 305'
print(re.sub(r'\d', '*', pin))
day = '2025/03/18'
print(re.sub(r'(\d{4})/(\d{2})/(\d{2})', r'\3.\2.\1', day))
プログラム 7(main.py)
# 正規表現(re)
import re
tags = 'red, blue;green yellow'
print(tags.split(','))
print(re.split(r'[,;\s]+', tags))
プログラム 8(main.py)
# 正規表現(re)
import re
html = '<b>bold</b> and <i>it</i>'
print(re.findall(r'<.+>', html))
print(re.findall(r'<.+?>', html))
プログラム 9(main.py)
# 正規表現(re)
import re
pattern = r'(\d{4}-\d{2}-\d{2}) \d{2}:\d{2} ERROR (.+)'
with open('log.txt', encoding='utf-8') as f:
for line in f:
m = re.search(pattern, line)
if m:
print(m.group(1), m.group(2))
プログラム 10(log.txt)
2025-03-18 10:02 INFO start
2025-03-18 10:15 ERROR disk full
2025-03-19 09:40 INFO retry
2025-03-19 09:41 ERROR timeout
このレクチャーで書いたプログラムです(書いた順)。コピーして手元で動かせます。
プログラム 1(main.py)
# 型ヒント
def to_km(steps, stride):
return steps * stride / 1000
プログラム 2(main.py)
# 型ヒント
steps: int = 8000
stride: float = 0.75
day: str = '月曜日'
done: bool = True
プログラム 3(main.py)
# 型ヒント
goal: int = int(input('目標歩数: '))
print(type(goal))
print(goal - 8000)
プログラム 4(main.py)
# 型ヒント
count: int
print(count)
プログラム 5(main.py)
# 型ヒント
def to_km(steps: int, stride: float) -> float:
return steps * stride / 1000
km: float = to_km(8000, 0.75)
print(km)
print(to_km.__annotations__)
プログラム 6(main.py)
# 型ヒント
def to_km(steps: int, stride: float = 0.75) -> float:
return steps * stride / 1000
try:
print(to_km('10000'))
except TypeError as e:
print(type(e).__name__)
print(e)
プログラム 7(main.py)
# 型ヒント
def show_steps(day: str, steps: int) -> None:
print(f'{day}: {steps}歩')
show_steps('月曜日', 8000)
show_steps('火曜日', 6500)
プログラム 8(main.py)
# 型ヒント
week: list[int] = [8000, 6500, 12500]
goals: dict[str, int] = {'平日': 8000, '休日': 5000}
best: tuple[str, int] = ('水曜日', 12500)
history: list[int] = []
プログラム 9(main.py)
# 型ヒント
Steps = list[int]
week: Steps = [8000, 6500, 12500]
def average(records: Steps) -> float:
return sum(records) / len(records)
print(average(week))
プログラム 10(main.py)
# 型ヒント
goals: dict[str, int] = {'平日': 8000, '休日': 5000}
def get_goal(kind: str) -> int | None:
return goals.get(kind)
def judge(steps: int, kind: str) -> str:
goal: int | None = get_goal(kind)
if goal is None:
return '目標なし'
return '達成' if steps >= goal else '未達'
print(judge(9000, '平日'))
print(judge(4000, '休日'))
print(judge(7000, '祝日'))
このレクチャーで書いたプログラムです(書いた順)。コピーして手元で動かせます。
プログラム 1(main.py)
# 総仕上げ:小さなアプリを作る
import budget
records = list(budget.load('expenses.csv'))
print(records)
プログラム 2(main.py)
# 総仕上げ:小さなアプリを作る
import budget
try:
records = list(budget.load('expense.csv'))
except FileNotFoundError as e:
print(type(e).__name__)
print(e.filename)
プログラム 3(main.py)
# 総仕上げ:小さなアプリを作る
import budget
records = list(budget.load('expenses.csv'))
while True:
text = input('費目,金額: ')
if text == 'q':
break
kind, price = text.split(',')
records.append((kind, int(price)))
budget.report(records)
プログラム 4(main.py)
# 総仕上げ:小さなアプリを作る
import budget
records = budget.load('expenses.csv')
while True:
text = input('費目,金額: ')
if text == 'q':
break
kind, price = text.split(',')
records.append((kind, int(price)))
budget.report(records)
プログラム 5(main.py)
# 総仕上げ:小さなアプリを作る
import budget
records = list(budget.load('expenses.csv'))
while True:
text = input('費目,金額: ')
if text == 'q':
break
try:
kind, price = text.split(',')
records.append((kind, int(price)))
except ValueError:
print('food,500 のように入力してください')
budget.report(records)
プログラム 6(expenses.csv)
food,450
book,1200
food,380
bus,220
cafe,350
プログラム 7(budget.py)
# 総仕上げ:小さなアプリを作る
def load(filename):
with open(filename, encoding='utf-8') as f:
for line in f:
if not line.startswith('#'):
kind, price = line.strip().split(',')
yield kind, int(price)
def report(records):
totals = {}
for kind, price in records:
totals[kind] = totals.get(kind, 0) + price
for kind in sorted(totals, key=totals.get, reverse=True):
print(f'{kind:<6}{totals[kind]:>6,}円')
X(@programing_uni)で、この講座の最安値クーポンを定期的に発行しています。
本コースにはAIの使用が含まれています。
■ AI の利用について
このコースの制作には、次のとおり AI ツールを使用しています。
・原稿(ナレーション)とサンプルコード:AI(Anthropic の Claude)で下書きを作り、講師が設計した構成と品質基準に沿って確認・修正しています
・ナレーション音声:Microsoft の音声合成による合成音声です。講師本人の声ではありません
・画面右下のアバター:Zoom のバーチャルアバター機能による映像です。講師本人の映像ではありません
・図解:AI が作った図の指示をもとに PowerPoint で作成しています
・字幕:音声認識(AI)で時刻を合わせています
すべてのサンプルコードは実際に実行しており、画面に映る結果は実際の実行結果です。
AIがコードを書いてくれる時代になりました。それでも、AIが出したコードが正しいかを判断し、動かないときに自分で直せる人と、そうでない人の差は大きく開いています。いま求められているのは「コードを書く力」以上に、「コードを読んで、見抜いて、直せる力」です。
このコースでは、Python をゼロから学びます。すべてのレッスンで、実際に VS Code にコードを書き、ターミナルで実行し、結果を確かめながら進みます。「なんとなく分かった」で終わらせず、なぜその結果になるのかを一つずつ解説します。
■ このコースで学べること
・変数と代入、数値・文字列、型変換と入力
・条件分岐(if・match)とくり返し(for・while)
・リスト・タプル・辞書・集合、内包表記、enumerate と zip
・関数と引数、スコープ、再帰、lambda
・例外処理(try・except・finally・raise)と自作の例外
・クラスとオブジェクト指向(継承・特殊メソッド・プロパティ・データクラス)
・イテレータ・ジェネレータ・デコレータ
・モジュールと標準ライブラリ、ファイル・JSON・CSV の読み書き、正規表現、型ヒント
・総仕上げとして小さなアプリを作る
■ このコースの特長
・初心者がつまずきやすいポイント(参照の共有、型の違い、エラーの読み方など)を先回りして解説
・エラーをあえて出して見せ、原因の見つけ方と直し方を体験できる
・すべてのコードを手元で同じように動かして確かめられる
■ こんな方におすすめ
・プログラミングを初めて学ぶ方
・独学で挫折した経験がある方
・AIを「使われる側」ではなく「使いこなす側」になりたい方