├── .gitignore ├── README.md ├── hisshu.jpg ├── jissen.jpg ├── やってみよう_実践編 ├── README.md ├── chapter04 │ ├── 4_1_cubes5.png │ ├── 4_1_cubes5.py │ ├── 4_1_cubes5000.png │ ├── 4_1_cubes5000.py │ ├── 4_2_colored_cubes.png │ ├── 4_2_colored_cubes.py │ ├── 4_3_molecular_motion.png │ ├── 4_3_molecular_motion.py │ ├── 4_5_random_walk.py │ ├── 4_6_d8_d8.html │ ├── 4_6_d8_d8.py │ ├── 4_7_3d6.html │ ├── 4_7_3d6.py │ ├── 4_8_d6xd6.html │ ├── 4_8_d6xd6.py │ ├── 4_9_d6_d6.html │ ├── 4_9_die_comprehension.py │ ├── die.py │ └── random_walk.py ├── chapter05 │ ├── 5_1_sitka_rainfall.png │ ├── 5_1_sitka_rainfall.py │ ├── 5_2_death_valley_highs_lows.png │ ├── 5_2_death_valley_highs_lows.py │ ├── 5_2_sitka_death_valley.png │ ├── 5_2_sitka_death_valley.py │ ├── 5_2_sitka_highs_lows.png │ ├── 5_2_sitka_highs_lows.py │ ├── 5_4_auto_indexes.png │ ├── 5_4_auto_indexes.py │ ├── 5_6_global_earthquakes.html │ ├── 5_7_auto_title.py │ ├── 5_7_global_earthquakes.html │ ├── 5_9_world_fires.html │ ├── 5_9_world_fires.py │ └── data │ │ ├── death_valley_2018_simple.csv │ │ ├── eq_data_30_day_m1.json │ │ ├── sitka_weather_2018_simple.csv │ │ └── world_fires_1_day.csv └── chapter06 │ ├── 6_1_other_languages.py │ ├── 6_2_active_discussions.py │ ├── 6_3_test_python_repos.py │ ├── hn_discussions.html │ ├── js_repos.html │ ├── python_repos.html │ └── python_repos.py ├── やってみよう_必修編 ├── README.md ├── chapter02 │ ├── 2_10_adding_comments.py │ ├── 2_1_simple_message.py │ ├── 2_2_simple_messages.py │ ├── 2_3_personal_message.py │ ├── 2_4_name_cases.py │ ├── 2_5_famous_quote.py │ ├── 2_6_famous_quote2.py │ ├── 2_7_stripping_names.py │ ├── 2_8_number_eight.oy │ └── 2_9_favorite_number.py ├── chapter03 │ ├── 3_1_names.py │ ├── 3_2_greetings.py │ ├── 3_3_your_own_list.py │ ├── 3_4_guest_list.py │ ├── 3_5_changing_guest_list.py │ ├── 3_6_more_guests.py │ ├── 3_7_shrinking_guest_list.py │ └── 3_8_seeing_the_world.py ├── chapter04 │ ├── 4_10_slices.py │ ├── 4_11_my_pizzas_your_pizzas.py │ ├── 4_12_more_loops.py │ ├── 4_13_buffet.py │ ├── 4_1_pizzas.py │ ├── 4_2_animals.py │ ├── 4_3_counting_to_twenty.py │ ├── 4_4_one_million.py │ ├── 4_5_summing_a_million.py │ ├── 4_6_odd_numbers.py │ ├── 4_7_threes.py │ ├── 4_8_cubes.py │ └── 4_9_cube_comprehension.py ├── chapter05 │ ├── 5_10_checking_usernames.py │ ├── 5_11_ordinal_numbers.py │ ├── 5_1_conditional_tests.py │ ├── 5_3_alien_colors1_false.py │ ├── 5_3_alien_colors1_true.py │ ├── 5_4_alien_colors2_else.py │ ├── 5_4_alien_colors2_if.py │ ├── 5_5_alien_colors3_elif.py │ ├── 5_5_alien_colors3_else.py │ ├── 5_5_alien_colors3_if.py │ ├── 5_6_stages_of_life.py │ ├── 5_7_favorite_fruit.py │ ├── 5_8_hello_admin.py │ └── 5_9_no_users.py ├── chapter06 │ ├── 6_10_favorite_numbers.py │ ├── 6_11_cities.py │ ├── 6_1_person.py │ ├── 6_2_favorite_numbers.py │ ├── 6_3_glossary.py │ ├── 6_4_glossary2.py │ ├── 6_5_rivers.py │ ├── 6_6_polling.py │ ├── 6_7_people.py │ ├── 6_8_pets.py │ └── 6_9_favorite_places.py ├── chapter07 │ ├── 7_10_dream_vacation.py │ ├── 7_1_rental_car.py │ ├── 7_2_restaurant_seating.py │ ├── 7_3_multiples_of_ten.py │ ├── 7_4_pizza_toppings.py │ ├── 7_5_movie_tickets.py │ ├── 7_6_three_exits.py │ ├── 7_7_infinity.py │ ├── 7_8_deli.py │ └── 7_9_no_pastrami.py ├── chapter08 │ ├── 8_10_sending_messages.py │ ├── 8_11_archived_messages.py │ ├── 8_12_sandwiches.py │ ├── 8_13_user_profile.py │ ├── 8_14_cars.py │ ├── 8_15_printing_models.py │ ├── 8_1_message.py │ ├── 8_2_favorite_book.py │ ├── 8_3_tshirt.py │ ├── 8_4_large_shirts.py │ ├── 8_5_cities.py │ ├── 8_6_citi_names.py │ ├── 8_7_album.py │ ├── 8_8_user_albums.py │ ├── 8_9_messages.py │ └── printing_functions.py ├── chapter09 │ ├── 9_10_imported_restaurant.py │ ├── 9_11_imported_admin.py │ ├── 9_12_multiple_modules.py │ ├── 9_13_dice.py │ ├── 9_14_lottery.py │ ├── 9_15_lottery_analysis.py │ ├── 9_1_restaurant.py │ ├── 9_2_three_restaurants.py │ ├── 9_3_users.py │ ├── 9_4_number_served.py │ ├── 9_5_login_attempts.py │ ├── 9_6_ice_cream_stand.py │ ├── 9_7_admin.py │ ├── 9_8_privileges.py │ ├── 9_9_battery_upgrade.py │ ├── admin.py │ ├── restaurant.py │ ├── user.py │ └── user2.py ├── chapter10 │ ├── 10_10_common_words.py │ ├── 10_11_favorite_number_read.py │ ├── 10_11_favorite_number_write.py │ ├── 10_12_favorite_number_remembered.py │ ├── 10_13_verify_user.py │ ├── 10_13_verify_user_cleaner.py │ ├── 10_1_learning_python.py │ ├── 10_2_learning_c.py │ ├── 10_3_guest.py │ ├── 10_4_guest_book.py │ ├── 10_5_programming_poll.py │ ├── 10_6_addition.py │ ├── 10_7_addition_calculator.py │ ├── 10_8_cats_and_dogs.py │ ├── 10_9_silent_cats_and_dogs.py │ ├── alice.txt │ ├── cats.txt │ ├── dogs.txt │ ├── favorite_number.json │ ├── guest.txt │ ├── guest_book.txt │ ├── learning_python.txt │ ├── programming_poll.txt │ └── username.json └── chapter11 │ ├── 11_1_test_cities.py │ ├── 11_2_test_cities.py │ ├── 11_3_test_employee.py │ ├── city_functions.py │ ├── city_functions2.py │ └── employee.py ├── 実践編 ├── appendixB │ └── mpl_squares.py ├── chapter01 │ ├── 1_ゲームのプロジェクトを開始する │ │ ├── alien_invasion.py │ │ └── settings.py │ ├── 2_宇宙船の画像を追加する │ │ ├── alien_invasion.py │ │ ├── images │ │ │ └── ship.bmp │ │ ├── settings.py │ │ └── ship.py │ ├── 3_リファクタリング │ │ ├── alien_invasion.py │ │ ├── images │ │ │ └── ship.bmp │ │ ├── settings.py │ │ └── ship.py │ ├── 4_宇宙船を操縦する │ │ ├── alien_invasion.py │ │ ├── images │ │ │ └── ship.bmp │ │ ├── settings.py │ │ └── ship.py │ └── 5_弾を発射する │ │ ├── alien_invasion.py │ │ ├── bullet.py │ │ ├── images │ │ └── ship.bmp │ │ ├── settings.py │ │ └── ship.py ├── chapter02 │ ├── 1_最初のエイリアンを生成する │ │ ├── alien.py │ │ ├── alien_invasion.py │ │ ├── bullet.py │ │ ├── images │ │ │ ├── alien.bmp │ │ │ └── ship.bmp │ │ ├── settings.py │ │ └── ship.py │ ├── 2_エイリアンの艦隊を編成する │ │ ├── alien.py │ │ ├── alien_invasion.py │ │ ├── bullet.py │ │ ├── images │ │ │ ├── alien.bmp │ │ │ └── ship.bmp │ │ ├── settings.py │ │ └── ship.py │ ├── 3_艦隊を動かす │ │ ├── alien.py │ │ ├── alien_invasion.py │ │ ├── bullet.py │ │ ├── images │ │ │ ├── alien.bmp │ │ │ └── ship.bmp │ │ ├── settings.py │ │ └── ship.py │ ├── 4_エイリアンを撃つ │ │ ├── alien.py │ │ ├── alien_invasion.py │ │ ├── bullet.py │ │ ├── images │ │ │ ├── alien.bmp │ │ │ └── ship.bmp │ │ ├── settings.py │ │ └── ship.py │ └── 5_ゲームを終了する │ │ ├── alien.py │ │ ├── alien_invasion.py │ │ ├── bullet.py │ │ ├── game_stats.py │ │ ├── images │ │ ├── alien.bmp │ │ └── ship.bmp │ │ ├── settings.py │ │ └── ship.py ├── chapter03 │ ├── 1_Playボタンを追加する │ │ ├── alien.py │ │ ├── alien_invasion.py │ │ ├── bullet.py │ │ ├── button.py │ │ ├── game_stats.py │ │ ├── images │ │ │ ├── alien.bmp │ │ │ └── ship.bmp │ │ ├── settings.py │ │ └── ship.py │ ├── 2_ゲームをリセットする │ │ ├── alien.py │ │ ├── alien_invasion.py │ │ ├── bullet.py │ │ ├── button.py │ │ ├── game_stats.py │ │ ├── images │ │ │ ├── alien.bmp │ │ │ └── ship.bmp │ │ ├── settings.py │ │ └── ship.py │ ├── 3_レベルアップする │ │ ├── alien.py │ │ ├── alien_invasion.py │ │ ├── bullet.py │ │ ├── button.py │ │ ├── game_stats.py │ │ ├── images │ │ │ ├── alien.bmp │ │ │ └── ship.bmp │ │ ├── settings.py │ │ └── ship.py │ └── 4_得点を表示する │ │ ├── alien.py │ │ ├── alien_invasion.py │ │ ├── bullet.py │ │ ├── button.py │ │ ├── game_stats.py │ │ ├── images │ │ ├── alien.bmp │ │ └── ship.bmp │ │ ├── org │ │ ├── alien.py │ │ ├── alien_invasion.py │ │ ├── bullet.py │ │ ├── button.puy │ │ ├── button.py │ │ ├── game_stats.py │ │ ├── scoreboard.py │ │ ├── settings.py │ │ └── ship.py │ │ ├── scoreboard.py │ │ ├── settings.py │ │ └── ship.py ├── chapter04 │ ├── 1_簡単な折れ線グラフを描画する │ │ ├── mpl_squares.py │ │ └── scatter_squares.py │ ├── 2_ランダムウォーク │ │ ├── random_walk.py │ │ └── rw_visual.py │ └── 3_Plotlyでサイコロを転がす │ │ ├── d6.html │ │ ├── d6_d10.html │ │ ├── d6_d6.html │ │ ├── dice_visual.py │ │ ├── dice_visual_different_sizes.py │ │ ├── die.py │ │ └── die_visual.py ├── chapter05 │ ├── 1_CSVファイル形式 │ │ ├── data │ │ │ ├── death_valley_2018_full.csv │ │ │ ├── death_valley_2018_simple.csv │ │ │ ├── sitka_weather_07-2018_simple.csv │ │ │ ├── sitka_weather_2018_full.csv │ │ │ └── sitka_weather_2018_simple.csv │ │ ├── death_valley_highs_lows.py │ │ ├── sitka_highs.py │ │ └── sitka_highs_lows.py │ └── 2_地球全体のデータセットを地図に描画する │ │ ├── data │ │ ├── eq_data_1_day_m1.json │ │ ├── eq_data_30_day_m1.json │ │ ├── eq_data_7_day_m1.json │ │ ├── readable_eq_data.json │ │ ├── world_fires_1_day.csv │ │ └── world_fires_7_day.csv │ │ ├── eq_explore_data.py │ │ ├── global_earthquakes.html │ │ └── show_color_scales.py ├── chapter06 │ ├── 1_Web APIを使う │ │ └── python_repos.py │ ├── 2_Plotlyを使ってリポジトリを可視化する │ │ └── python_repos_visual.py │ └── 3_Hacker NewsのAPI │ │ ├── hn_article.py │ │ └── hn_submissions.py ├── chapter07 │ ├── 2_アプリケーションを開始する │ │ └── learning_log │ │ │ ├── learning_log │ │ │ └── settings.py │ │ │ └── learning_logs │ │ │ ├── admin.py │ │ │ └── models.py │ ├── 3_ページを作成する:学習ノートのホームページ │ │ └── learning_log │ │ │ ├── learning_log │ │ │ └── urls.py │ │ │ └── learning_logs │ │ │ ├── templates │ │ │ └── learning_logs │ │ │ │ └── index.html │ │ │ ├── urls.py │ │ │ └── views.py │ └── 4_追加のページを作成する │ │ └── learning_log │ │ └── learning_logs │ │ ├── templates │ │ └── learning_logs │ │ │ ├── base.html │ │ │ ├── index.html │ │ │ ├── topic.html │ │ │ └── topics.html │ │ ├── urls.py │ │ └── views.py ├── chapter08 │ ├── 1_ユーザーがデータを入力できるようにする │ │ └── learning_log │ │ │ └── learning_logs │ │ │ ├── forms.py │ │ │ ├── templates │ │ │ └── learning_logs │ │ │ │ ├── edit_entry.html │ │ │ │ ├── new_entry.html │ │ │ │ ├── new_topic.html │ │ │ │ ├── topic.html │ │ │ │ └── topics.html │ │ │ ├── urls.py │ │ │ └── views.py │ ├── 2_ユーザーアカウントを設定する │ │ └── learning_log │ │ │ ├── learning_log │ │ │ ├── settings.py │ │ │ └── urls.py │ │ │ ├── learning_logs │ │ │ └── templates │ │ │ │ └── learning_logs │ │ │ │ └── base.html │ │ │ └── users │ │ │ ├── templates │ │ │ └── registration │ │ │ │ ├── logged_out.html │ │ │ │ ├── login.html │ │ │ │ └── register.html │ │ │ ├── urls.py │ │ │ └── views.py │ └── 3_ユーザーが自分のデータを持てるようにする │ │ └── learning_log │ │ ├── learning_log │ │ └── settings.py │ │ └── learning_logs │ │ ├── models.py │ │ └── views.py └── chapter09 │ ├── 1_「学習ノート」にスタイルを設定する │ └── learning_log │ │ ├── learning_log │ │ └── settings.py │ │ ├── learning_logs │ │ └── templates │ │ │ └── learning_logs │ │ │ ├── base.html │ │ │ ├── index.html │ │ │ ├── topic.html │ │ │ └── topics.html │ │ └── users │ │ └── templates │ │ └── registration │ │ └── login.html │ └── 2_「学習ノート」をデプロイする │ └── learning_log │ ├── .gitignore │ ├── Procfile │ ├── learning_log │ └── settings.py │ ├── learning_logs │ └── views.py │ ├── requirements.txt │ ├── runtime.txt │ └── templates │ ├── 404.html │ └── 500.html └── 必修編 ├── chapter01 ├── Python3.sublime-build └── hello_world.py ├── chapter02 ├── apostrophe.py ├── comment.py ├── full_name.py ├── hello_world.py └── name.py ├── chapter03 ├── bicycles.py ├── cars.py └── motorcycles.py ├── chapter04 ├── dimensions.py ├── even_numbers.py ├── first_numbers.py ├── foods.py ├── magicians.py ├── players.py └── squares.py ├── chapter05 ├── amusement_park.py ├── banned_users.py ├── cars.py ├── magic_number.py ├── toppings.py └── voting.py ├── chapter06 ├── alien.py ├── alien_no_points.py ├── aliens.py ├── favorite_languages.py ├── many_users.py ├── pizza.py └── user.py ├── chapter07 ├── cities.py ├── confirmed_users.py ├── counting.py ├── even_or_odd.py ├── greeter.py ├── mountain_poll.py ├── parrot.py ├── pets.py └── rollercoaster.py ├── chapter08 ├── formatted_name.py ├── greet_users.py ├── greeter.py ├── making_pizzas.py ├── person.py ├── pets.py ├── pizza.py ├── printing_models.py └── user_profile.py ├── chapter09 ├── car.py ├── dog.py ├── electric_car.py └── クラスをインポートする │ ├── car.py │ ├── my_car.py │ ├── my_cars.py │ └── my_electric_car.py ├── chapter10 ├── alice.py ├── alice.txt ├── division_calculator.py ├── file_reader.py ├── greet_user.py ├── little_women.txt ├── moby_dick.txt ├── number_reader.py ├── number_writer.py ├── pi_digits.txt ├── pi_million_digits.txt ├── pi_string.py ├── remember_me.py ├── word_count.py └── write_message.py ├── chapter11 ├── language_survey.py ├── name_function.py ├── names.py ├── survey.py ├── test_name_function.py └── test_survey.py └── インストール手順 ├── linux.md ├── macos.md ├── win-install.png └── windows.md /hisshu.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/takanory/saitan-python/8196a91a9aac5011bc29782381b93f143b0ae25a/hisshu.jpg -------------------------------------------------------------------------------- /jissen.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/takanory/saitan-python/8196a91a9aac5011bc29782381b93f143b0ae25a/jissen.jpg -------------------------------------------------------------------------------- /やってみよう_実践編/README.md: -------------------------------------------------------------------------------- 1 | # 実践編の「やってみよう」の回答例 2 | 3 | 書籍「最短距離でゼロからしっかり学ぶPython入門 実践編」の演習問題「やってみよう」の回答例です。 4 | -------------------------------------------------------------------------------- /やってみよう_実践編/chapter04/4_1_cubes5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/takanory/saitan-python/8196a91a9aac5011bc29782381b93f143b0ae25a/やってみよう_実践編/chapter04/4_1_cubes5.png -------------------------------------------------------------------------------- /やってみよう_実践編/chapter04/4_1_cubes5.py: -------------------------------------------------------------------------------- 1 | from matplotlib import pyplot as plt 2 | 3 | # データを定義する 4 | x_values = [1, 2, 3, 4, 5] 5 | cubes = [x**3 for x in x_values] 6 | 7 | # プロットを作成する 8 | plt.style.use('seaborn') 9 | fig, ax = plt.subplots() 10 | ax.scatter(x_values, cubes, edgecolor='none', s=40) 11 | 12 | # グラフのタイトルと軸ラベルを設定する 13 | ax.set_title("Cubes", fontsize=24) 14 | ax.set_xlabel('Value', fontsize=14) 15 | ax.set_ylabel('Cube of Value', fontsize=14) 16 | 17 | # 軸のメモリラベルを設定する 18 | ax.tick_params(axis='both', labelsize=14) 19 | 20 | # グラフを表示する 21 | # plt.savefig('4_1_cubes5.png') 22 | plt.show() 23 | -------------------------------------------------------------------------------- /やってみよう_実践編/chapter04/4_1_cubes5000.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/takanory/saitan-python/8196a91a9aac5011bc29782381b93f143b0ae25a/やってみよう_実践編/chapter04/4_1_cubes5000.png -------------------------------------------------------------------------------- /やってみよう_実践編/chapter04/4_1_cubes5000.py: -------------------------------------------------------------------------------- 1 | from matplotlib import pyplot as plt 2 | 3 | # データを定義する 4 | x_values = list(range(1, 5001)) 5 | cubes = [x**3 for x in x_values] 6 | 7 | # プロットを作成する 8 | plt.style.use('seaborn') 9 | fig, ax = plt.subplots() 10 | ax.scatter(x_values, cubes, edgecolor='none', s=10) 11 | 12 | # グラフのタイトルと軸ラベルを設定する 13 | ax.set_title("Cubes", fontsize=24) 14 | ax.set_xlabel('Value', fontsize=14) 15 | ax.set_ylabel('Cube of Value', fontsize=14) 16 | 17 | # 軸のメモリラベルを設定する 18 | ax.tick_params(axis='both', labelsize=14) 19 | 20 | # グラフを表示する 21 | # plt.savefig('4_1_cubes5000.png') 22 | plt.show() 23 | -------------------------------------------------------------------------------- /やってみよう_実践編/chapter04/4_2_colored_cubes.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/takanory/saitan-python/8196a91a9aac5011bc29782381b93f143b0ae25a/やってみよう_実践編/chapter04/4_2_colored_cubes.png -------------------------------------------------------------------------------- /やってみよう_実践編/chapter04/4_2_colored_cubes.py: -------------------------------------------------------------------------------- 1 | from matplotlib import pyplot as plt 2 | 3 | # データを定義する 4 | x_values = list(range(1, 5001)) 5 | cubes = [x**3 for x in x_values] 6 | 7 | # プロットを作成する 8 | plt.style.use('seaborn') 9 | fig, ax = plt.subplots() 10 | ax.scatter(x_values, cubes, c=cubes, cmap=plt.cm.Greens, s=10) 11 | 12 | # グラフのタイトルと軸ラベルを設定する 13 | ax.set_title("Cubes", fontsize=24) 14 | ax.set_xlabel('Value', fontsize=14) 15 | ax.set_ylabel('Cube of Value', fontsize=14) 16 | 17 | # 軸のメモリラベルを設定する 18 | ax.tick_params(axis='both', labelsize=14) 19 | 20 | # グラフを表示する 21 | # plt.savefig('4_2_colored_cubes.png') 22 | plt.show() 23 | -------------------------------------------------------------------------------- /やってみよう_実践編/chapter04/4_3_molecular_motion.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/takanory/saitan-python/8196a91a9aac5011bc29782381b93f143b0ae25a/やってみよう_実践編/chapter04/4_3_molecular_motion.png -------------------------------------------------------------------------------- /やってみよう_実践編/chapter04/4_3_molecular_motion.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | 3 | from random_walk import RandomWalk 4 | 5 | # プログラムが動作している間、新しいランダムウォークを作成しつづける 6 | while True: 7 | # ランダムウォークを作成する 8 | rw = RandomWalk(5_000) 9 | rw.fill_walk() 10 | 11 | # ランダムウォークの点を描画する 12 | plt.style.use('classic') 13 | fig, ax = plt.subplots(figsize=(15, 9)) 14 | point_numbers = range(rw.num_points) 15 | ax.plot(rw.x_values, rw.y_values, linewidth=1, zorder=1) 16 | 17 | # 開始点と終了点を強調する 18 | # zorder引数を指定して、折れ線グラフの前に点を表示する 19 | ax.scatter(0, 0, c='green', edgecolors='none', s=100, zorder=2) 20 | ax.scatter(rw.x_values[-1], rw.y_values[-1], c='red', edgecolors='none', 21 | s=100, zorder=2) 22 | 23 | # 軸を削除する 24 | ax.get_xaxis().set_visible(False) 25 | ax.get_yaxis().set_visible(False) 26 | 27 | # plt.savefig('4_3_molecular_motion.png') 28 | plt.show() 29 | 30 | keep_running = input("別のランダムウォークを生成する?(y/n): ") 31 | if keep_running == 'n': 32 | break 33 | -------------------------------------------------------------------------------- /やってみよう_実践編/chapter04/4_5_random_walk.py: -------------------------------------------------------------------------------- 1 | from random import choice 2 | 3 | class RandomWalk: 4 | """ランダムウォークを生成するためのクラス""" 5 | 6 | def __init__(self, num_points=5000): 7 | """ランダムウォークの属性を初期化する""" 8 | self.num_points = num_points 9 | 10 | # すべてのランダムウォークは(0, 0)から開始する 11 | self.x_values = [0] 12 | self.y_values = [0] 13 | 14 | def get_step(self): 15 | """各ステップの方向と距離を決定する""" 16 | direction = choice([1, -1]) 17 | distance = choice([0, 1, 2, 3, 4]) 18 | step = direction * distance 19 | return step 20 | 21 | def fill_walk(self): 22 | """ランダムウォークのすべての点を計算する""" 23 | 24 | # ステップ数が指定した数になるまでランダムウォークを続ける 25 | while len(self.x_values) < self.num_points: 26 | 27 | # 移動する方向と距離を決定する 28 | x_step = self.get_step() 29 | y_step = self.get_step() 30 | 31 | # どこにも移動しない場合は結果を破棄する 32 | if x_step == 0 and y_step == 0: 33 | continue 34 | 35 | # 新しい位置を計算する 36 | x = self.x_values[-1] + x_step 37 | y = self.y_values[-1] + y_step 38 | 39 | self.x_values.append(x) 40 | self.y_values.append(y) 41 | -------------------------------------------------------------------------------- /やってみよう_実践編/chapter04/4_6_d8_d8.py: -------------------------------------------------------------------------------- 1 | from plotly.graph_objs import Bar, Layout 2 | from plotly import offline 3 | 4 | from die import Die 5 | 6 | # 2つの8面サイコロを作成する 7 | die_1 = Die(num_sides=8) 8 | die_2 = Die(num_sides=8) 9 | 10 | # サイコロを転がし、結果をリストに格納する 11 | results = [] 12 | for roll_num in range(1_000_000): 13 | result = die_1.roll() + die_2.roll() 14 | results.append(result) 15 | 16 | # 結果を分析する 17 | frequencies = [] 18 | max_result = die_1.num_sides + die_2.num_sides 19 | for value in range(2, max_result+1): 20 | frequency = results.count(value) 21 | frequencies.append(frequency) 22 | 23 | # 結果を可視化する 24 | x_values = list(range(2, max_result+1)) 25 | data = [Bar(x=x_values, y=frequencies)] 26 | 27 | x_axis_config = {'title': '結果', 'dtick': 1} 28 | y_axis_config = {'title': '発生した回数'} 29 | my_layout = Layout(title='2つの8面サイコロを1,000,000回転がした結果', 30 | xaxis=x_axis_config, yaxis=y_axis_config) 31 | offline.plot({'data': data, 'layout': my_layout}, filename='4_6_d8_d8.html') 32 | -------------------------------------------------------------------------------- /やってみよう_実践編/chapter04/4_7_3d6.py: -------------------------------------------------------------------------------- 1 | from plotly.graph_objs import Bar, Layout 2 | from plotly import offline 3 | 4 | from die import Die 5 | 6 | # 3つの6面サイコロを作成する 7 | die_1 = Die() 8 | die_2 = Die() 9 | die_3 = Die() 10 | 11 | # サイコロを転がし、結果をリストに格納する 12 | results = [] 13 | for roll_num in range(1_000_000): 14 | result = die_1.roll() + die_2.roll() + die_3.roll() 15 | results.append(result) 16 | 17 | # 結果を分析する 18 | frequencies = [] 19 | max_result = die_1.num_sides + die_2.num_sides + die_3.num_sides 20 | for value in range(3, max_result+1): 21 | frequency = results.count(value) 22 | frequencies.append(frequency) 23 | 24 | # 結果を可視化する 25 | x_values = list(range(3, max_result+1)) 26 | data = [Bar(x=x_values, y=frequencies)] 27 | 28 | x_axis_config = {'title': '結果', 'dtick': 1} 29 | y_axis_config = {'title': '発生した回数'} 30 | my_layout = Layout(title='3つの6面サイコロを1,000,000回転がした結果', 31 | xaxis=x_axis_config, yaxis=y_axis_config) 32 | offline.plot({'data': data, 'layout': my_layout}, filename='4_7_3d6.html') 33 | -------------------------------------------------------------------------------- /やってみよう_実践編/chapter04/4_8_d6xd6.py: -------------------------------------------------------------------------------- 1 | from plotly.graph_objs import Bar, Layout 2 | from plotly import offline 3 | 4 | from die import Die 5 | 6 | # 2つの6面サイコロを作成する 7 | die_1 = Die() 8 | die_2 = Die() 9 | 10 | # サイコロを転がし、結果をリストに格納する 11 | results = [] 12 | for roll_num in range(1_000_000): 13 | result = die_1.roll() * die_2.roll() 14 | results.append(result) 15 | 16 | # 結果を分析する 17 | frequencies = [] 18 | max_result = die_1.num_sides * die_2.num_sides 19 | for value in range(1, max_result+1): 20 | frequency = results.count(value) 21 | frequencies.append(frequency) 22 | 23 | # 結果を可視化する 24 | x_values = list(range(1, max_result+1)) 25 | data = [Bar(x=x_values, y=frequencies)] 26 | 27 | x_axis_config = {'title': '結果', 'dtick': 1} 28 | y_axis_config = {'title': '発生した回数'} 29 | my_layout = Layout(title='2つの6面サイコロをかけ算した結果(1,000,000回)', 30 | xaxis=x_axis_config, yaxis=y_axis_config) 31 | offline.plot({'data': data, 'layout': my_layout}, filename='4_8_d6xd6.html') 32 | -------------------------------------------------------------------------------- /やってみよう_実践編/chapter04/4_9_die_comprehension.py: -------------------------------------------------------------------------------- 1 | from plotly.graph_objs import Bar, Layout 2 | from plotly import offline 3 | 4 | from die import Die 5 | 6 | # 2つの6面サイコロを作成する 7 | die_1 = Die() 8 | die_2 = Die() 9 | 10 | # サイコロを転がし、結果をリストに格納する 11 | results = [die_1.roll() + die_2.roll() for roll_num in range(1000)] 12 | 13 | # 結果を分析する 14 | max_result = die_1.num_sides + die_2.num_sides 15 | frequencies = [results.count(value) for value in range(2, max_result+1)] 16 | 17 | # 結果を可視化する 18 | x_values = list(range(1, max_result+1)) 19 | data = [Bar(x=x_values, y=frequencies)] 20 | 21 | x_axis_config = {'title': '結果', 'dtick': 1} 22 | y_axis_config = {'title': '発生した回数'} 23 | my_layout = Layout(title='2つの6面サイコロを1,000回転がした結果', 24 | xaxis=x_axis_config, yaxis=y_axis_config) 25 | offline.plot({'data': data, 'layout': my_layout}, filename='4_9_d6_d6.html') 26 | -------------------------------------------------------------------------------- /やってみよう_実践編/chapter04/die.py: -------------------------------------------------------------------------------- 1 | from random import randint 2 | 3 | class Die: 4 | """1個のサイコロを表すクラス""" 5 | 6 | def __init__(self, num_sides=6): 7 | """6面のサイコロをデフォルトにする""" 8 | self.num_sides = num_sides 9 | 10 | def roll(self): 11 | """1から面の数の間のランダムな数値を返す""" 12 | return randint(1, self.num_sides) 13 | -------------------------------------------------------------------------------- /やってみよう_実践編/chapter04/random_walk.py: -------------------------------------------------------------------------------- 1 | from random import choice 2 | 3 | class RandomWalk: 4 | """ランダムウォークを生成するためのクラス""" 5 | 6 | def __init__(self, num_points=5000): 7 | """ランダムウォークの属性を初期化する""" 8 | self.num_points = num_points 9 | 10 | # すべてのランダムウォークは(0, 0)から開始する 11 | self.x_values = [0] 12 | self.y_values = [0] 13 | 14 | def fill_walk(self): 15 | """ランダムウォークのすべての点を計算する""" 16 | 17 | # ステップ数が指定した数になるまでランダムウォークを続ける 18 | while len(self.x_values) < self.num_points: 19 | 20 | # 移動する方向と距離を決定する 21 | x_direction = choice([1, -1]) 22 | x_distance = choice([0, 1, 2, 3, 4]) 23 | x_step = x_direction * x_distance 24 | 25 | y_direction = choice([1, -1]) 26 | y_distance = choice([0, 1, 2, 3, 4]) 27 | y_step = y_direction * y_distance 28 | 29 | # どこにも移動しない場合は結果を破棄する 30 | if x_step == 0 and y_step == 0: 31 | continue 32 | 33 | # 新しい位置を計算する 34 | x = self.x_values[-1] + x_step 35 | y = self.y_values[-1] + y_step 36 | 37 | self.x_values.append(x) 38 | self.y_values.append(y) 39 | -------------------------------------------------------------------------------- /やってみよう_実践編/chapter05/5_1_sitka_rainfall.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/takanory/saitan-python/8196a91a9aac5011bc29782381b93f143b0ae25a/やってみよう_実践編/chapter05/5_1_sitka_rainfall.png -------------------------------------------------------------------------------- /やってみよう_実践編/chapter05/5_1_sitka_rainfall.py: -------------------------------------------------------------------------------- 1 | import csv 2 | from datetime import datetime 3 | 4 | from matplotlib import pyplot as plt 5 | 6 | filename = 'data/sitka_weather_2018_simple.csv' 7 | with open(filename) as f: 8 | reader = csv.reader(f) 9 | header_row = next(reader) 10 | 11 | # ファイルから日付と降水量を取得する 12 | dates, precips = [], [] 13 | for row in reader: 14 | current_date = datetime.strptime(row[2], '%Y-%m-%d') 15 | dates.append(current_date) 16 | precip = float(row[3]) 17 | precips.append(precip) 18 | 19 | # 降水量をグラフに描画する 20 | plt.style.use('seaborn') 21 | fig, ax = plt.subplots() 22 | ax.plot(dates, precips, c='blue') 23 | 24 | # グラフにフォーマットを設定する 25 | plt.title("Daily Rainfall Amounts - 2018", fontsize=24) 26 | plt.xlabel('', fontsize=16) 27 | fig.autofmt_xdate() 28 | plt.ylabel("Rainfall (in)", fontsize=16) 29 | plt.tick_params(axis='both', which='major', labelsize=16) 30 | 31 | # plt.savefig('5_1_sitka_rainfall.png') 32 | plt.show() 33 | -------------------------------------------------------------------------------- /やってみよう_実践編/chapter05/5_2_death_valley_highs_lows.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/takanory/saitan-python/8196a91a9aac5011bc29782381b93f143b0ae25a/やってみよう_実践編/chapter05/5_2_death_valley_highs_lows.png -------------------------------------------------------------------------------- /やってみよう_実践編/chapter05/5_2_death_valley_highs_lows.py: -------------------------------------------------------------------------------- 1 | import csv 2 | from datetime import datetime 3 | 4 | import matplotlib.pyplot as plt 5 | 6 | filename = 'data/death_valley_2018_simple.csv' 7 | with open(filename) as f: 8 | reader = csv.reader(f) 9 | header_row = next(reader) 10 | 11 | # ファイルから日付と最高気温、最低気温を取得する 12 | dates, highs, lows = [], [], [] 13 | for row in reader: 14 | current_date = datetime.strptime(row[2], '%Y-%m-%d') 15 | try: 16 | high = int(row[4]) 17 | low = int(row[5]) 18 | except ValueError: 19 | print(f"Missing data for {current_date}") 20 | else: 21 | dates.append(current_date) 22 | highs.append(high) 23 | lows.append(low) 24 | 25 | # 最高気温と最低気温をグラフに描画する 26 | plt.style.use('seaborn') 27 | fig, ax = plt.subplots() 28 | ax.plot(dates, highs, c='red', alpha=0.5) 29 | ax.plot(dates, lows, c='blue', alpha=0.5) 30 | plt.fill_between(dates, highs, lows, facecolor='blue', alpha=0.1) 31 | 32 | # グラフにフォーマットを指定する 33 | title = "Daily high and low temperatures - 2018\nDeath Valley, CA" 34 | plt.title(title, fontsize=20) 35 | plt.xlabel('', fontsize=16) 36 | fig.autofmt_xdate() 37 | plt.ylabel("Temperature (F)", fontsize=16) 38 | plt.tick_params(axis='both', which='major', labelsize=16) 39 | plt.ylim(10, 130) 40 | 41 | # plt.savefig('5_2_death_valley_highs_lows.png') 42 | plt.show() 43 | -------------------------------------------------------------------------------- /やってみよう_実践編/chapter05/5_2_sitka_death_valley.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/takanory/saitan-python/8196a91a9aac5011bc29782381b93f143b0ae25a/やってみよう_実践編/chapter05/5_2_sitka_death_valley.png -------------------------------------------------------------------------------- /やってみよう_実践編/chapter05/5_2_sitka_highs_lows.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/takanory/saitan-python/8196a91a9aac5011bc29782381b93f143b0ae25a/やってみよう_実践編/chapter05/5_2_sitka_highs_lows.png -------------------------------------------------------------------------------- /やってみよう_実践編/chapter05/5_2_sitka_highs_lows.py: -------------------------------------------------------------------------------- 1 | import csv 2 | from datetime import datetime 3 | 4 | import matplotlib.pyplot as plt 5 | 6 | filename = 'data/sitka_weather_2018_simple.csv' 7 | with open(filename) as f: 8 | reader = csv.reader(f) 9 | header_row = next(reader) 10 | 11 | # ファイルから日付と最高気温、最低気温を取得する 12 | dates, highs, lows = [], [], [] 13 | for row in reader: 14 | current_date = datetime.strptime(row[2], '%Y-%m-%d') 15 | high = int(row[5]) 16 | low = int(row[6]) 17 | dates.append(current_date) 18 | highs.append(high) 19 | lows.append(low) 20 | 21 | # 最高気温と最低気温をグラフに描画する 22 | plt.style.use('seaborn') 23 | fig, ax = plt.subplots() 24 | ax.plot(dates, highs, c='red', alpha=0.5) 25 | ax.plot(dates, lows, c='blue', alpha=0.5) 26 | plt.fill_between(dates, highs, lows, facecolor='blue', alpha=0.1) 27 | 28 | # グラフにフォーマットを指定する 29 | plt.title("Daily high and low temperatures - 2018", fontsize=24) 30 | plt.xlabel('', fontsize=16) 31 | fig.autofmt_xdate() 32 | plt.ylabel("Temperature (F)", fontsize=16) 33 | plt.tick_params(axis='both', which='major', labelsize=16) 34 | plt.ylim(10, 130) 35 | 36 | # plt.savefig('5_2_sitka_highs_lows.png') 37 | plt.show() 38 | -------------------------------------------------------------------------------- /やってみよう_実践編/chapter05/5_4_auto_indexes.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/takanory/saitan-python/8196a91a9aac5011bc29782381b93f143b0ae25a/やってみよう_実践編/chapter05/5_4_auto_indexes.png -------------------------------------------------------------------------------- /やってみよう_実践編/chapter05/5_7_auto_title.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | from plotly.graph_objs import Scattergeo, Layout 4 | from plotly import offline 5 | 6 | # データの構造を調査する 7 | filename = 'data/eq_data_30_day_m1.json' 8 | with open(filename) as f: 9 | all_eq_data = json.load(f) 10 | 11 | title = all_eq_data['metadata']['title'] # タイトルを取得 12 | all_eq_dicts = all_eq_data['features'] 13 | 14 | mags, lons, lats, hover_texts = [], [], [], [] 15 | for eq_dict in all_eq_dicts: 16 | mags.append(eq_dict['properties']['mag']) 17 | lons.append(eq_dict['geometry']['coordinates'][0]) 18 | lats.append(eq_dict['geometry']['coordinates'][1]) 19 | hover_texts.append(eq_dict['properties']['title']) 20 | 21 | # 地震の地図 22 | data = [{ 23 | 'type': 'scattergeo', 24 | 'lon': lons, 25 | 'lat': lats, 26 | 'text': hover_texts, 27 | 'marker': { 28 | 'size': [5*mag for mag in mags], 29 | 'color': mags, 30 | 'colorscale': 'Viridis', 31 | 'reversescale': True, 32 | 'colorbar': {'title': 'マグニチュード'}, 33 | }, 34 | }] 35 | my_layout = Layout(title=title) 36 | 37 | fig = {'data': data, 'layout': my_layout} 38 | offline.plot(fig, filename='5_7_global_earthquakes.html') 39 | -------------------------------------------------------------------------------- /やってみよう_必修編/README.md: -------------------------------------------------------------------------------- 1 | # 必修編の「やってみよう」の回答例 2 | 3 | 書籍「最短距離でゼロからしっかり学ぶPython入門 必修編」の演習問題「やってみよう」の回答例です。 4 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter02/2_10_adding_comments.py: -------------------------------------------------------------------------------- 1 | # 空白を含んだ文字列からメソッドを使用して空白を取り除く 2 | name = "\tTakanori Suzuki\n" 3 | 4 | print("そのまま出力") 5 | print(name) 6 | 7 | print("\nlstrip()を使用") 8 | print(name.lstrip()) # 左側の空白を取り除く 9 | 10 | print("\nrstrip()を使用") 11 | print(name.rstrip()) # 右側の空白を取り除く 12 | 13 | print("\nstrip()を使用") 14 | print(name.strip()) # 左右の空白を取り除く 15 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter02/2_1_simple_message.py: -------------------------------------------------------------------------------- 1 | message = "私はPythonが好きです" 2 | print(message) 3 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter02/2_2_simple_messages.py: -------------------------------------------------------------------------------- 1 | message = "私はPythonが好きです" 2 | print(message) 3 | 4 | message = "Pythonはとても機能が充実しています!" 5 | print(message) 6 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter02/2_3_personal_message.py: -------------------------------------------------------------------------------- 1 | name = "Takanori" 2 | print(f"こんにちは{name}、今日はPythonを学びますか?") 3 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter02/2_4_name_cases.py: -------------------------------------------------------------------------------- 1 | name = "Takanori" 2 | 3 | print("小文字") 4 | print(f"こんにちは{name.lower()}") 5 | 6 | print("\n大文字") 7 | print(f"こんにちは{name.upper()}") 8 | 9 | print("\nタイトルケース") 10 | print(f"こんにちは{name.title()}") 11 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter02/2_5_famous_quote.py: -------------------------------------------------------------------------------- 1 | print('アルベルト・アインシュタインは "挫折を経験したことがない者は、') 2 | print('何も新しいことに挑戦したことがないということだ。" と言った。') 3 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter02/2_6_famous_quote2.py: -------------------------------------------------------------------------------- 1 | famous_person = "アルベルト・アインシュタイン" 2 | message = f'{famous_person}は "挫折を経験したことがない者は、何も新しいことに挑戦したことがないということだ。" と言った。' 3 | print(message) 4 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter02/2_7_stripping_names.py: -------------------------------------------------------------------------------- 1 | name = "\tTakanori Suzuki\n" 2 | 3 | print("そのまま出力") 4 | print(name) 5 | 6 | print("\nlstrip()を使用") 7 | print(name.lstrip()) 8 | 9 | print("\nrstrip()を使用") 10 | print(name.rstrip()) 11 | 12 | print("\nstrip()を使用") 13 | print(name.strip()) 14 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter02/2_8_number_eight.oy: -------------------------------------------------------------------------------- 1 | print(5+3) 2 | print(10-2) 3 | print(2*4) 4 | print(64/8) -------------------------------------------------------------------------------- /やってみよう_必修編/chapter02/2_9_favorite_number.py: -------------------------------------------------------------------------------- 1 | fav_number = 42 2 | print(f"私の好きな数字は{fav_number}です。") 3 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter03/3_1_names.py: -------------------------------------------------------------------------------- 1 | names = ['やすだ', 'てらだ', 'しみずかわ'] 2 | 3 | print(names[0]) 4 | print(names[1]) 5 | print(names[2]) 6 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter03/3_2_greetings.py: -------------------------------------------------------------------------------- 1 | names = ['やすだ', 'てらだ', 'しみずかわ'] 2 | 3 | print(f"こんにちは、{names[0]}さん!") 4 | print(f"こんにちは、{names[1]}さん!") 5 | print(f"こんにちは、{names[2]}さん!") 6 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter03/3_3_your_own_list.py: -------------------------------------------------------------------------------- 1 | cycles = ["trek", "cannondale", "leuis garneau"] 2 | 3 | print(f"私は{cycles[0].title()}の自転車がほしい。") 4 | print(f"私は{cycles[1].title()}の自転車がほしい。") 5 | print(f"私は{cycles[2].title()}の自転車がほしい。") 6 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter03/3_4_guest_list.py: -------------------------------------------------------------------------------- 1 | guests = ["guido van rossum", "ewa jodlowska", "naomi ceder"] 2 | 3 | name = guests[0].title() 4 | print(f"{name}さん、ぜひ夕食に来てください。") 5 | 6 | name = guests[1].title() 7 | print(f"{name}さん、ぜひ夕食に来てください。") 8 | 9 | name = guests[2].title() 10 | print(f"{name}さん、ぜひ夕食に来てください。") 11 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter03/3_5_changing_guest_list.py: -------------------------------------------------------------------------------- 1 | guests = ["guido van rossum", "ewa jodlowska", "naomi ceder"] 2 | 3 | name = guests[0].title() 4 | print(f"{name}さん、ぜひ夕食に来てください。") 5 | 6 | name = guests[1].title() 7 | print(f"{name}さん、ぜひ夕食に来てください。") 8 | 9 | name = guests[2].title() 10 | print(f"{name}さん、ぜひ夕食に来てください。") 11 | 12 | name = guests[1].title() 13 | print(f"\nすいません、{name}さんが夕食に参加できなくなりました。") 14 | 15 | # Ewaさんの代わりにCoryさんを招待します 16 | del guests[1] 17 | guests.insert(1, 'cory althoff') 18 | 19 | # 再度、招待メッセージを取得する 20 | name = guests[0].title() 21 | print(f"\n{name}さん、ぜひ夕食に来てください。") 22 | 23 | name = guests[1].title() 24 | print(f"{name}さん、ぜひ夕食に来てください。") 25 | 26 | name = guests[2].title() 27 | print(f"{name}さん、ぜひ夕食に来てください。") 28 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter03/3_6_more_guests.py: -------------------------------------------------------------------------------- 1 | guests = ["guido van rossum", "ewa jodlowska", "naomi ceder"] 2 | 3 | name = guests[0].title() 4 | print(f"{name}さん、ぜひ夕食に来てください。") 5 | 6 | name = guests[1].title() 7 | print(f"{name}さん、ぜひ夕食に来てください。") 8 | 9 | name = guests[2].title() 10 | print(f"{name}さん、ぜひ夕食に来てください。") 11 | 12 | name = guests[1].title() 13 | print(f"\nすいません、{name}さんが夕食に参加できなくなりました。") 14 | 15 | # Ewaさんの代わりにCoryさんを招待します 16 | del guests[1] 17 | guests.insert(1, 'cory althoff') 18 | 19 | # 再度、招待メッセージを取得する 20 | name = guests[0].title() 21 | print(f"\n{name}さん、ぜひ夕食に来てください。") 22 | 23 | name = guests[1].title() 24 | print(f"{name}さん、ぜひ夕食に来てください。") 25 | 26 | name = guests[2].title() 27 | print(f"{name}さん、ぜひ夕食に来てください。") 28 | 29 | # 大きなテーブルを見つけたので、追加のゲストを招待する 30 | print("\n大きなテーブルを見つけた!") 31 | guests.insert(0, 'iqbal abdullah') 32 | guests.insert(2, 'younggun kim') 33 | guests.append('jung yu cheng') 34 | 35 | name = guests[0].title() 36 | print(f"{name}さん、ぜひ夕食に来てください。") 37 | 38 | name = guests[1].title() 39 | print(f"{name}さん、ぜひ夕食に来てください。") 40 | 41 | name = guests[2].title() 42 | print(f"{name}さん、ぜひ夕食に来てください。") 43 | 44 | name = guests[3].title() 45 | print(f"{name}さん、ぜひ夕食に来てください。") 46 | 47 | name = guests[4].title() 48 | print(f"{name}さん、ぜひ夕食に来てください。") 49 | 50 | name = guests[5].title() 51 | print(f"{name}さん、ぜひ夕食に来てください。") 52 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter03/3_8_seeing_the_world.py: -------------------------------------------------------------------------------- 1 | locations = ['barcelona', 'machu picchu', 'uyuni', 'guiana shield', 'ulruru'] 2 | 3 | print("元の順番") 4 | print(locations) 5 | 6 | print("\nアルファベット順") 7 | print(sorted(locations)) 8 | 9 | print("\n元の順番") 10 | print(locations) 11 | 12 | print("\nアルファベットの逆順") 13 | print(sorted(locations, reverse=True)) 14 | 15 | print("\n元の順番") 16 | print(locations) 17 | 18 | print("\n逆順") 19 | locations.reverse() 20 | print(locations) 21 | 22 | print("\n元の順番") 23 | locations.reverse() 24 | print(locations) 25 | 26 | print("\nアルファベット順") 27 | locations.sort() 28 | print(locations) 29 | 30 | print("\nアルファベットの逆順") 31 | locations.sort(reverse=True) 32 | print(locations) 33 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter04/4_10_slices.py: -------------------------------------------------------------------------------- 1 | odd_numbers = list(range(1, 21, 2)) 2 | 3 | for number in odd_numbers: 4 | print(number) 5 | 6 | print("\nリストの最初の3つの要素です。") 7 | for number in odd_numbers[:3]: 8 | print(number) 9 | 10 | print("\nリストの中央の3つの要素です。") 11 | for number in odd_numbers[3:6]: 12 | print(number) 13 | 14 | print("\nリストの最後の3つの要素です。") 15 | for number in odd_numbers[-3:]: 16 | print(number) 17 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter04/4_11_my_pizzas_your_pizzas.py: -------------------------------------------------------------------------------- 1 | favorite_pizzas = ['マルゲリータ', 'クアトロ・フォルマッジ', 'マリナーラ'] 2 | friend_pizzas = favorite_pizzas[:] 3 | 4 | favorite_pizzas.append('ビスマルク') 5 | friend_pizzas.append('ペスカトーレ') 6 | 7 | print("私が好きなピザ") 8 | for pizza in favorite_pizzas: 9 | print(f"- {pizza}") 10 | 11 | print("\n友達が好きなピザ") 12 | for pizza in friend_pizzas: 13 | print(f"- {pizza}") 14 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter04/4_12_more_loops.py: -------------------------------------------------------------------------------- 1 | my_foods = ['ピザ', 'だんご', 'ケーキ'] 2 | friend_foods = my_foods[:] 3 | 4 | my_foods.append('チョコレート') 5 | friend_foods.append('アイスクリーム') 6 | 7 | print("私の好きな食べ物") 8 | for food in my_foods: 9 | print(f"- {food}") 10 | 11 | print("\n友達が好きな食べ物") 12 | for food in friend_foods: 13 | print(f"- {food}") 14 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter04/4_13_buffet.py: -------------------------------------------------------------------------------- 1 | menu_items = ( 2 | 'ハンバーグステーキ', 'ポークリブ', 'ラムチョップ', 3 | 'サーモングリル', 'ロブスター', 4 | ) 5 | 6 | print("以下のメニューから選択できます。") 7 | for item in menu_items: 8 | print(f"- {item}") 9 | 10 | menu_items = ( 11 | 'ハンバーグステーキ', 'ポークリブ', 'ラムチョップ', 12 | '真鯛のグリル', 'イカフライ', 13 | ) 14 | 15 | print("\nメニューが変更になりました。") 16 | print("以下のメニューから選択できるようになりました。") 17 | for item in menu_items: 18 | print(f"- {item}") 19 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter04/4_1_pizzas.py: -------------------------------------------------------------------------------- 1 | favorite_pizzas = ['マルゲリータ', 'クアトロ・フォルマッジ', 'マリナーラ'] 2 | 3 | # ピザの名前を出力する 4 | for pizza in favorite_pizzas: 5 | print(pizza) 6 | 7 | print() 8 | 9 | # ピザについての文章を出力する 10 | for pizza in favorite_pizzas: 11 | print(f"私は{pizza}ピザが好きです。") 12 | 13 | print("\n私はピザが大好きです!") 14 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter04/4_2_animals.py: -------------------------------------------------------------------------------- 1 | animals = ['イヌ', 'ネコ', 'フェレット'] 2 | 3 | # 動物の名前を出力する 4 | for animal in animals: 5 | print(animal) 6 | 7 | print() 8 | 9 | # 動物についての文章を出力するの名前を出力する 10 | for animal in animals: 11 | print(f"{animal}は素晴らしいペットです。") 12 | 13 | print("\nこの動物たちはとても素晴らしいペットです!") 14 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter04/4_3_counting_to_twenty.py: -------------------------------------------------------------------------------- 1 | for number in range(1, 21): 2 | print(number) 3 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter04/4_4_one_million.py: -------------------------------------------------------------------------------- 1 | for number in range(1, 1_000_001): 2 | print(number) 3 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter04/4_5_summing_a_million.py: -------------------------------------------------------------------------------- 1 | numbers = list(range(1, 1_000_001)) 2 | 3 | print(min(numbers)) 4 | print(max(numbers)) 5 | print(sum(numbers)) 6 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter04/4_6_odd_numbers.py: -------------------------------------------------------------------------------- 1 | odd_numbers = list(range(1, 21, 2)) 2 | 3 | for number in odd_numbers: 4 | print(number) 5 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter04/4_7_threes.py: -------------------------------------------------------------------------------- 1 | threes = list(range(3, 31, 3)) 2 | 3 | for number in threes: 4 | print(number) 5 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter04/4_8_cubes.py: -------------------------------------------------------------------------------- 1 | cubes = [] 2 | for number in range(1, 11): 3 | cube = number**3 4 | cubes.append(cube) 5 | 6 | for cube in cubes: 7 | print(cube) 8 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter04/4_9_cube_comprehension.py: -------------------------------------------------------------------------------- 1 | cubes = [number**3 for number in range(1, 11)] 2 | 3 | for cube in cubes: 4 | print(cube) 5 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter05/5_10_checking_usernames.py: -------------------------------------------------------------------------------- 1 | current_users = ['takanory', 'zenich', 'admin', 'shimizukawa', 'ken5'] 2 | new_users = ['soogie', 'Zenich', 'TAKANORY', 'NaoY', 'Kashew_nuts'] 3 | 4 | current_users_lower = [user.lower() for user in current_users] 5 | 6 | for new_user in new_users: 7 | if new_user.lower() in current_users_lower: 8 | print(f"すいません{new_user}、その名前はすでに使用されています。") 9 | else: 10 | print(f"よかった、{new_user}という名前は利用可能です。") 11 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter05/5_11_ordinal_numbers.py: -------------------------------------------------------------------------------- 1 | numbers = list(range(1, 10)) 2 | 3 | for number in numbers: 4 | if number == 1: 5 | print("1st") 6 | elif number == 2: 7 | print("2nd") 8 | elif number == 3: 9 | print("3rd") 10 | else: 11 | print(f"{number}th") 12 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter05/5_1_conditional_tests.py: -------------------------------------------------------------------------------- 1 | car = 'subaru' 2 | print("car == 'subaru' の結果を True と予測します。") 3 | print(car == 'subaru') 4 | 5 | print("\ncar == 'audi' の結果を False と予測します。") 6 | print(car == 'audi') 7 | 8 | answer = 17 9 | print("\nanswer == 17 の結果を True と予測します。") 10 | print(answer == 17) 11 | 12 | print("\nanswer == 42 の結果を False と予測します。") 13 | print(answer == 42) 14 | 15 | age = 21 16 | print("\nage > 19 の結果を True と予測します。") 17 | print(age > 19) 18 | 19 | print("\nage <= 19 の結果を False と予測します。") 20 | print(age <= 19) 21 | 22 | print("\nage < 22 or age > 40 の結果を True と予測します。") 23 | print(age < 22 or age > 40) 24 | 25 | print("\nage < 22 and age > 40 の結果を False と予測します。") 26 | print(age < 22 and age > 40) 27 | 28 | pets = ['イヌ', 'ネコ', 'フェレット'] 29 | print("\n'フェレット' in pets の結果を True と予測します。") 30 | print('フェレット' in pets) 31 | 32 | print("\n'フェレット' not in pets の結果を True と予測します。") 33 | print('フェレット' not in pets) 34 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter05/5_3_alien_colors1_false.py: -------------------------------------------------------------------------------- 1 | alien_color = '赤' 2 | 3 | if alien_color == '緑': 4 | print("5点を獲得しました!") 5 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter05/5_3_alien_colors1_true.py: -------------------------------------------------------------------------------- 1 | alien_color = '緑' 2 | 3 | if alien_color == '緑': 4 | print("5点を獲得しました!") 5 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter05/5_4_alien_colors2_else.py: -------------------------------------------------------------------------------- 1 | alien_color = '黄' 2 | 3 | if alien_color == '緑': 4 | print("5点を獲得しました!") 5 | else: 6 | print("10点を獲得しました!") 7 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter05/5_4_alien_colors2_if.py: -------------------------------------------------------------------------------- 1 | alien_color = '緑' 2 | 3 | if alien_color == '緑': 4 | print("5点を獲得しました!") 5 | else: 6 | print("10点を獲得しました!") 7 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter05/5_5_alien_colors3_elif.py: -------------------------------------------------------------------------------- 1 | alien_color = '黄' 2 | 3 | if alien_color == '緑': 4 | print("5点を獲得しました!") 5 | elif alien_color == '黄': 6 | print("10点を獲得しました!") 7 | else: 8 | print("15点を獲得しました!") 9 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter05/5_5_alien_colors3_else.py: -------------------------------------------------------------------------------- 1 | alien_color = '赤' 2 | 3 | if alien_color == '緑': 4 | print("5点を獲得しました!") 5 | elif alien_color == '黄': 6 | print("10点を獲得しました!") 7 | else: 8 | print("15点を獲得しました!") 9 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter05/5_5_alien_colors3_if.py: -------------------------------------------------------------------------------- 1 | alien_color = '緑' 2 | 3 | if alien_color == '緑': 4 | print("5点を獲得しました!") 5 | elif alien_color == '黄': 6 | print("10点を獲得しました!") 7 | else: 8 | print("15点を獲得しました!") 9 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter05/5_6_stages_of_life.py: -------------------------------------------------------------------------------- 1 | age = 17 2 | 3 | if age < 2: 4 | stage = "赤ちゃん" 5 | elif age < 4: 6 | stage = "幼児" 7 | elif age < 13: 8 | stage = "子ども" 9 | elif age < 20: 10 | stage = "ティーンエイジャー" 11 | elif age < 65: 12 | stage = "大人" 13 | else: 14 | stage = "高齢者" 15 | 16 | print(f"あなたは{stage}です!") 17 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter05/5_7_favorite_fruit.py: -------------------------------------------------------------------------------- 1 | favorite_fruits = ['スイカ', '桃', 'キウイ'] 2 | 3 | if 'バナナ' in favorite_fruits: 4 | print("あなたは本当にバナナが好きですね!") 5 | if 'スイカ' in favorite_fruits: 6 | print("あなたは本当にスイカが好きですね!") 7 | if 'イチゴ' in favorite_fruits: 8 | print("あなたは本当にイチゴが好きですね!") 9 | if '桃' in favorite_fruits: 10 | print("あなたは本当に桃が好きですね!") 11 | if 'リンゴ' in favorite_fruits: 12 | print("あなたは本当にリンゴが好きですね!") 13 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter05/5_8_hello_admin.py: -------------------------------------------------------------------------------- 1 | usernames = ['takanory', 'zenich', 'admin', 'shimizukawa', 'ken5'] 2 | 3 | for username in usernames: 4 | if username == 'admin': 5 | print("こんにちはadmin、状況のレポートを見ますか?") 6 | else: 7 | print(f"こんにちは{username}、またログインしてくれてありがとう。") 8 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter05/5_9_no_users.py: -------------------------------------------------------------------------------- 1 | usernames = [] 2 | 3 | if usernames: 4 | for username in usernames: 5 | if username == 'admin': 6 | print("こんにちはadmin、状況のレポートを見ますか?") 7 | else: 8 | print(f"こんにちは{username}、またログインしてくれてありがとう。") 9 | else: 10 | print("ユーザー募集中です!") 11 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter06/6_10_favorite_numbers.py: -------------------------------------------------------------------------------- 1 | favorite_numbers = { 2 | 'たかのり': [42, 17], 3 | 'ぜんいち': [42, 39, 56], 4 | 'かしゅー': [7, 12], 5 | } 6 | 7 | for name, numbers in favorite_numbers.items(): 8 | print(f"\n{name.title()}の好きな数字は以下です。") 9 | for number in numbers: 10 | print(f" {number}") 11 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter06/6_11_cities.py: -------------------------------------------------------------------------------- 1 | cities = { 2 | 'taipei': { 3 | 'country': 'taiwan', 4 | 'population': 2_646_000, 5 | 'fact': 'night market', 6 | }, 7 | 'bali': { 8 | 'country': 'indonesia', 9 | 'population': 4_220_000, 10 | 'fact': 'kecak', 11 | }, 12 | 'billund': { 13 | 'country': 'denpark', 14 | 'population': 6_277, 15 | 'fact': 'legoland', 16 | } 17 | } 18 | 19 | for city, city_info in cities.items(): 20 | country = city_info['country'].title() 21 | population = city_info['population'] 22 | fact = city_info['fact'].title() 23 | 24 | print(f"\n{city.title()}は{country}にあります。") 25 | print(f" 人口は約{population}人です。") 26 | print(f" 特徴として{fact}があります。") 27 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter06/6_1_person.py: -------------------------------------------------------------------------------- 1 | person = { 2 | 'first_name': 'takanori', 3 | 'last_name': 'suzuki', 4 | 'age': 49, 5 | 'city': 'Tokyo', 6 | } 7 | 8 | print(person['first_name']) 9 | print(person['last_name']) 10 | print(person['age']) 11 | print(person['city']) 12 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter06/6_2_favorite_numbers.py: -------------------------------------------------------------------------------- 1 | favorite_numbers = { 2 | 'たかのり': 42, 3 | 'ぜんいち': 23, 4 | 'かしゅー': 7, 5 | 'あきこ': 1000_000, 6 | 'にっきー': 0, 7 | } 8 | 9 | num = favorite_numbers['たかのり'] 10 | print(f"たかのりの好きな数字は{num}です。") 11 | 12 | num = favorite_numbers['ぜんいち'] 13 | print(f"ぜんいちの好きな数字は{num}です。") 14 | 15 | num = favorite_numbers['かしゅー'] 16 | print(f"かしゅーの好きな数字は{num}です。") 17 | 18 | num = favorite_numbers['あきこ'] 19 | print(f"あきこの好きな数字は{num}です。") 20 | 21 | num = favorite_numbers['にっきー'] 22 | print(f"にっきーの好きな数字は{num}です。") 23 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter06/6_3_glossary.py: -------------------------------------------------------------------------------- 1 | glossary = { 2 | 'string': '一連の文字。', 3 | 'comment': 'プログラム内のメモで、Pythonインタープリタは無視する。', 4 | 'list': '特定の順番のアイテムの集まり。', 5 | 'loop': 'アイテムの集まりを1つずつ処理すること。', 6 | 'dictionary': "キーと値のペアの集まり。", 7 | } 8 | 9 | word = 'string' 10 | print(f"{word.title()}: {glossary[word]}") 11 | 12 | word = 'comment' 13 | print(f"\n{word.title()}: {glossary[word]}") 14 | 15 | word = 'list' 16 | print(f"\n{word.title()}: {glossary[word]}") 17 | 18 | word = 'loop' 19 | print(f"\n{word.title()}: {glossary[word]}") 20 | 21 | word = 'dictionary' 22 | print(f"\n{word.title()}: {glossary[word]}") 23 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter06/6_4_glossary2.py: -------------------------------------------------------------------------------- 1 | glossary = { 2 | 'string': '一連の文字。', 3 | 'comment': 'プログラム内のメモで、Pythonインタープリタは無視する。', 4 | 'list': '特定の順番のアイテムの集まり。', 5 | 'loop': 'アイテムの集まりを1つずつ処理すること。', 6 | 'dictionary': "キーと値のペアの集まり。", 7 | 'key': '辞書のキーと値のペアの最初の項目。', 8 | 'value': '辞書のキーと関連付けられた項目。', 9 | 'int': '整数の数値。', 10 | 'float': '小数点がある数値。', 11 | 'and': '両方の条件がTrueの場合にTrueとなり、それ以外はFalseとなる。', 12 | } 13 | 14 | for word, definition in glossary.items(): 15 | print(f"\n{word.title()}: {definition}") 16 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter06/6_5_rivers.py: -------------------------------------------------------------------------------- 1 | rivers = { 2 | 'nile': 'egypt', 3 | 'mississippi': 'united states', 4 | 'amazon': 'brazil', 5 | } 6 | 7 | for river, country in rivers.items(): 8 | print(f"{river.title()}は{country.title()}を流れている。") 9 | 10 | print("\nこのデータセットには、以下の川が含まれています。") 11 | for river in rivers.keys(): 12 | print(f"- {river.title()}") 13 | 14 | print("\nこのデータセットには、以下の国が含まれています。") 15 | for country in rivers.values(): 16 | print(f"- {country.title()}") 17 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter06/6_6_polling.py: -------------------------------------------------------------------------------- 1 | favorite_languages = { 2 | 'jen': 'python', 3 | 'sarah': 'c', 4 | 'edward': 'ruby', 5 | 'phil': 'python', 6 | } 7 | 8 | for name, language in favorite_languages.items(): 9 | print(f"{name.title()}の好きなプログラミング言語は{language.title()}です。") 10 | 11 | print("") 12 | 13 | coders = ['phil', 'josh', 'david', 'becca', 'sarah', 'matt', 'danielle'] 14 | for coder in coders: 15 | if coder in favorite_languages.keys(): 16 | print(f"{coder.title()}、投票してくれてありがとう!") 17 | else: 18 | print(f"{coder.title()}、好きなプログラミング言語はなんですか?") 19 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter06/6_7_people.py: -------------------------------------------------------------------------------- 1 | # 空のリストを作成する 2 | people = [] 3 | 4 | # 人の辞書を作成してリストに追加する 5 | person = { 6 | 'first_name': 'たかのり', 7 | 'last_name': '鈴木', 8 | 'age': 49, 9 | 'city': '東京', 10 | } 11 | people.append(person) 12 | 13 | person = { 14 | 'first_name': 'せぶん', 15 | 'last_name': '鈴木', 16 | 'age': 2, 17 | 'city': '東京', 18 | } 19 | people.append(person) 20 | 21 | person = { 22 | 'first_name': 'にあ', 23 | 'last_name': '鈴木', 24 | 'age': 4, 25 | 'city': '東京', 26 | } 27 | people.append(person) 28 | 29 | # 辞書の全情報を出力する 30 | for person in people: 31 | name = f"{person['last_name']}{person['first_name']}" 32 | age = person['age'] 33 | city = person['city'].title() 34 | 35 | print(f"{name}は{city}に住んでおり、{age}才です。") 36 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter06/6_8_pets.py: -------------------------------------------------------------------------------- 1 | # ペットの情報を格納する空のリストを作成する 2 | pets = [] 3 | 4 | # ペットの情報を作成してリストに追加する 5 | pet = { 6 | 'animal type': 'フェレット', 7 | 'name': 'せぶん', 8 | 'owner': 'takanory', 9 | 'eats': 'ferret food', 10 | } 11 | pets.append(pet) 12 | 13 | pet = { 14 | 'animal type': 'うさぎ', 15 | 'name': 'ちゃまる', 16 | 'owner': 'selina', 17 | 'eats': 'grass', 18 | } 19 | pets.append(pet) 20 | 21 | # 各ペットの情報を出力する 22 | for pet in pets: 23 | print(f"\n{pet['name']}についての情報です。") 24 | for key, value in pet.items(): 25 | print(f"\t{key}: {value}") 26 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter06/6_9_favorite_places.py: -------------------------------------------------------------------------------- 1 | favorite_places = { 2 | 'eric': ['bear mountain', 'death valley', 'tierra del fuego'], 3 | 'takanory': ['barcelona', 'billund', 'taipei'], 4 | 'zenich': ['san francisco', 'amsterdam', 'campbell river'], 5 | } 6 | 7 | for name, places in favorite_places.items(): 8 | print(f"\n{name.title()}が好きな場所は以下です。") 9 | for place in places: 10 | print(f"- {place.title()}") 11 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter07/7_10_dream_vacation.py: -------------------------------------------------------------------------------- 1 | name_prompt = "\nあなたのお名前は? " 2 | place_prompt = "世界中どこでも好きなところに行けるとしたらどこに行きたいですか? " 3 | continue_prompt = "\n誰か他に回答してくれる人はいますか? (yes/no) " 4 | 5 | # Responses will be stored in the form {name: place}. 6 | responses = {} 7 | 8 | while True: 9 | # Ask the user where they'd like to go. 10 | name = input(name_prompt) 11 | place = input(place_prompt) 12 | 13 | # Store the response. 14 | responses[name] = place 15 | 16 | # Ask if there's anyone else responding. 17 | repeat = input(continue_prompt) 18 | if repeat != 'yes': 19 | break 20 | 21 | # Show results of the survey. 22 | print("\n--- 投票結果 ---") 23 | for name, place in responses.items(): 24 | print(f"{name.title()}さんが行きたい場所は{place.title()}です。") 25 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter07/7_1_rental_car.py: -------------------------------------------------------------------------------- 1 | car = input("どんな種類の車を借りたいですか? ") 2 | 3 | print(f"{car.title()}を準備できるかどうか調べます。") 4 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter07/7_2_restaurant_seating.py: -------------------------------------------------------------------------------- 1 | party_size = input("今晩のディナーには何人参加しますか? ") 2 | party_size = int(party_size) 3 | 4 | if party_size > 8: 5 | print("すみません、席につくまで少しお待ちください。") 6 | else: 7 | print("テーブルの準備はできています。") 8 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter07/7_3_multiples_of_ten.py: -------------------------------------------------------------------------------- 1 | number = input("何か数を入力してください: ") 2 | number = int(number) 3 | 4 | if number % 10 == 0: 5 | print(f"{number}は10の倍数です。") 6 | else: 7 | print(f"{number}は10の倍数ではありません。") 8 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter07/7_4_pizza_toppings.py: -------------------------------------------------------------------------------- 1 | prompt = "\n何をピザにトッピングしたいですか?" 2 | prompt += "\n終わったら '終了' と入力してください。): " 3 | 4 | while True: 5 | topping = input(prompt) 6 | if topping != '終了': 7 | print(f" あなたのピザに{topping}をトッピングします。") 8 | else: 9 | break 10 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter07/7_5_movie_tickets.py: -------------------------------------------------------------------------------- 1 | prompt = "何歳ですか?" 2 | prompt += "\n終わったら '終了' と入力してください。: " 3 | 4 | while True: 5 | age = input(prompt) 6 | if age == '終了': 7 | break 8 | age = int(age) 9 | 10 | if age < 3: 11 | print(" チケット料金は無料です。") 12 | elif age < 13: 13 | print(" チケット料金は1000円です。") 14 | else: 15 | print(" チケット料金は1500円です。") 16 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter07/7_6_three_exits.py: -------------------------------------------------------------------------------- 1 | prompt = "何歳ですか? " 2 | prompt += "\n終わったら '終了' と入力してください。: " 3 | 4 | active = True 5 | while active: 6 | age = input(prompt) 7 | if age == '終了': 8 | break 9 | age = int(age) 10 | 11 | if age < 3: 12 | print(" チケット料金は無料です。") 13 | elif age < 13: 14 | print(" チケット料金は1000円です。") 15 | elif age < 19: 16 | print(" チケット料金は1500円です。") 17 | else: 18 | print(" 19歳以上は対象外です。終了します。") 19 | active = False 20 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter07/7_7_infinity.py: -------------------------------------------------------------------------------- 1 | prompt = "何歳ですか? " 2 | 3 | active = True 4 | while active: 5 | age = input(prompt) 6 | age = int(age) 7 | 8 | if age < 3: 9 | print(" チケット料金は無料です。") 10 | elif age < 13: 11 | print(" チケット料金は1000円です。") 12 | else: 13 | print(" チケット料金は1500円です。") 14 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter07/7_8_deli.py: -------------------------------------------------------------------------------- 1 | sandwich_orders = ['ベジー', 'グリルドチーズ', 'ターキー', 'ローストビーフ'] 2 | finished_sandwiches = [] 3 | 4 | while sandwich_orders: 5 | current_sandwich = sandwich_orders.pop() 6 | print(f"{current_sandwich}サンドを調理中です。") 7 | finished_sandwiches.append(current_sandwich) 8 | 9 | print("\n") 10 | for sandwich in finished_sandwiches: 11 | print(f"ご注文の{sandwich}サンドができました。") 12 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter07/7_9_no_pastrami.py: -------------------------------------------------------------------------------- 1 | sandwich_orders = [ 2 | 'パストラミ', 'ベジー', 'グリルドチーズ', 'パストラミ', 3 | 'ターキー', 'ローストビーフ', 'パストラミ'] 4 | finished_sandwiches = [] 5 | 6 | print("あいにく今日はパストラミが品切れです。") 7 | while 'パストラミ' in sandwich_orders: 8 | sandwich_orders.remove('パストラミ') 9 | 10 | print("\n") 11 | while sandwich_orders: 12 | current_sandwich = sandwich_orders.pop() 13 | print(f"{current_sandwich}サンドを調理中です。") 14 | finished_sandwiches.append(current_sandwich) 15 | 16 | print("\n") 17 | for sandwich in finished_sandwiches: 18 | print(f"ご注文の{sandwich}サンドができました。") 19 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter08/8_10_sending_messages.py: -------------------------------------------------------------------------------- 1 | def show_messages(messages): 2 | """リストの中の各メッセージを出力する""" 3 | print("全メッセージを表示します。") 4 | for message in messages: 5 | print(message) 6 | 7 | 8 | def send_messages(messages, sent_messages): 9 | """各メッセージを出力し、sent_messagesに移動する""" 10 | print("\n全メッセージを送信します。") 11 | while messages: 12 | current_message = messages.pop() 13 | print(current_message) 14 | sent_messages.append(current_message) 15 | 16 | 17 | messages = ["こんにちは", "元気ですか?", "ビール飲みたい"] 18 | show_messages(messages) 19 | 20 | sent_messages = [] 21 | send_messages(messages, sent_messages) 22 | 23 | print("\n最終的なリストの状態") 24 | print(messages) 25 | print(sent_messages) 26 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter08/8_11_archived_messages.py: -------------------------------------------------------------------------------- 1 | def show_messages(messages): 2 | """リストの中の各メッセージを出力する""" 3 | print("全メッセージを表示します。") 4 | for message in messages: 5 | print(message) 6 | 7 | 8 | def send_messages(messages, sent_messages): 9 | """各メッセージを出力し、sent_messagesに移動する""" 10 | print("\n全メッセージを送信します。") 11 | while messages: 12 | current_message = messages.pop() 13 | print(current_message) 14 | sent_messages.append(current_message) 15 | 16 | 17 | messages = ["こんにちは", "元気ですか?", "ビール飲みたい"] 18 | show_messages(messages) 19 | 20 | sent_messages = [] 21 | send_messages(messages[:], sent_messages) 22 | 23 | print("\n最終的なリストの状態") 24 | print(messages) 25 | print(sent_messages) 26 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter08/8_12_sandwiches.py: -------------------------------------------------------------------------------- 1 | def make_sandwich(*items): 2 | """指定された材料でサンドイッチを作る""" 3 | print("\nこれからサンドイッチを作ります。") 4 | for item in items: 5 | print(f" ...{item}をサンドイッチに追加しました。") 6 | print("サンドイッチができました!") 7 | 8 | 9 | make_sandwich('ベーコン', 'レタス', 'トマト') 10 | make_sandwich('ツナ', 'マヨネーズ') 11 | make_sandwich('ハム', 'チーズ', 'レタス', 'トマト', '玉子') 12 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter08/8_13_user_profile.py: -------------------------------------------------------------------------------- 1 | def build_profile(first, last, **user_info): 2 | """ユーザーの全情報を格納した辞書を作成する""" 3 | user_info['first_name'] = first 4 | user_info['last_name'] = last 5 | return user_info 6 | 7 | 8 | user_profile = build_profile('たかのり', '鈴木', 9 | location='東京', 10 | organization='PyCon JP Association', 11 | company='BeProud') 12 | 13 | print(user_profile) 14 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter08/8_14_cars.py: -------------------------------------------------------------------------------- 1 | def make_car(maker, model, **options): 2 | """自動車を表す辞書を作成する""" 3 | car_dict = { 4 | 'maker': maker.title(), 5 | 'model': model.title(), 6 | } 7 | for option, value in options.items(): 8 | car_dict[option] = value 9 | 10 | return car_dict 11 | 12 | 13 | subaru = make_car('スバル', 'レガシィ', color='ブルー', recorder=True) 14 | print(subaru) 15 | 16 | accord = make_car('honda', 'accord', year=1991, color='白', 17 | headlights='popup') 18 | print(accord) 19 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter08/8_15_printing_models.py: -------------------------------------------------------------------------------- 1 | from printing_functions import print_models, show_completed_models 2 | 3 | unprinted_designs = ['iPhoneケース', 'ロボットのペンダント', '12面体'] 4 | completed_models = [] 5 | 6 | print_models(unprinted_designs, completed_models) 7 | show_completed_models(completed_models) 8 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter08/8_1_message.py: -------------------------------------------------------------------------------- 1 | def display_message(): 2 | """この章で学んだことを出力する""" 3 | message = "コードを関数に格納する方法を学んでいます。" 4 | print(message) 5 | 6 | 7 | display_message() 8 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter08/8_2_favorite_book.py: -------------------------------------------------------------------------------- 1 | def favorite_book(title): 2 | """好きな本に関するメッセージを出力する""" 3 | print(f"私の好きな本は{title}です。") 4 | 5 | 6 | favorite_book('指輪物語') 7 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter08/8_3_tshirt.py: -------------------------------------------------------------------------------- 1 | def make_shirt(size, message): 2 | """作成するTシャツの情報を出力する""" 3 | print(f"\n{size}サイズのTシャツを作ります。") 4 | print(f'プリントするメッセージは「{message}」です。') 5 | 6 | 7 | make_shirt('M', '大好きPython!') 8 | make_shirt(message="Spam, Ham, Eggs", size='G-L') 9 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter08/8_4_large_shirts.py: -------------------------------------------------------------------------------- 1 | def make_shirt(size='L', message='I love Python'): 2 | """作成するTシャツの情報を出力する""" 3 | print(f"\n{size}サイズのTシャツを作ります。") 4 | print(f'プリントするメッセージは「{message}」です。') 5 | 6 | 7 | make_shirt() 8 | make_shirt(size='M') 9 | make_shirt('S', 'バグを憎んで人を憎まず') 10 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter08/8_5_cities.py: -------------------------------------------------------------------------------- 1 | def describe_city(city, country='日本'): 2 | """都市について説明する""" 3 | msg = f"{city}は{country}にあります。" 4 | print(msg) 5 | 6 | 7 | describe_city('京都') 8 | describe_city('レイキャビク', 'アイスランド') 9 | describe_city('札幌') 10 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter08/8_6_citi_names.py: -------------------------------------------------------------------------------- 1 | def city_country(city, country): 2 | """'Santiago, Chile' のような文字列を返す""" 3 | return f"{city.title()}, {country.title()}" 4 | 5 | 6 | city = city_country('santiago', 'chile') 7 | print(city) 8 | 9 | city = city_country('taipei', 'taiwan') 10 | print(city) 11 | 12 | city = city_country('kota kinabalu', 'malaysia') 13 | print(city) 14 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter08/8_7_album.py: -------------------------------------------------------------------------------- 1 | def make_album(artist, title, tracks=0): 2 | """アルバムに関する情報を含んだ辞書を作成する""" 3 | album_dict = { 4 | 'artist': artist.title(), 5 | 'title': title.title(), 6 | } 7 | if tracks: 8 | album_dict['tracks'] = tracks 9 | return album_dict 10 | 11 | 12 | album = make_album('steve reich', 'music for 18 musicians') 13 | print(album) 14 | 15 | album = make_album('大阪市音楽団', '宇宙の音楽') 16 | print(album) 17 | 18 | album = make_album('queen', 'a night at the opera', tracks=12) 19 | print(album) 20 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter08/8_8_user_albums.py: -------------------------------------------------------------------------------- 1 | def make_album(artist, title, tracks=0): 2 | """アルバムに関する情報を含んだ辞書を作成する""" 3 | album_dict = { 4 | 'artist': artist.title(), 5 | 'title': title.title(), 6 | } 7 | if tracks: 8 | album_dict['tracks'] = tracks 9 | return album_dict 10 | 11 | 12 | # 終了方法を通知する 13 | print("'quit' と入力すると終了します。") 14 | 15 | while True: 16 | title = input("\nアルバムの名前を教えてください: ") 17 | if title == 'quit': 18 | break 19 | 20 | artist = input("アーティストは誰ですか? ") 21 | if artist == 'quit': 22 | break 23 | 24 | album = make_album(artist, title) 25 | print(album) 26 | 27 | print("\n入力ありがとうございます!") 28 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter08/8_9_messages.py: -------------------------------------------------------------------------------- 1 | def show_messages(messages): 2 | """リストの中の各メッセージを出力する""" 3 | for message in messages: 4 | print(message) 5 | 6 | 7 | messages = ["こんにちは", "元気ですか?", "ビール飲みたい"] 8 | show_messages(messages) 9 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter08/printing_functions.py: -------------------------------------------------------------------------------- 1 | def print_models(unprinted_designs, completed_models): 2 | """ 3 | リストからなくなるまでデザインを3D印刷する 4 | 各デザインは印刷後に completed_models に移動する 5 | """ 6 | while unprinted_designs: 7 | current_design = unprinted_designs.pop() 8 | print(f"3D印刷中: {current_design}") 9 | completed_models.append(current_design) 10 | 11 | 12 | def show_completed_models(completed_models): 13 | """3D印刷されたすべてのモデルの情報を出力する""" 14 | print("\n以下のデザインが3D印刷されました") 15 | for completed_model in completed_models: 16 | print(completed_model) 17 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter09/9_10_imported_restaurant.py: -------------------------------------------------------------------------------- 1 | from restaurant import Restaurant 2 | 3 | restaurant = Restaurant('malaychan', '東南アジア料理') 4 | restaurant.describe_restaurant() 5 | restaurant.open_restaurant() 6 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter09/9_11_imported_admin.py: -------------------------------------------------------------------------------- 1 | from user import Admin 2 | 3 | takanory = Admin('takanori', 'suzuki', 'takanory', 'takanory@example.com', 4 | 'toshima-ku') 5 | takanory.describe_user() 6 | 7 | takanory_privileges = [ 8 | "投稿を追加する", 9 | "投稿を削除する", 10 | "ユーザーを利用禁止にする", 11 | ] 12 | takanory.privileges.privileges = takanory_privileges 13 | takanory.privileges.show_privileges() 14 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter09/9_12_multiple_modules.py: -------------------------------------------------------------------------------- 1 | from admin import Admin 2 | 3 | takanory = Admin('takanori', 'suzuki', 'takanory', 'takanory@example.com', 4 | 'toshima-ku') 5 | takanory.describe_user() 6 | 7 | takanory_privileges = [ 8 | "投稿を追加する", 9 | "投稿を削除する", 10 | "ユーザーを利用禁止にする", 11 | ] 12 | takanory.privileges.privileges = takanory_privileges 13 | takanory.privileges.show_privileges() 14 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter09/9_13_dice.py: -------------------------------------------------------------------------------- 1 | from random import randint 2 | 3 | 4 | class Die(): 5 | """サイコロを表すクラス""" 6 | 7 | def __init__(self, sides=6): 8 | """サイコロを初期化する""" 9 | self.sides = sides 10 | 11 | def roll_die(self): 12 | """サイコロの出た目(1〜面の数)を返す""" 13 | return randint(1, self.sides) 14 | 15 | 16 | # 6面のサイコロを作成し、10回転がした結果を出力する 17 | d6 = Die() 18 | 19 | results = [] 20 | for roll_num in range(10): 21 | result = d6.roll_die() 22 | results.append(result) 23 | print("6面サイコロを10回転がした結果") 24 | print(results) 25 | 26 | # 10面のサイコロを作成し、10回転がした結果を出力する 27 | d10 = Die(sides=10) 28 | 29 | results = [] 30 | for roll_num in range(10): 31 | result = d10.roll_die() 32 | results.append(result) 33 | print("\n10面サイコロを10回転が結果") 34 | print(results) 35 | 36 | # 20面のサイコロを作成し、10回転がした結果を出力する 37 | d20 = Die(sides=20) 38 | 39 | results = [] 40 | for roll_num in range(10): 41 | result = d20.roll_die() 42 | results.append(result) 43 | print("\n20面サイコロを10回転が結果") 44 | print(results) 45 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter09/9_14_lottery.py: -------------------------------------------------------------------------------- 1 | from random import choice 2 | 3 | possibilities = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e') 4 | 5 | winning_ticket = [] 6 | print("くじに当選した番号は...") 7 | 8 | # 同じ数字や文字を繰り返さないために while ループを使用する 9 | while len(winning_ticket) < 4: 10 | pulled_item = choice(possibilities) 11 | 12 | # 存在しない数字や文字の場合だけ、当選した番号のリストに追加する 13 | if pulled_item not in winning_ticket: 14 | print(f" 「{pulled_item}」を引きました!") 15 | winning_ticket.append(pulled_item) 16 | 17 | print(f"\n当選番号は {winning_ticket} です!") 18 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter09/9_1_restaurant.py: -------------------------------------------------------------------------------- 1 | class Restaurant(): 2 | """レストランを表すクラス""" 3 | 4 | def __init__(self, name, cuisine_type): 5 | """レストランを初期化する""" 6 | self.name = name.title() 7 | self.cuisine_type = cuisine_type 8 | 9 | def describe_restaurant(self): 10 | """レストランについての情報を出力する""" 11 | msg = f"{self.name}は素晴らしい{self.cuisine_type}を提供します。" 12 | print(f"\n{msg}") 13 | 14 | def open_restaurant(self): 15 | """レストランが開店したことを知らせるメッセージを出力する""" 16 | msg = f"{self.name}が開店しました。ぜひご来店ください!" 17 | print(f"\n{msg}") 18 | 19 | 20 | restaurant = Restaurant('malaychan', '東南アジア料理') 21 | print(restaurant.name) 22 | print(restaurant.cuisine_type) 23 | 24 | restaurant.describe_restaurant() 25 | restaurant.open_restaurant() 26 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter09/9_2_three_restaurants.py: -------------------------------------------------------------------------------- 1 | class Restaurant(): 2 | """レストランを表すクラス""" 3 | 4 | def __init__(self, name, cuisine_type): 5 | """レストランを初期化する""" 6 | self.name = name.title() 7 | self.cuisine_type = cuisine_type 8 | 9 | def describe_restaurant(self): 10 | """レストランについての情報を出力する""" 11 | msg = f"{self.name}は素晴らしい{self.cuisine_type}を提供します。" 12 | print(f"\n{msg}") 13 | 14 | def open_restaurant(self): 15 | """レストランが開店したことを知らせるメッセージを出力する""" 16 | msg = f"{self.name}が開店しました。ぜひご来店ください!" 17 | print(f"\n{msg}") 18 | 19 | 20 | restaurant = Restaurant('malaychan', '東南アジア料理') 21 | restaurant.describe_restaurant() 22 | 23 | restaurant = Restaurant('もうやん', 'カレーライス') 24 | restaurant.describe_restaurant() 25 | 26 | restaurant = Restaurant('かるかや', 'うどん') 27 | restaurant.describe_restaurant() 28 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter09/9_3_users.py: -------------------------------------------------------------------------------- 1 | class User(): 2 | """ユーザーのプロフィールを表すクラス""" 3 | 4 | def __init__(self, first_name, last_name, username, email, location): 5 | """ユーザーを初期化する""" 6 | self.first_name = first_name.title() 7 | self.last_name = last_name.title() 8 | self.username = username 9 | self.email = email 10 | self.location = location.title() 11 | 12 | def describe_user(self): 13 | """ユーザーの情報を出力する""" 14 | print(f"\n{self.first_name} {self.last_name}") 15 | print(f" ユーザー名: {self.username}") 16 | print(f" メールアドレス: {self.email}") 17 | print(f" 場所: {self.location}") 18 | 19 | def greet_user(self): 20 | """ユーザー宛のあいさつメッセージを出力する""" 21 | print(f"\nおかえりなさい{self.username}!") 22 | 23 | 24 | takanory = User('takanori', 'suzuki', 'takanory', 'takanory@example.com', 25 | 'toshima-ku') 26 | takanory.describe_user() 27 | takanory.greet_user() 28 | 29 | zenich = User('zenichiro', 'yasuda', 'zenich', 'zen@example.com', 'chofu') 30 | zenich.describe_user() 31 | zenich.greet_user() 32 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter09/9_4_number_served.py: -------------------------------------------------------------------------------- 1 | class Restaurant(): 2 | """レストランを表すクラス""" 3 | 4 | def __init__(self, name, cuisine_type): 5 | """レストランを初期化する""" 6 | self.name = name.title() 7 | self.cuisine_type = cuisine_type 8 | self.number_served = 0 9 | 10 | def describe_restaurant(self): 11 | """レストランについての情報を出力する""" 12 | msg = f"{self.name}は素晴らしい{self.cuisine_type}を提供します。" 13 | print(f"\n{msg}") 14 | 15 | def open_restaurant(self): 16 | """レストランが開店したことを知らせるメッセージを出力する""" 17 | msg = f"{self.name}が開店しました。ぜひご来店ください!" 18 | print(f"\n{msg}") 19 | 20 | def set_number_served(self, number_served): 21 | """料理を提供したお客さんの数を設定する""" 22 | self.number_served = number_served 23 | 24 | def increment_number_served(self, additional_served): 25 | """料理を提供したお客さんの数を増やす""" 26 | self.number_served += additional_served 27 | 28 | 29 | restaurant = Restaurant('malaychan', '東南アジア料理') 30 | restaurant.describe_restaurant() 31 | 32 | print(f"\n料理の提供数: {restaurant.number_served}") 33 | restaurant.number_served = 430 34 | print(f"料理の提供数: {restaurant.number_served}") 35 | 36 | restaurant.set_number_served(1236) 37 | print(f"料理の提供数: {restaurant.number_served}") 38 | 39 | restaurant.increment_number_served(248) 40 | print(f"料理の提供数: {restaurant.number_served}") 41 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter09/admin.py: -------------------------------------------------------------------------------- 1 | """管理者ユーザーを表すクラスの集まり""" 2 | 3 | from user2 import User 4 | 5 | 6 | class Admin(User): 7 | """管理権限を持ったユーザーを表すクラス""" 8 | 9 | def __init__(self, first_name, last_name, username, email, location): 10 | """管理者ユーザーを初期化する""" 11 | super().__init__(first_name, last_name, username, email, location) 12 | self.privileges = [] 13 | 14 | # 空の権限で初期化する 15 | self.privileges = Privileges() 16 | 17 | 18 | class Privileges(): 19 | """管理者の権限を格納するクラス""" 20 | 21 | def __init__(self, privileges=[]): 22 | self.privileges = privileges 23 | 24 | def show_privileges(self): 25 | """管理者が持っている権限を出力する""" 26 | print("\n権限の一覧") 27 | if self.privileges: 28 | for privilege in self.privileges: 29 | print(f"- {privilege}") 30 | else: 31 | print("- このユーザーには権限がありません。") 32 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter09/restaurant.py: -------------------------------------------------------------------------------- 1 | """レストランを表すクラス""" 2 | 3 | 4 | class Restaurant(): 5 | """レストランを表すクラス""" 6 | 7 | def __init__(self, name, cuisine_type): 8 | """レストランを初期化する""" 9 | self.name = name.title() 10 | self.cuisine_type = cuisine_type 11 | self.number_served = 0 12 | 13 | def describe_restaurant(self): 14 | """レストランについての情報を出力する""" 15 | msg = f"{self.name}は素晴らしい{self.cuisine_type}を提供します。" 16 | print(f"\n{msg}") 17 | 18 | def open_restaurant(self): 19 | """レストランが開店したことを知らせるメッセージを出力する""" 20 | msg = f"{self.name}が開店しました。ぜひご来店ください!" 21 | print(f"\n{msg}") 22 | 23 | def set_number_served(self, number_served): 24 | """料理を提供したお客さんの数を設定する""" 25 | self.number_served = number_served 26 | 27 | def increment_number_served(self, additional_served): 28 | """料理を提供したお客さんの数を増やす""" 29 | self.number_served += additional_served 30 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter09/user2.py: -------------------------------------------------------------------------------- 1 | """ユーザーのプロフィールを表すクラス""" 2 | 3 | 4 | class User(): 5 | """ユーザーのプロフィールを表すクラス""" 6 | 7 | def __init__(self, first_name, last_name, username, email, location): 8 | """ユーザーを初期化する""" 9 | self.first_name = first_name.title() 10 | self.last_name = last_name.title() 11 | self.username = username 12 | self.email = email 13 | self.location = location.title() 14 | self.login_attempts = 0 15 | 16 | def describe_user(self): 17 | """ユーザーの情報を出力する""" 18 | print(f"\n{self.first_name} {self.last_name}") 19 | print(f" ユーザー名: {self.username}") 20 | print(f" メールアドレス: {self.email}") 21 | print(f" 場所: {self.location}") 22 | 23 | def greet_user(self): 24 | """ユーザー宛のあいさつメッセージを出力する""" 25 | print(f"\nおかえりなさい{self.username}!") 26 | 27 | def increment_login_attempts(self): 28 | """ログイン試行回数を1増やす""" 29 | self.login_attempts += 1 30 | 31 | def reset_login_attempts(self): 32 | """ログイン試行回数を0にリセットする""" 33 | self.login_attempts = 0 34 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter10/10_10_common_words.py: -------------------------------------------------------------------------------- 1 | def count_common_words(filename, word): 2 | """テキスト内の単語の出現回数を数える。""" 3 | # 注意: これは本当に単純な近似値です。実際の出現回数よりも大きな数が返されるでしょう。 4 | try: 5 | with open(filename, encoding='utf-8') as f: 6 | contents = f.read() 7 | except FileNotFoundError: 8 | pass 9 | else: 10 | word_count = contents.lower().count(word) 11 | 12 | msg = f"単語'{word}'は{filename}内に約{word_count}回出現します。" 13 | print(msg) 14 | 15 | filename = 'alice.txt' 16 | count_common_words(filename, 'the') 17 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter10/10_11_favorite_number_read.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | with open('favorite_number.json') as f: 4 | number = json.load(f) 5 | 6 | print(f"あなたが好きな数字を知っています!それは{number}です。") 7 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter10/10_11_favorite_number_write.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | number = input("好きな数字は何ですか? ") 4 | 5 | with open('favorite_number.json', 'w') as f: 6 | json.dump(number, f) 7 | print("ありがとうございます! その数字を覚えておきます。") 8 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter10/10_12_favorite_number_remembered.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | try: 4 | with open('favorite_number.json') as f: 5 | number = json.load(f) 6 | except FileNotFoundError: 7 | number = input("好きな数字は何ですか? ") 8 | with open('favorite_number.json', 'w') as f: 9 | json.dump(number, f) 10 | print("ありがとうございます! その数字を覚えておきます。") 11 | else: 12 | print(f"あなたが好きな数字を知っています!それは{number}です。") 13 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter10/10_13_verify_user.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | def get_stored_username(): 4 | """保存されたユーザー名があれば取得する。""" 5 | filename = 'username.json' 6 | try: 7 | with open(filename) as f: 8 | username = json.load(f) 9 | except FileNotFoundError: 10 | return None 11 | else: 12 | return username 13 | 14 | def get_new_username(): 15 | """新たなユーザー名の入力を促す。""" 16 | username = input("あなたのお名前は? ") 17 | filename = 'username.json' 18 | with open(filename, 'w') as f: 19 | json.dump(username, f) 20 | return username 21 | 22 | def greet_user(): 23 | """ユーザー名であいさつする。""" 24 | username = get_stored_username() 25 | if username: 26 | correct = input(f"あなたは{username}さんですか? (y/n) ") 27 | if correct == 'y': 28 | print(f"おかえりなさい、{username}さん!") 29 | else: 30 | username = get_new_username() 31 | print(f"戻ってきたときにも名前を覚えていますよ、{username}さん!") 32 | else: 33 | username = get_new_username() 34 | print(f"戻ってきたときにも名前を覚えていますよ、{username}さん!") 35 | 36 | greet_user() 37 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter10/10_13_verify_user_cleaner.py: -------------------------------------------------------------------------------- 1 | # greet_user()関数の重複を解消したよりクリーンなバージョンの回答例 2 | # https://ehmatthes.github.io/pcc_2e/solutions/chapter_10/#10-13-verify-user 3 | # で紹介されている 4 | import json 5 | 6 | def get_stored_username(): 7 | """保存されたユーザー名があれば取得する。""" 8 | filename = 'username.json' 9 | try: 10 | with open(filename) as f: 11 | username = json.load(f) 12 | except FileNotFoundError: 13 | return None 14 | else: 15 | return username 16 | 17 | def get_new_username(): 18 | """新たなユーザー名の入力を促す。""" 19 | username = input("あなたのお名前は? ") 20 | filename = 'username.json' 21 | with open(filename, 'w') as f: 22 | json.dump(username, f) 23 | return username 24 | 25 | def greet_user(): 26 | """ユーザー名であいさつする。""" 27 | username = get_stored_username() 28 | if username: 29 | correct = input(f"あなたは{username}さんですか? (y/n) ") 30 | if correct == 'y': 31 | print(f"おかえりなさい、{username}さん!") 32 | return 33 | 34 | # usernameは取得できたが正しくないため、 35 | # 新たなusernameの入力を求める。 36 | username = get_new_username() 37 | print(f"戻ってきたときにも名前を覚えていますよ、{username}さん!") 38 | 39 | greet_user() 40 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter10/10_1_learning_python.py: -------------------------------------------------------------------------------- 1 | filename = 'learning_python.txt' 2 | 3 | print("--- ファイル全体を読み込む:") 4 | with open(filename) as f: 5 | contents = f.read() 6 | print(contents) 7 | 8 | print("\n--- ファイルの各行ををループ:") 9 | with open(filename) as f: 10 | for line in f: 11 | print(line.rstrip()) 12 | 13 | print("\n--- 各行をリストに格納する:") 14 | with open(filename) as f: 15 | lines = f.readlines() 16 | 17 | for line in lines: 18 | print(line.rstrip()) 19 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter10/10_2_learning_c.py: -------------------------------------------------------------------------------- 1 | filename = 'learning_python.txt' 2 | 3 | with open(filename) as f: 4 | lines = f.readlines() 5 | 6 | for line in lines: 7 | # 余分な空行を取り除いてから「Python」を「C言語」に置き換える。 8 | line = line.rstrip() 9 | print(line.replace('Python', 'C言語')) 10 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter10/10_3_guest.py: -------------------------------------------------------------------------------- 1 | name = input("お名前は? ") 2 | 3 | filename = 'guest.txt' 4 | 5 | with open(filename, 'w') as f: 6 | f.write(name) 7 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter10/10_4_guest_book.py: -------------------------------------------------------------------------------- 1 | filename = 'guest_book.txt' 2 | 3 | print("終了するには '終了' と入力してください。") 4 | while True: 5 | name = input("\nお名前は? ") 6 | if name == '終了': 7 | break 8 | else: 9 | with open(filename, 'a') as f: 10 | f.write(f"{name}\n") 11 | print(f"こんにちは{name}さん。あなたはゲストブックに追加されました。") 12 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter10/10_5_programming_poll.py: -------------------------------------------------------------------------------- 1 | filename = 'programming_poll.txt' 2 | 3 | responses = [] 4 | while True: 5 | response = input("\nプログラミングが好きな理由は何ですか? ") 6 | responses.append(response) 7 | 8 | continue_poll = input("誰か他に回答する人はいますか? (y/n) ") 9 | if continue_poll != 'y': 10 | break 11 | 12 | with open(filename, 'a') as f: 13 | for response in responses: 14 | f.write(f"{response}\n") 15 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter10/10_6_addition.py: -------------------------------------------------------------------------------- 1 | try: 2 | x = input("何か数字を入力してください: ") 3 | x = int(x) 4 | 5 | y = input("別の数字を入力してください: ") 6 | y = int(y) 7 | except ValueError: 8 | print("すみません、数字でお願いします。") 9 | else: 10 | sum = x + y 11 | print(f"{x}と{y}の合計は{sum}です。") 12 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter10/10_7_addition_calculator.py: -------------------------------------------------------------------------------- 1 | print("終了するにはいつでも 'q' を入力してください。\n") 2 | 3 | while True: 4 | try: 5 | x = input("\n何か数字を入力してください: ") 6 | if x == 'q': 7 | break 8 | 9 | x = int(x) 10 | 11 | y = input("別の数字を入力してください: ") 12 | if y == 'q': 13 | break 14 | 15 | y = int(y) 16 | 17 | except ValueError: 18 | print("すみません、数字でお願いします。") 19 | 20 | else: 21 | sum = x + y 22 | print(f"{x}と{y}の合計は{sum}です。") 23 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter10/10_8_cats_and_dogs.py: -------------------------------------------------------------------------------- 1 | filenames = ['cats.txt', 'dogs.txt'] 2 | 3 | for filename in filenames: 4 | 5 | try: 6 | with open(filename) as f: 7 | contents = f.read() 8 | 9 | except FileNotFoundError: 10 | pass 11 | 12 | else: 13 | print(f"\n読込中のファイル: {filename}") 14 | print(contents) 15 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter10/10_9_silent_cats_and_dogs.py: -------------------------------------------------------------------------------- 1 | filenames = ['cats.txt', 'dogs.txt'] 2 | 3 | for filename in filenames: 4 | print(f"\n読込中のファイル: {filename}") 5 | try: 6 | with open(filename) as f: 7 | contents = f.read() 8 | print(contents) 9 | except FileNotFoundError: 10 | print(" すみません、ファイルが見つかりませんでした。") 11 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter10/cats.txt: -------------------------------------------------------------------------------- 1 | タマ 2 | ドラ 3 | コテツ 4 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter10/dogs.txt: -------------------------------------------------------------------------------- 1 | 小太郎 2 | ハチ 3 | シロ 4 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter10/favorite_number.json: -------------------------------------------------------------------------------- 1 | "442" -------------------------------------------------------------------------------- /やってみよう_必修編/chapter10/guest.txt: -------------------------------------------------------------------------------- 1 | 安田善一郎 -------------------------------------------------------------------------------- /やってみよう_必修編/chapter10/guest_book.txt: -------------------------------------------------------------------------------- 1 | 安田善一郎 2 | 鈴木たかのり 3 | 清水川貴之 4 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter10/learning_python.txt: -------------------------------------------------------------------------------- 1 | Pythonでできることは好きなだけ情報を格納することです。 2 | Pythonでできることはバラバラの情報を結合することです。 3 | Pythonでできることは現実世界のモデルを構築することです。 4 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter10/programming_poll.txt: -------------------------------------------------------------------------------- 1 | 新しく何かを作り出す楽しさがある 2 | 頭の中で考えたことが形になっていくのを見ることが面白い 3 | プログラミングをするときは常に新鮮な気分でいられる 4 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter10/username.json: -------------------------------------------------------------------------------- 1 | "\u305c\u3093" -------------------------------------------------------------------------------- /やってみよう_必修編/chapter11/11_1_test_cities.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | from city_functions import city_country 4 | 5 | 6 | class CitiesTestCase(unittest.TestCase): 7 | """city_functions.pyをテストする""" 8 | 9 | def test_city_country(self): 10 | """シンプルな都市名と国名の組が動作するか確認する""" 11 | santiago_chile = city_country('santiago', 'chile') 12 | self.assertEqual(santiago_chile, 'Santiago, Chile') 13 | 14 | 15 | if __name__ == '__main__': 16 | unittest.main() 17 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter11/11_2_test_cities.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | from city_functions2 import city_country 4 | 5 | 6 | class CitiesTestCase(unittest.TestCase): 7 | """city_functions2.pyをテストする""" 8 | 9 | def test_city_country(self): 10 | """シンプルな都市名と国名の組が動作するか確認する""" 11 | santiago_chile = city_country('santiago', 'chile') 12 | self.assertEqual(santiago_chile, 'Santiago, Chile') 13 | 14 | def test_city_country_population(self): 15 | """人口を含んでも動作するかを確認する""" 16 | santiago_chile = city_country('santiago', 'chile', 17 | population=5_000_000) 18 | self.assertEqual(santiago_chile, 'Santiago, Chile - 人口 5000000') 19 | 20 | 21 | if __name__ == '__main__': 22 | unittest.main() 23 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter11/11_3_test_employee.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | from employee import Employee 4 | 5 | 6 | class TestEmployee(unittest.TestCase): 7 | """employeeモジュールをテストする""" 8 | 9 | def setUp(self): 10 | """テスト用の従業員を作成する""" 11 | self.takanory = Employee('takanori', 'suzuki', 6_500_000) 12 | 13 | def test_give_default_raise(self): 14 | """デフォルト金額での昇給が正しく動作することを確認する""" 15 | self.takanory.give_raise() 16 | self.assertEqual(self.takanory.salary, 7_000_000) 17 | 18 | def test_give_custom_raise(self): 19 | """指定した金額での昇給が正しく動作することを確認する""" 20 | self.takanory.give_raise(1_000_000) 21 | self.assertEqual(self.takanory.salary, 7_500_000) 22 | 23 | 24 | if __name__ == '__main__': 25 | unittest.main() 26 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter11/city_functions.py: -------------------------------------------------------------------------------- 1 | """都市に関する情報を返す関数""" 2 | 3 | 4 | def city_country(city, country): 5 | """'Santiago, Chile'のような文字列を返す""" 6 | return f"{city.title()}, {country.title()}" 7 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter11/city_functions2.py: -------------------------------------------------------------------------------- 1 | """都市に関する情報を返す関数""" 2 | 3 | 4 | def city_country(city, country, population=0): 5 | """'Santiago, Chile - 人口 5000000'のような文字列を返す""" 6 | output_string = f"{city.title()}, {country.title()}" 7 | if population: 8 | output_string += f" - 人口 {population}" 9 | return output_string 10 | -------------------------------------------------------------------------------- /やってみよう_必修編/chapter11/employee.py: -------------------------------------------------------------------------------- 1 | class Employee(): 2 | """従業員を表すクラス""" 3 | 4 | def __init__(self, f_name, l_name, salary): 5 | """従業員を初期化する""" 6 | self.first = f_name.title() 7 | self.last = l_name.title() 8 | self.salary = salary 9 | 10 | def give_raise(self, amount=500000): 11 | """従業員を給与を増やす""" 12 | self.salary += amount 13 | -------------------------------------------------------------------------------- /実践編/appendixB/mpl_squares.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | from matplotlib import rcParams 3 | 4 | input_values = [1, 2, 3, 4, 5] 5 | squares = [1, 4, 9, 16, 25] 6 | 7 | plt.style.use('seaborn') 8 | rcParams['font.family'] = 'IPAexGothic' 9 | fig, ax = plt.subplots() 10 | ax.plot(input_values, squares, linewidth=3) 11 | 12 | # グラフのタイトルと軸のラベルを設定する 13 | ax.set_title("平方数", fontsize=24) 14 | ax.set_xlabel("値", fontsize=14) 15 | ax.set_ylabel("2乗した値", fontsize=14) 16 | 17 | # 目盛りラベルのサイズを設定する 18 | ax.tick_params(axis='both', labelsize=14) 19 | 20 | plt.show() 21 | -------------------------------------------------------------------------------- /実践編/chapter01/1_ゲームのプロジェクトを開始する/alien_invasion.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | import pygame 4 | 5 | from settings import Settings 6 | 7 | class AlienInvasion: 8 | """ゲームのアセットと動作を管理する全体的なクラス""" 9 | 10 | def __init__(self): 11 | """ゲームを初期化し、ゲームのリソースを作成する""" 12 | pygame.init() 13 | self.settings = Settings() 14 | 15 | self.screen = pygame.display.set_mode( 16 | (self.settings.screen_width, self.settings.screen_height)) 17 | pygame.display.set_caption("エイリアン侵略") 18 | 19 | def run_game(self): 20 | """ゲームのメインループを開始する""" 21 | while True: 22 | # キーボードとマウスのイベントを監視する 23 | for event in pygame.event.get(): 24 | if event.type == pygame.QUIT: 25 | sys.exit() 26 | 27 | # ループを通過するたびに画面を再描画する 28 | self.screen.fill(self.settings.bg_color) 29 | 30 | # 最新の状態の画面を表示する 31 | pygame.display.flip() 32 | 33 | if __name__ == '__main__': 34 | # ゲームのインスタンスを作成し、ゲームを実行する 35 | ai = AlienInvasion() 36 | ai.run_game() 37 | -------------------------------------------------------------------------------- /実践編/chapter01/1_ゲームのプロジェクトを開始する/settings.py: -------------------------------------------------------------------------------- 1 | class Settings: 2 | """エイリアン侵略の全設定を格納するクラス""" 3 | 4 | def __init__(self): 5 | """ゲームの初期設定""" 6 | # 画面に関する設定 7 | self.screen_width = 1200 8 | self.screen_height = 800 9 | self.bg_color = (230, 230, 230) 10 | -------------------------------------------------------------------------------- /実践編/chapter01/2_宇宙船の画像を追加する/alien_invasion.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | import pygame 4 | 5 | from settings import Settings 6 | from ship import Ship 7 | 8 | class AlienInvasion: 9 | """ゲームのアセットと動作を管理する全体的なクラス""" 10 | 11 | def __init__(self): 12 | """ゲームを初期化し、ゲームのリソースを作成する""" 13 | pygame.init() 14 | self.settings = Settings() 15 | 16 | self.screen = pygame.display.set_mode( 17 | (self.settings.screen_width, self.settings.screen_height)) 18 | pygame.display.set_caption("エイリアン侵略") 19 | 20 | self.ship = Ship(self) 21 | 22 | def run_game(self): 23 | """ゲームのメインループを開始する""" 24 | while True: 25 | # キーボードとマウスのイベントを監視する 26 | for event in pygame.event.get(): 27 | if event.type == pygame.QUIT: 28 | sys.exit() 29 | 30 | # ループを通過するたびに画面を再描画する 31 | self.screen.fill(self.settings.bg_color) 32 | self.ship.blitme() 33 | 34 | # 最新の状態の画面を表示する 35 | pygame.display.flip() 36 | 37 | if __name__ == '__main__': 38 | # ゲームのインスタンスを作成し、ゲームを実行する 39 | ai = AlienInvasion() 40 | ai.run_game() 41 | -------------------------------------------------------------------------------- /実践編/chapter01/2_宇宙船の画像を追加する/images/ship.bmp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/takanory/saitan-python/8196a91a9aac5011bc29782381b93f143b0ae25a/実践編/chapter01/2_宇宙船の画像を追加する/images/ship.bmp -------------------------------------------------------------------------------- /実践編/chapter01/2_宇宙船の画像を追加する/settings.py: -------------------------------------------------------------------------------- 1 | class Settings: 2 | """エイリアン侵略の全設定を格納するクラス""" 3 | 4 | def __init__(self): 5 | """ゲームの初期設定""" 6 | # 画面に関する設定 7 | self.screen_width = 1200 8 | self.screen_height = 800 9 | self.bg_color = (230, 230, 230) 10 | -------------------------------------------------------------------------------- /実践編/chapter01/2_宇宙船の画像を追加する/ship.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | 3 | class Ship: 4 | """宇宙船を管理するクラス""" 5 | 6 | def __init__(self, ai_game): 7 | """宇宙船を初期化し、開始時の位置を設定する""" 8 | self.screen = ai_game.screen 9 | self.screen_rect = ai_game.screen.get_rect() 10 | 11 | # 宇宙船の画像を読み込み、サイズを取得する 12 | self.image = pygame.image.load('images/ship.bmp') 13 | self.rect = self.image.get_rect() 14 | 15 | # 新しい宇宙船を画面下部の中央に配置する 16 | self.rect.midbottom = self.screen_rect.midbottom 17 | 18 | def blitme(self): 19 | """宇宙船を現在位置に描画する""" 20 | self.screen.blit(self.image, self.rect) 21 | -------------------------------------------------------------------------------- /実践編/chapter01/3_リファクタリング/alien_invasion.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | import pygame 4 | 5 | from settings import Settings 6 | from ship import Ship 7 | 8 | class AlienInvasion: 9 | """ゲームのアセットと動作を管理する全体的なクラス""" 10 | 11 | def __init__(self): 12 | """ゲームを初期化し、ゲームのリソースを作成する""" 13 | pygame.init() 14 | self.settings = Settings() 15 | 16 | self.screen = pygame.display.set_mode( 17 | (self.settings.screen_width, self.settings.screen_height)) 18 | pygame.display.set_caption("エイリアン侵略") 19 | 20 | self.ship = Ship(self) 21 | 22 | def run_game(self): 23 | """ゲームのメインループを開始する""" 24 | while True: 25 | self._check_events() 26 | self._update_screen() 27 | 28 | def _check_events(self): 29 | """キーボードとマウスのイベントに対応する""" 30 | for event in pygame.event.get(): 31 | if event.type == pygame.QUIT: 32 | sys.exit() 33 | 34 | def _update_screen(self): 35 | """画面上の画像を更新し、新しい画面に切り替える""" 36 | self.screen.fill(self.settings.bg_color) 37 | self.ship.blitme() 38 | 39 | pygame.display.flip() 40 | 41 | if __name__ == '__main__': 42 | # ゲームのインスタンスを作成し、ゲームを実行する 43 | ai = AlienInvasion() 44 | ai.run_game() 45 | -------------------------------------------------------------------------------- /実践編/chapter01/3_リファクタリング/images/ship.bmp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/takanory/saitan-python/8196a91a9aac5011bc29782381b93f143b0ae25a/実践編/chapter01/3_リファクタリング/images/ship.bmp -------------------------------------------------------------------------------- /実践編/chapter01/3_リファクタリング/settings.py: -------------------------------------------------------------------------------- 1 | class Settings: 2 | """エイリアン侵略の全設定を格納するクラス""" 3 | 4 | def __init__(self): 5 | """ゲームの初期設定""" 6 | # 画面に関する設定 7 | self.screen_width = 1200 8 | self.screen_height = 800 9 | self.bg_color = (230, 230, 230) 10 | -------------------------------------------------------------------------------- /実践編/chapter01/3_リファクタリング/ship.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | 3 | class Ship: 4 | """宇宙船を管理するクラス""" 5 | 6 | def __init__(self, ai_game): 7 | """宇宙船を初期化し、開始時の位置を設定する""" 8 | self.screen = ai_game.screen 9 | self.screen_rect = ai_game.screen.get_rect() 10 | 11 | # 宇宙船の画像を読み込み、サイズを取得する 12 | self.image = pygame.image.load('images/ship.bmp') 13 | self.rect = self.image.get_rect() 14 | 15 | # 新しい宇宙船を画面下部の中央に配置する 16 | self.rect.midbottom = self.screen_rect.midbottom 17 | 18 | def blitme(self): 19 | """宇宙船を現在位置に描画する""" 20 | self.screen.blit(self.image, self.rect) 21 | -------------------------------------------------------------------------------- /実践編/chapter01/4_宇宙船を操縦する/images/ship.bmp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/takanory/saitan-python/8196a91a9aac5011bc29782381b93f143b0ae25a/実践編/chapter01/4_宇宙船を操縦する/images/ship.bmp -------------------------------------------------------------------------------- /実践編/chapter01/4_宇宙船を操縦する/settings.py: -------------------------------------------------------------------------------- 1 | class Settings: 2 | """エイリアン侵略の全設定を格納するクラス""" 3 | 4 | def __init__(self): 5 | """ゲームの初期設定""" 6 | # 画面に関する設定 7 | self.screen_width = 1200 8 | self.screen_height = 800 9 | self.bg_color = (230, 230, 230) 10 | 11 | # 宇宙船の設定 12 | self.ship_speed = 1.5 13 | -------------------------------------------------------------------------------- /実践編/chapter01/4_宇宙船を操縦する/ship.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | 3 | class Ship: 4 | """宇宙船を管理するクラス""" 5 | 6 | def __init__(self, ai_game): 7 | """宇宙船を初期化し、開始時の位置を設定する""" 8 | self.screen = ai_game.screen 9 | self.settings = ai_game.settings 10 | self.screen_rect = ai_game.screen.get_rect() 11 | 12 | # 宇宙船の画像を読み込み、サイズを取得する 13 | self.image = pygame.image.load('images/ship.bmp') 14 | self.rect = self.image.get_rect() 15 | 16 | # 新しい宇宙船を画面下部の中央に配置する 17 | self.rect.midbottom = self.screen_rect.midbottom 18 | 19 | # 宇宙船の水平位置の浮動小数点数を格納する 20 | self.x = float(self.rect.x) 21 | 22 | # 左右の移動フラグ 23 | self.moving_right = False 24 | self.moving_left = False 25 | 26 | def update(self): 27 | """左右の移動フラグによって宇宙船の位置を更新する""" 28 | # 宇宙船のxの値を更新する(rectではない) 29 | if self.moving_right and self.rect.right < self.screen_rect.right: 30 | self.x += self.settings.ship_speed 31 | if self.moving_left and self.rect.left > 0: 32 | self.x -= self.settings.ship_speed 33 | 34 | # self.xからrectオブジェクトの位置を更新する 35 | self.rect.x = self.x 36 | 37 | def blitme(self): 38 | """宇宙船を現在位置に描画する""" 39 | self.screen.blit(self.image, self.rect) 40 | -------------------------------------------------------------------------------- /実践編/chapter01/5_弾を発射する/bullet.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | from pygame.sprite import Sprite 3 | 4 | class Bullet(Sprite): 5 | """宇宙船から発射される弾を管理するクラス""" 6 | 7 | def __init__(self, ai_game): 8 | """宇宙船の現在の位置から弾のオブジェクトを生成する""" 9 | super().__init__() 10 | self.screen = ai_game.screen 11 | self.settings = ai_game.settings 12 | self.color = self.settings.bullet_color 13 | 14 | # 弾のrectを(0, 0)の位置に作成してから、正しい位置を設定する 15 | self.rect = pygame.Rect(0, 0, self.settings.bullet_width, 16 | self.settings.bullet_height) 17 | self.rect.midtop = ai_game.ship.rect.midtop 18 | 19 | # 弾の位置を浮動小数点数で保存する 20 | self.y = float(self.rect.y) 21 | 22 | def update(self): 23 | """画面上の弾を移動する""" 24 | # 弾の浮動小数点数での位置を更新する 25 | self.y -= self.settings.bullet_speed 26 | # rectの位置を更新する 27 | self.rect.y = self.y 28 | 29 | def draw_bullet(self): 30 | """画面に弾を描画する""" 31 | pygame.draw.rect(self.screen, self.color, self.rect) 32 | -------------------------------------------------------------------------------- /実践編/chapter01/5_弾を発射する/images/ship.bmp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/takanory/saitan-python/8196a91a9aac5011bc29782381b93f143b0ae25a/実践編/chapter01/5_弾を発射する/images/ship.bmp -------------------------------------------------------------------------------- /実践編/chapter01/5_弾を発射する/settings.py: -------------------------------------------------------------------------------- 1 | class Settings: 2 | """エイリアン侵略の全設定を格納するクラス""" 3 | 4 | def __init__(self): 5 | """ゲームの初期設定""" 6 | # 画面に関する設定 7 | self.screen_width = 1200 8 | self.screen_height = 800 9 | self.bg_color = (230, 230, 230) 10 | 11 | # 宇宙船の設定 12 | self.ship_speed = 1.5 13 | 14 | # 弾の設定 15 | self.bullet_speed = 1.0 16 | self.bullet_width = 3 17 | self.bullet_height = 15 18 | self.bullet_color = (60, 60, 60) 19 | self.bullets_allowed = 3 20 | -------------------------------------------------------------------------------- /実践編/chapter01/5_弾を発射する/ship.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | 3 | class Ship: 4 | """宇宙船を管理するクラス""" 5 | 6 | def __init__(self, ai_game): 7 | """宇宙船を初期化し、開始時の位置を設定する""" 8 | self.screen = ai_game.screen 9 | self.settings = ai_game.settings 10 | self.screen_rect = ai_game.screen.get_rect() 11 | 12 | # 宇宙船の画像を読み込み、サイズを取得する 13 | self.image = pygame.image.load('images/ship.bmp') 14 | self.rect = self.image.get_rect() 15 | 16 | # 新しい宇宙船を画面下部の中央に配置する 17 | self.rect.midbottom = self.screen_rect.midbottom 18 | 19 | # 宇宙船の水平位置の浮動小数点数を格納する 20 | self.x = float(self.rect.x) 21 | 22 | # 左右の移動フラグ 23 | self.moving_right = False 24 | self.moving_left = False 25 | 26 | def update(self): 27 | """左右の移動フラグによって宇宙船の位置を更新する""" 28 | # 宇宙船のxの値を更新する(rectではない) 29 | if self.moving_right and self.rect.right < self.screen_rect.right: 30 | self.x += self.settings.ship_speed 31 | if self.moving_left and self.rect.left > 0: 32 | self.x -= self.settings.ship_speed 33 | 34 | # self.xからrectオブジェクトの位置を更新する 35 | self.rect.x = self.x 36 | 37 | def blitme(self): 38 | """宇宙船を現在位置に描画する""" 39 | self.screen.blit(self.image, self.rect) 40 | -------------------------------------------------------------------------------- /実践編/chapter02/1_最初のエイリアンを生成する/alien.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | from pygame.sprite import Sprite 3 | 4 | class Alien(Sprite): 5 | """艦隊の中の1匹のエイリアンを表すクラス""" 6 | 7 | def __init__(self, ai_game): 8 | """エイリアンを初期化し、開始時の位置を設定する""" 9 | super().__init__() 10 | self.screen = ai_game.screen 11 | 12 | # エイリアンの画像を読み込み、サイズを取得する 13 | self.image = pygame.image.load('images/alien.bmp') 14 | self.rect = self.image.get_rect() 15 | 16 | # 新しいエイリアンを画面の左上の近くに配置する 17 | self.rect.x = self.rect.width 18 | self.rect.y = self.rect.height 19 | 20 | # エイリアンの実際の位置を格納する 21 | self.x = float(self.rect.x) 22 | -------------------------------------------------------------------------------- /実践編/chapter02/1_最初のエイリアンを生成する/bullet.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | from pygame.sprite import Sprite 3 | 4 | class Bullet(Sprite): 5 | """宇宙船から発射される弾を管理するクラス""" 6 | 7 | def __init__(self, ai_game): 8 | """宇宙船の現在の位置から弾のオブジェクトを生成する""" 9 | super().__init__() 10 | self.screen = ai_game.screen 11 | self.settings = ai_game.settings 12 | self.color = self.settings.bullet_color 13 | 14 | # 弾のrectを(0, 0)の位置に作成してから、正しい位置を設定する 15 | self.rect = pygame.Rect(0, 0, self.settings.bullet_width, 16 | self.settings.bullet_height) 17 | self.rect.midtop = ai_game.ship.rect.midtop 18 | 19 | # 弾の位置を浮動小数点数で保存する 20 | self.y = float(self.rect.y) 21 | 22 | def update(self): 23 | """画面上の弾を移動する""" 24 | # 弾の浮動小数点数での位置を更新する 25 | self.y -= self.settings.bullet_speed 26 | # rectの位置を更新する 27 | self.rect.y = self.y 28 | 29 | def draw_bullet(self): 30 | """画面に弾を描画する""" 31 | pygame.draw.rect(self.screen, self.color, self.rect) 32 | -------------------------------------------------------------------------------- /実践編/chapter02/1_最初のエイリアンを生成する/images/alien.bmp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/takanory/saitan-python/8196a91a9aac5011bc29782381b93f143b0ae25a/実践編/chapter02/1_最初のエイリアンを生成する/images/alien.bmp -------------------------------------------------------------------------------- /実践編/chapter02/1_最初のエイリアンを生成する/images/ship.bmp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/takanory/saitan-python/8196a91a9aac5011bc29782381b93f143b0ae25a/実践編/chapter02/1_最初のエイリアンを生成する/images/ship.bmp -------------------------------------------------------------------------------- /実践編/chapter02/1_最初のエイリアンを生成する/settings.py: -------------------------------------------------------------------------------- 1 | class Settings: 2 | """エイリアン侵略の全設定を格納するクラス""" 3 | 4 | def __init__(self): 5 | """ゲームの初期設定""" 6 | # 画面に関する設定 7 | self.screen_width = 1200 8 | self.screen_height = 800 9 | self.bg_color = (230, 230, 230) 10 | 11 | # 宇宙船の設定 12 | self.ship_speed = 1.5 13 | 14 | # 弾の設定 15 | self.bullet_speed = 1.0 16 | self.bullet_width = 3 17 | self.bullet_height = 15 18 | self.bullet_color = (60, 60, 60) 19 | self.bullets_allowed = 3 20 | -------------------------------------------------------------------------------- /実践編/chapter02/1_最初のエイリアンを生成する/ship.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | 3 | class Ship: 4 | """宇宙船を管理するクラス""" 5 | 6 | def __init__(self, ai_game): 7 | """宇宙船を初期化し、開始時の位置を設定する""" 8 | self.screen = ai_game.screen 9 | self.settings = ai_game.settings 10 | self.screen_rect = ai_game.screen.get_rect() 11 | 12 | # 宇宙船の画像を読み込み、サイズを取得する 13 | self.image = pygame.image.load('images/ship.bmp') 14 | self.rect = self.image.get_rect() 15 | 16 | # 新しい宇宙船を画面下部の中央に配置する 17 | self.rect.midbottom = self.screen_rect.midbottom 18 | 19 | # 宇宙船の水平位置の浮動小数点数を格納する 20 | self.x = float(self.rect.x) 21 | 22 | # 左右の移動フラグ 23 | self.moving_right = False 24 | self.moving_left = False 25 | 26 | def update(self): 27 | """左右の移動フラグによって宇宙船の位置を更新する""" 28 | # 宇宙船のxの値を更新する(rectではない) 29 | if self.moving_right and self.rect.right < self.screen_rect.right: 30 | self.x += self.settings.ship_speed 31 | if self.moving_left and self.rect.left > 0: 32 | self.x -= self.settings.ship_speed 33 | 34 | # self.xからrectオブジェクトの位置を更新する 35 | self.rect.x = self.x 36 | 37 | def blitme(self): 38 | """宇宙船を現在位置に描画する""" 39 | self.screen.blit(self.image, self.rect) 40 | -------------------------------------------------------------------------------- /実践編/chapter02/2_エイリアンの艦隊を編成する/alien.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | from pygame.sprite import Sprite 3 | 4 | class Alien(Sprite): 5 | """艦隊の中の1匹のエイリアンを表すクラス""" 6 | 7 | def __init__(self, ai_game): 8 | """エイリアンを初期化し、開始時の位置を設定する""" 9 | super().__init__() 10 | self.screen = ai_game.screen 11 | 12 | # エイリアンの画像を読み込み、サイズを取得する 13 | self.image = pygame.image.load('images/alien.bmp') 14 | self.rect = self.image.get_rect() 15 | 16 | # 新しいエイリアンを画面の左上の近くに配置する 17 | self.rect.x = self.rect.width 18 | self.rect.y = self.rect.height 19 | 20 | # エイリアンの実際の位置を格納する 21 | self.x = float(self.rect.x) 22 | -------------------------------------------------------------------------------- /実践編/chapter02/2_エイリアンの艦隊を編成する/bullet.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | from pygame.sprite import Sprite 3 | 4 | class Bullet(Sprite): 5 | """宇宙船から発射される弾を管理するクラス""" 6 | 7 | def __init__(self, ai_game): 8 | """宇宙船の現在の位置から弾のオブジェクトを生成する""" 9 | super().__init__() 10 | self.screen = ai_game.screen 11 | self.settings = ai_game.settings 12 | self.color = self.settings.bullet_color 13 | 14 | # 弾のrectを(0, 0)の位置に作成してから、正しい位置を設定する 15 | self.rect = pygame.Rect(0, 0, self.settings.bullet_width, 16 | self.settings.bullet_height) 17 | self.rect.midtop = ai_game.ship.rect.midtop 18 | 19 | # 弾の位置を浮動小数点数で保存する 20 | self.y = float(self.rect.y) 21 | 22 | def update(self): 23 | """画面上の弾を移動する""" 24 | # 弾の浮動小数点数での位置を更新する 25 | self.y -= self.settings.bullet_speed 26 | # rectの位置を更新する 27 | self.rect.y = self.y 28 | 29 | def draw_bullet(self): 30 | """画面に弾を描画する""" 31 | pygame.draw.rect(self.screen, self.color, self.rect) 32 | -------------------------------------------------------------------------------- /実践編/chapter02/2_エイリアンの艦隊を編成する/images/alien.bmp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/takanory/saitan-python/8196a91a9aac5011bc29782381b93f143b0ae25a/実践編/chapter02/2_エイリアンの艦隊を編成する/images/alien.bmp -------------------------------------------------------------------------------- /実践編/chapter02/2_エイリアンの艦隊を編成する/images/ship.bmp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/takanory/saitan-python/8196a91a9aac5011bc29782381b93f143b0ae25a/実践編/chapter02/2_エイリアンの艦隊を編成する/images/ship.bmp -------------------------------------------------------------------------------- /実践編/chapter02/2_エイリアンの艦隊を編成する/settings.py: -------------------------------------------------------------------------------- 1 | class Settings: 2 | """エイリアン侵略の全設定を格納するクラス""" 3 | 4 | def __init__(self): 5 | """ゲームの初期設定""" 6 | # 画面に関する設定 7 | self.screen_width = 1200 8 | self.screen_height = 800 9 | self.bg_color = (230, 230, 230) 10 | 11 | # 宇宙船の設定 12 | self.ship_speed = 1.5 13 | 14 | # 弾の設定 15 | self.bullet_speed = 1.0 16 | self.bullet_width = 3 17 | self.bullet_height = 15 18 | self.bullet_color = (60, 60, 60) 19 | self.bullets_allowed = 3 20 | -------------------------------------------------------------------------------- /実践編/chapter02/2_エイリアンの艦隊を編成する/ship.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | 3 | class Ship: 4 | """宇宙船を管理するクラス""" 5 | 6 | def __init__(self, ai_game): 7 | """宇宙船を初期化し、開始時の位置を設定する""" 8 | self.screen = ai_game.screen 9 | self.settings = ai_game.settings 10 | self.screen_rect = ai_game.screen.get_rect() 11 | 12 | # 宇宙船の画像を読み込み、サイズを取得する 13 | self.image = pygame.image.load('images/ship.bmp') 14 | self.rect = self.image.get_rect() 15 | 16 | # 新しい宇宙船を画面下部の中央に配置する 17 | self.rect.midbottom = self.screen_rect.midbottom 18 | 19 | # 宇宙船の水平位置の浮動小数点数を格納する 20 | self.x = float(self.rect.x) 21 | 22 | # 左右の移動フラグ 23 | self.moving_right = False 24 | self.moving_left = False 25 | 26 | def update(self): 27 | """左右の移動フラグによって宇宙船の位置を更新する""" 28 | # 宇宙船のxの値を更新する(rectではない) 29 | if self.moving_right and self.rect.right < self.screen_rect.right: 30 | self.x += self.settings.ship_speed 31 | if self.moving_left and self.rect.left > 0: 32 | self.x -= self.settings.ship_speed 33 | 34 | # self.xからrectオブジェクトの位置を更新する 35 | self.rect.x = self.x 36 | 37 | def blitme(self): 38 | """宇宙船を現在位置に描画する""" 39 | self.screen.blit(self.image, self.rect) 40 | -------------------------------------------------------------------------------- /実践編/chapter02/3_艦隊を動かす/alien.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | from pygame.sprite import Sprite 3 | 4 | class Alien(Sprite): 5 | """艦隊の中の1匹のエイリアンを表すクラス""" 6 | 7 | def __init__(self, ai_game): 8 | """エイリアンを初期化し、開始時の位置を設定する""" 9 | super().__init__() 10 | self.screen = ai_game.screen 11 | self.settings = ai_game.settings 12 | 13 | # エイリアンの画像を読み込み、サイズを取得する 14 | self.image = pygame.image.load('images/alien.bmp') 15 | self.rect = self.image.get_rect() 16 | 17 | # 新しいエイリアンを画面の左上の近くに配置する 18 | self.rect.x = self.rect.width 19 | self.rect.y = self.rect.height 20 | 21 | # エイリアンの実際の位置を格納する 22 | self.x = float(self.rect.x) 23 | 24 | def check_edges(self): 25 | """エイリアンが画面の端に達した場合は True を返す""" 26 | screen_rect = self.screen.get_rect() 27 | if self.rect.right >= screen_rect.right or self.rect.left <= 0: 28 | return True 29 | 30 | def update(self): 31 | """エイリアンを右または左に移動する""" 32 | self.x += (self.settings.alien_speed * self.settings.fleet_direction) 33 | self.rect.x = self.x 34 | -------------------------------------------------------------------------------- /実践編/chapter02/3_艦隊を動かす/bullet.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | from pygame.sprite import Sprite 3 | 4 | class Bullet(Sprite): 5 | """宇宙船から発射される弾を管理するクラス""" 6 | 7 | def __init__(self, ai_game): 8 | """宇宙船の現在の位置から弾のオブジェクトを生成する""" 9 | super().__init__() 10 | self.screen = ai_game.screen 11 | self.settings = ai_game.settings 12 | self.color = self.settings.bullet_color 13 | 14 | # 弾のrectを(0, 0)の位置に作成してから、正しい位置を設定する 15 | self.rect = pygame.Rect(0, 0, self.settings.bullet_width, 16 | self.settings.bullet_height) 17 | self.rect.midtop = ai_game.ship.rect.midtop 18 | 19 | # 弾の位置を浮動小数点数で保存する 20 | self.y = float(self.rect.y) 21 | 22 | def update(self): 23 | """画面上の弾を移動する""" 24 | # 弾の浮動小数点数での位置を更新する 25 | self.y -= self.settings.bullet_speed 26 | # rectの位置を更新する 27 | self.rect.y = self.y 28 | 29 | def draw_bullet(self): 30 | """画面に弾を描画する""" 31 | pygame.draw.rect(self.screen, self.color, self.rect) 32 | -------------------------------------------------------------------------------- /実践編/chapter02/3_艦隊を動かす/images/alien.bmp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/takanory/saitan-python/8196a91a9aac5011bc29782381b93f143b0ae25a/実践編/chapter02/3_艦隊を動かす/images/alien.bmp -------------------------------------------------------------------------------- /実践編/chapter02/3_艦隊を動かす/images/ship.bmp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/takanory/saitan-python/8196a91a9aac5011bc29782381b93f143b0ae25a/実践編/chapter02/3_艦隊を動かす/images/ship.bmp -------------------------------------------------------------------------------- /実践編/chapter02/3_艦隊を動かす/settings.py: -------------------------------------------------------------------------------- 1 | class Settings: 2 | """エイリアン侵略の全設定を格納するクラス""" 3 | 4 | def __init__(self): 5 | """ゲームの初期設定""" 6 | # 画面に関する設定 7 | self.screen_width = 1200 8 | self.screen_height = 800 9 | self.bg_color = (230, 230, 230) 10 | 11 | # 宇宙船の設定 12 | self.ship_speed = 1.5 13 | 14 | # 弾の設定 15 | self.bullet_speed = 1.0 16 | self.bullet_width = 3 17 | self.bullet_height = 15 18 | self.bullet_color = (60, 60, 60) 19 | self.bullets_allowed = 3 20 | 21 | # エイリアンの設定 22 | self.alien_speed = 1.0 23 | self.fleet_drop_speed = 10 24 | # 艦隊の移動方向を表し 1 は右、-1 は左に移動することを表す 25 | self.fleet_direction = 1 26 | -------------------------------------------------------------------------------- /実践編/chapter02/3_艦隊を動かす/ship.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | 3 | class Ship: 4 | """宇宙船を管理するクラス""" 5 | 6 | def __init__(self, ai_game): 7 | """宇宙船を初期化し、開始時の位置を設定する""" 8 | self.screen = ai_game.screen 9 | self.settings = ai_game.settings 10 | self.screen_rect = ai_game.screen.get_rect() 11 | 12 | # 宇宙船の画像を読み込み、サイズを取得する 13 | self.image = pygame.image.load('images/ship.bmp') 14 | self.rect = self.image.get_rect() 15 | 16 | # 新しい宇宙船を画面下部の中央に配置する 17 | self.rect.midbottom = self.screen_rect.midbottom 18 | 19 | # 宇宙船の水平位置の浮動小数点数を格納する 20 | self.x = float(self.rect.x) 21 | 22 | # 左右の移動フラグ 23 | self.moving_right = False 24 | self.moving_left = False 25 | 26 | def update(self): 27 | """左右の移動フラグによって宇宙船の位置を更新する""" 28 | # 宇宙船のxの値を更新する(rectではない) 29 | if self.moving_right and self.rect.right < self.screen_rect.right: 30 | self.x += self.settings.ship_speed 31 | if self.moving_left and self.rect.left > 0: 32 | self.x -= self.settings.ship_speed 33 | 34 | # self.xからrectオブジェクトの位置を更新する 35 | self.rect.x = self.x 36 | 37 | def blitme(self): 38 | """宇宙船を現在位置に描画する""" 39 | self.screen.blit(self.image, self.rect) 40 | -------------------------------------------------------------------------------- /実践編/chapter02/4_エイリアンを撃つ/alien.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | from pygame.sprite import Sprite 3 | 4 | class Alien(Sprite): 5 | """艦隊の中の1匹のエイリアンを表すクラス""" 6 | 7 | def __init__(self, ai_game): 8 | """エイリアンを初期化し、開始時の位置を設定する""" 9 | super().__init__() 10 | self.screen = ai_game.screen 11 | self.settings = ai_game.settings 12 | 13 | # エイリアンの画像を読み込み、サイズを取得する 14 | self.image = pygame.image.load('images/alien.bmp') 15 | self.rect = self.image.get_rect() 16 | 17 | # 新しいエイリアンを画面の左上の近くに配置する 18 | self.rect.x = self.rect.width 19 | self.rect.y = self.rect.height 20 | 21 | # エイリアンの実際の位置を格納する 22 | self.x = float(self.rect.x) 23 | 24 | def check_edges(self): 25 | """エイリアンが画面の端に達した場合は True を返す""" 26 | screen_rect = self.screen.get_rect() 27 | if self.rect.right >= screen_rect.right or self.rect.left <= 0: 28 | return True 29 | 30 | def update(self): 31 | """エイリアンを右または左に移動する""" 32 | self.x += (self.settings.alien_speed * self.settings.fleet_direction) 33 | self.rect.x = self.x 34 | -------------------------------------------------------------------------------- /実践編/chapter02/4_エイリアンを撃つ/bullet.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | from pygame.sprite import Sprite 3 | 4 | class Bullet(Sprite): 5 | """宇宙船から発射される弾を管理するクラス""" 6 | 7 | def __init__(self, ai_game): 8 | """宇宙船の現在の位置から弾のオブジェクトを生成する""" 9 | super().__init__() 10 | self.screen = ai_game.screen 11 | self.settings = ai_game.settings 12 | self.color = self.settings.bullet_color 13 | 14 | # 弾のrectを(0, 0)の位置に作成してから、正しい位置を設定する 15 | self.rect = pygame.Rect(0, 0, self.settings.bullet_width, 16 | self.settings.bullet_height) 17 | self.rect.midtop = ai_game.ship.rect.midtop 18 | 19 | # 弾の位置を浮動小数点数で保存する 20 | self.y = float(self.rect.y) 21 | 22 | def update(self): 23 | """画面上の弾を移動する""" 24 | # 弾の浮動小数点数での位置を更新する 25 | self.y -= self.settings.bullet_speed 26 | # rectの位置を更新する 27 | self.rect.y = self.y 28 | 29 | def draw_bullet(self): 30 | """画面に弾を描画する""" 31 | pygame.draw.rect(self.screen, self.color, self.rect) 32 | -------------------------------------------------------------------------------- /実践編/chapter02/4_エイリアンを撃つ/images/alien.bmp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/takanory/saitan-python/8196a91a9aac5011bc29782381b93f143b0ae25a/実践編/chapter02/4_エイリアンを撃つ/images/alien.bmp -------------------------------------------------------------------------------- /実践編/chapter02/4_エイリアンを撃つ/images/ship.bmp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/takanory/saitan-python/8196a91a9aac5011bc29782381b93f143b0ae25a/実践編/chapter02/4_エイリアンを撃つ/images/ship.bmp -------------------------------------------------------------------------------- /実践編/chapter02/4_エイリアンを撃つ/settings.py: -------------------------------------------------------------------------------- 1 | class Settings: 2 | """エイリアン侵略の全設定を格納するクラス""" 3 | 4 | def __init__(self): 5 | """ゲームの初期設定""" 6 | # 画面に関する設定 7 | self.screen_width = 1200 8 | self.screen_height = 800 9 | self.bg_color = (230, 230, 230) 10 | 11 | # 宇宙船の設定 12 | self.ship_speed = 1.5 13 | 14 | # 弾の設定 15 | self.bullet_speed = 1.5 16 | self.bullet_width = 3 17 | self.bullet_height = 15 18 | self.bullet_color = (60, 60, 60) 19 | self.bullets_allowed = 3 20 | 21 | # エイリアンの設定 22 | self.alien_speed = 1.0 23 | self.fleet_drop_speed = 10 24 | # 艦隊の移動方向を表し 1 は右、-1 は左に移動することを表す 25 | self.fleet_direction = 1 26 | -------------------------------------------------------------------------------- /実践編/chapter02/4_エイリアンを撃つ/ship.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | 3 | class Ship: 4 | """宇宙船を管理するクラス""" 5 | 6 | def __init__(self, ai_game): 7 | """宇宙船を初期化し、開始時の位置を設定する""" 8 | self.screen = ai_game.screen 9 | self.settings = ai_game.settings 10 | self.screen_rect = ai_game.screen.get_rect() 11 | 12 | # 宇宙船の画像を読み込み、サイズを取得する 13 | self.image = pygame.image.load('images/ship.bmp') 14 | self.rect = self.image.get_rect() 15 | 16 | # 新しい宇宙船を画面下部の中央に配置する 17 | self.rect.midbottom = self.screen_rect.midbottom 18 | 19 | # 宇宙船の水平位置の浮動小数点数を格納する 20 | self.x = float(self.rect.x) 21 | 22 | # 左右の移動フラグ 23 | self.moving_right = False 24 | self.moving_left = False 25 | 26 | def update(self): 27 | """左右の移動フラグによって宇宙船の位置を更新する""" 28 | # 宇宙船のxの値を更新する(rectではない) 29 | if self.moving_right and self.rect.right < self.screen_rect.right: 30 | self.x += self.settings.ship_speed 31 | if self.moving_left and self.rect.left > 0: 32 | self.x -= self.settings.ship_speed 33 | 34 | # self.xからrectオブジェクトの位置を更新する 35 | self.rect.x = self.x 36 | 37 | def blitme(self): 38 | """宇宙船を現在位置に描画する""" 39 | self.screen.blit(self.image, self.rect) 40 | -------------------------------------------------------------------------------- /実践編/chapter02/5_ゲームを終了する/alien.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | from pygame.sprite import Sprite 3 | 4 | class Alien(Sprite): 5 | """艦隊の中の1匹のエイリアンを表すクラス""" 6 | 7 | def __init__(self, ai_game): 8 | """エイリアンを初期化し、開始時の位置を設定する""" 9 | super().__init__() 10 | self.screen = ai_game.screen 11 | self.settings = ai_game.settings 12 | 13 | # エイリアンの画像を読み込み、サイズを取得する 14 | self.image = pygame.image.load('images/alien.bmp') 15 | self.rect = self.image.get_rect() 16 | 17 | # 新しいエイリアンを画面の左上の近くに配置する 18 | self.rect.x = self.rect.width 19 | self.rect.y = self.rect.height 20 | 21 | # エイリアンの実際の位置を格納する 22 | self.x = float(self.rect.x) 23 | 24 | def check_edges(self): 25 | """エイリアンが画面の端に達した場合は True を返す""" 26 | screen_rect = self.screen.get_rect() 27 | if self.rect.right >= screen_rect.right or self.rect.left <= 0: 28 | return True 29 | 30 | def update(self): 31 | """エイリアンを右または左に移動する""" 32 | self.x += (self.settings.alien_speed * self.settings.fleet_direction) 33 | self.rect.x = self.x 34 | -------------------------------------------------------------------------------- /実践編/chapter02/5_ゲームを終了する/bullet.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | from pygame.sprite import Sprite 3 | 4 | class Bullet(Sprite): 5 | """宇宙船から発射される弾を管理するクラス""" 6 | 7 | def __init__(self, ai_game): 8 | """宇宙船の現在の位置から弾のオブジェクトを生成する""" 9 | super().__init__() 10 | self.screen = ai_game.screen 11 | self.settings = ai_game.settings 12 | self.color = self.settings.bullet_color 13 | 14 | # 弾のrectを(0, 0)の位置に作成してから、正しい位置を設定する 15 | self.rect = pygame.Rect(0, 0, self.settings.bullet_width, 16 | self.settings.bullet_height) 17 | self.rect.midtop = ai_game.ship.rect.midtop 18 | 19 | # 弾の位置を浮動小数点数で保存する 20 | self.y = float(self.rect.y) 21 | 22 | def update(self): 23 | """画面上の弾を移動する""" 24 | # 弾の浮動小数点数での位置を更新する 25 | self.y -= self.settings.bullet_speed 26 | # rectの位置を更新する 27 | self.rect.y = self.y 28 | 29 | def draw_bullet(self): 30 | """画面に弾を描画する""" 31 | pygame.draw.rect(self.screen, self.color, self.rect) 32 | -------------------------------------------------------------------------------- /実践編/chapter02/5_ゲームを終了する/game_stats.py: -------------------------------------------------------------------------------- 1 | class GameStats: 2 | """エイリアン侵略ゲームの統計情報を記録する""" 3 | 4 | def __init__(self, ai_game): 5 | """統計情報を初期化する""" 6 | self.settings = ai_game.settings 7 | self.reset_stats() 8 | 9 | # エイリアン侵略ゲームをアクティブな状態で開始する 10 | self.game_active = True 11 | 12 | def reset_stats(self): 13 | """ゲーム中に変更される統計情報を初期化する""" 14 | self.ships_left = self.settings.ship_limit 15 | -------------------------------------------------------------------------------- /実践編/chapter02/5_ゲームを終了する/images/alien.bmp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/takanory/saitan-python/8196a91a9aac5011bc29782381b93f143b0ae25a/実践編/chapter02/5_ゲームを終了する/images/alien.bmp -------------------------------------------------------------------------------- /実践編/chapter02/5_ゲームを終了する/images/ship.bmp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/takanory/saitan-python/8196a91a9aac5011bc29782381b93f143b0ae25a/実践編/chapter02/5_ゲームを終了する/images/ship.bmp -------------------------------------------------------------------------------- /実践編/chapter02/5_ゲームを終了する/settings.py: -------------------------------------------------------------------------------- 1 | class Settings: 2 | """エイリアン侵略の全設定を格納するクラス""" 3 | 4 | def __init__(self): 5 | """ゲームの初期設定""" 6 | # 画面に関する設定 7 | self.screen_width = 1200 8 | self.screen_height = 800 9 | self.bg_color = (230, 230, 230) 10 | 11 | # 宇宙船の設定 12 | self.ship_speed = 1.5 13 | self.ship_limit = 3 14 | 15 | # 弾の設定 16 | self.bullet_speed = 1.5 17 | self.bullet_width = 3 18 | self.bullet_height = 15 19 | self.bullet_color = (60, 60, 60) 20 | self.bullets_allowed = 3 21 | 22 | # エイリアンの設定 23 | self.alien_speed = 1.0 24 | self.fleet_drop_speed = 10 25 | # 艦隊の移動方向を表し 1 は右、-1 は左に移動することを表す 26 | self.fleet_direction = 1 27 | -------------------------------------------------------------------------------- /実践編/chapter02/5_ゲームを終了する/ship.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | 3 | class Ship: 4 | """宇宙船を管理するクラス""" 5 | 6 | def __init__(self, ai_game): 7 | """宇宙船を初期化し、開始時の位置を設定する""" 8 | self.screen = ai_game.screen 9 | self.settings = ai_game.settings 10 | self.screen_rect = ai_game.screen.get_rect() 11 | 12 | # 宇宙船の画像を読み込み、サイズを取得する 13 | self.image = pygame.image.load('images/ship.bmp') 14 | self.rect = self.image.get_rect() 15 | 16 | # 新しい宇宙船を画面下部の中央に配置する 17 | self.rect.midbottom = self.screen_rect.midbottom 18 | 19 | # 宇宙船の水平位置の浮動小数点数を格納する 20 | self.x = float(self.rect.x) 21 | 22 | # 左右の移動フラグ 23 | self.moving_right = False 24 | self.moving_left = False 25 | 26 | def update(self): 27 | """左右の移動フラグによって宇宙船の位置を更新する""" 28 | # 宇宙船のxの値を更新する(rectではない) 29 | if self.moving_right and self.rect.right < self.screen_rect.right: 30 | self.x += self.settings.ship_speed 31 | if self.moving_left and self.rect.left > 0: 32 | self.x -= self.settings.ship_speed 33 | 34 | # self.xからrectオブジェクトの位置を更新する 35 | self.rect.x = self.x 36 | 37 | def blitme(self): 38 | """宇宙船を現在位置に描画する""" 39 | self.screen.blit(self.image, self.rect) 40 | 41 | def center_ship(self): 42 | """宇宙船を画面の中央に配置する""" 43 | self.rect.midbottom = self.screen_rect.midbottom 44 | self.x = float(self.rect.x) 45 | -------------------------------------------------------------------------------- /実践編/chapter03/1_Playボタンを追加する/alien.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | from pygame.sprite import Sprite 3 | 4 | class Alien(Sprite): 5 | """艦隊の中の1匹のエイリアンを表すクラス""" 6 | 7 | def __init__(self, ai_game): 8 | """エイリアンを初期化し、開始時の位置を設定する""" 9 | super().__init__() 10 | self.screen = ai_game.screen 11 | self.settings = ai_game.settings 12 | 13 | # エイリアンの画像を読み込み、サイズを取得する 14 | self.image = pygame.image.load('images/alien.bmp') 15 | self.rect = self.image.get_rect() 16 | 17 | # 新しいエイリアンを画面の左上の近くに配置する 18 | self.rect.x = self.rect.width 19 | self.rect.y = self.rect.height 20 | 21 | # エイリアンの実際の位置を格納する 22 | self.x = float(self.rect.x) 23 | 24 | def check_edges(self): 25 | """エイリアンが画面の端に達した場合は True を返す""" 26 | screen_rect = self.screen.get_rect() 27 | if self.rect.right >= screen_rect.right or self.rect.left <= 0: 28 | return True 29 | 30 | def update(self): 31 | """エイリアンを右または左に移動する""" 32 | self.x += (self.settings.alien_speed * self.settings.fleet_direction) 33 | self.rect.x = self.x 34 | -------------------------------------------------------------------------------- /実践編/chapter03/1_Playボタンを追加する/bullet.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | from pygame.sprite import Sprite 3 | 4 | class Bullet(Sprite): 5 | """宇宙船から発射される弾を管理するクラス""" 6 | 7 | def __init__(self, ai_game): 8 | """宇宙船の現在の位置から弾のオブジェクトを生成する""" 9 | super().__init__() 10 | self.screen = ai_game.screen 11 | self.settings = ai_game.settings 12 | self.color = self.settings.bullet_color 13 | 14 | # 弾のrectを(0, 0)の位置に作成してから、正しい位置を設定する 15 | self.rect = pygame.Rect(0, 0, self.settings.bullet_width, 16 | self.settings.bullet_height) 17 | self.rect.midtop = ai_game.ship.rect.midtop 18 | 19 | # 弾の位置を浮動小数点数で保存する 20 | self.y = float(self.rect.y) 21 | 22 | def update(self): 23 | """画面上の弾を移動する""" 24 | # 弾の浮動小数点数での位置を更新する 25 | self.y -= self.settings.bullet_speed 26 | # rectの位置を更新する 27 | self.rect.y = self.y 28 | 29 | def draw_bullet(self): 30 | """画面に弾を描画する""" 31 | pygame.draw.rect(self.screen, self.color, self.rect) 32 | -------------------------------------------------------------------------------- /実践編/chapter03/1_Playボタンを追加する/button.py: -------------------------------------------------------------------------------- 1 | import pygame.font 2 | 3 | class Button: 4 | 5 | def __init__(self, ai_game, msg): 6 | """ボタンの属性を初期化する""" 7 | self.screen = ai_game.screen 8 | self.screen_rect = self.screen.get_rect() 9 | 10 | # ボタンの大きさと属性を設定する 11 | self.width, self.height = 200, 50 12 | self.button_color = (0, 255, 0) 13 | self.text_color = (255, 255, 255) 14 | self.font = pygame.font.SysFont(None, 48) 15 | 16 | # ボタンの rect オブジェクトを生成し画面の中央に配置する 17 | self.rect = pygame.Rect(0, 0, self.width, self.height) 18 | self.rect.center = self.screen_rect.center 19 | 20 | # ボタンのメッセージは一度だけ準備する必要がある 21 | self._prep_msg(msg) 22 | 23 | def _prep_msg(self, msg): 24 | """msgを画像に変換しボタンの中央に配置する""" 25 | self.msg_image = self.font.render(msg, True, self.text_color, 26 | self.button_color) 27 | self.msg_image_rect = self.msg_image.get_rect() 28 | self.msg_image_rect.center = self.rect.center 29 | 30 | def draw_button(self): 31 | # 空白のボタンを描画し、メッセージを描画する 32 | self.screen.fill(self.button_color, self.rect) 33 | self.screen.blit(self.msg_image, self.msg_image_rect) 34 | -------------------------------------------------------------------------------- /実践編/chapter03/1_Playボタンを追加する/game_stats.py: -------------------------------------------------------------------------------- 1 | class GameStats: 2 | """エイリアン侵略ゲームの統計情報を記録する""" 3 | 4 | def __init__(self, ai_game): 5 | """統計情報を初期化する""" 6 | self.settings = ai_game.settings 7 | self.reset_stats() 8 | 9 | # 非アクティブな状態でゲームを開始する 10 | self.game_active = False 11 | 12 | def reset_stats(self): 13 | """ゲーム中に変更される統計情報を初期化する""" 14 | self.ships_left = self.settings.ship_limit 15 | -------------------------------------------------------------------------------- /実践編/chapter03/1_Playボタンを追加する/images/alien.bmp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/takanory/saitan-python/8196a91a9aac5011bc29782381b93f143b0ae25a/実践編/chapter03/1_Playボタンを追加する/images/alien.bmp -------------------------------------------------------------------------------- /実践編/chapter03/1_Playボタンを追加する/images/ship.bmp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/takanory/saitan-python/8196a91a9aac5011bc29782381b93f143b0ae25a/実践編/chapter03/1_Playボタンを追加する/images/ship.bmp -------------------------------------------------------------------------------- /実践編/chapter03/1_Playボタンを追加する/settings.py: -------------------------------------------------------------------------------- 1 | class Settings: 2 | """エイリアン侵略の全設定を格納するクラス""" 3 | 4 | def __init__(self): 5 | """ゲームの初期設定""" 6 | # 画面に関する設定 7 | self.screen_width = 1200 8 | self.screen_height = 800 9 | self.bg_color = (230, 230, 230) 10 | 11 | # 宇宙船の設定 12 | self.ship_speed = 1.5 13 | self.ship_limit = 3 14 | 15 | # 弾の設定 16 | self.bullet_speed = 1.5 17 | self.bullet_width = 3 18 | self.bullet_height = 15 19 | self.bullet_color = (60, 60, 60) 20 | self.bullets_allowed = 3 21 | 22 | # エイリアンの設定 23 | self.alien_speed = 1.0 24 | self.fleet_drop_speed = 10 25 | # 艦隊の移動方向を表し 1 は右、-1 は左に移動することを表す 26 | self.fleet_direction = 1 27 | -------------------------------------------------------------------------------- /実践編/chapter03/2_ゲームをリセットする/alien.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | from pygame.sprite import Sprite 3 | 4 | class Alien(Sprite): 5 | """艦隊の中の1匹のエイリアンを表すクラス""" 6 | 7 | def __init__(self, ai_game): 8 | """エイリアンを初期化し、開始時の位置を設定する""" 9 | super().__init__() 10 | self.screen = ai_game.screen 11 | self.settings = ai_game.settings 12 | 13 | # エイリアンの画像を読み込み、サイズを取得する 14 | self.image = pygame.image.load('images/alien.bmp') 15 | self.rect = self.image.get_rect() 16 | 17 | # 新しいエイリアンを画面の左上の近くに配置する 18 | self.rect.x = self.rect.width 19 | self.rect.y = self.rect.height 20 | 21 | # エイリアンの実際の位置を格納する 22 | self.x = float(self.rect.x) 23 | 24 | def check_edges(self): 25 | """エイリアンが画面の端に達した場合は True を返す""" 26 | screen_rect = self.screen.get_rect() 27 | if self.rect.right >= screen_rect.right or self.rect.left <= 0: 28 | return True 29 | 30 | def update(self): 31 | """エイリアンを右または左に移動する""" 32 | self.x += (self.settings.alien_speed * self.settings.fleet_direction) 33 | self.rect.x = self.x 34 | -------------------------------------------------------------------------------- /実践編/chapter03/2_ゲームをリセットする/bullet.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | from pygame.sprite import Sprite 3 | 4 | class Bullet(Sprite): 5 | """宇宙船から発射される弾を管理するクラス""" 6 | 7 | def __init__(self, ai_game): 8 | """宇宙船の現在の位置から弾のオブジェクトを生成する""" 9 | super().__init__() 10 | self.screen = ai_game.screen 11 | self.settings = ai_game.settings 12 | self.color = self.settings.bullet_color 13 | 14 | # 弾のrectを(0, 0)の位置に作成してから、正しい位置を設定する 15 | self.rect = pygame.Rect(0, 0, self.settings.bullet_width, 16 | self.settings.bullet_height) 17 | self.rect.midtop = ai_game.ship.rect.midtop 18 | 19 | # 弾の位置を浮動小数点数で保存する 20 | self.y = float(self.rect.y) 21 | 22 | def update(self): 23 | """画面上の弾を移動する""" 24 | # 弾の浮動小数点数での位置を更新する 25 | self.y -= self.settings.bullet_speed 26 | # rectの位置を更新する 27 | self.rect.y = self.y 28 | 29 | def draw_bullet(self): 30 | """画面に弾を描画する""" 31 | pygame.draw.rect(self.screen, self.color, self.rect) 32 | -------------------------------------------------------------------------------- /実践編/chapter03/2_ゲームをリセットする/button.py: -------------------------------------------------------------------------------- 1 | import pygame.font 2 | 3 | class Button: 4 | 5 | def __init__(self, ai_game, msg): 6 | """ボタンの属性を初期化する""" 7 | self.screen = ai_game.screen 8 | self.screen_rect = self.screen.get_rect() 9 | 10 | # ボタンの大きさと属性を設定する 11 | self.width, self.height = 200, 50 12 | self.button_color = (0, 255, 0) 13 | self.text_color = (255, 255, 255) 14 | self.font = pygame.font.SysFont(None, 48) 15 | 16 | # ボタンの rect オブジェクトを生成し画面の中央に配置する 17 | self.rect = pygame.Rect(0, 0, self.width, self.height) 18 | self.rect.center = self.screen_rect.center 19 | 20 | # ボタンのメッセージは一度だけ準備する必要がある 21 | self._prep_msg(msg) 22 | 23 | def _prep_msg(self, msg): 24 | """msgを画像に変換しボタンの中央に配置する""" 25 | self.msg_image = self.font.render(msg, True, self.text_color, 26 | self.button_color) 27 | self.msg_image_rect = self.msg_image.get_rect() 28 | self.msg_image_rect.center = self.rect.center 29 | 30 | def draw_button(self): 31 | # 空白のボタンを描画し、メッセージを描画する 32 | self.screen.fill(self.button_color, self.rect) 33 | self.screen.blit(self.msg_image, self.msg_image_rect) 34 | -------------------------------------------------------------------------------- /実践編/chapter03/2_ゲームをリセットする/game_stats.py: -------------------------------------------------------------------------------- 1 | class GameStats: 2 | """エイリアン侵略ゲームの統計情報を記録する""" 3 | 4 | def __init__(self, ai_game): 5 | """統計情報を初期化する""" 6 | self.settings = ai_game.settings 7 | self.reset_stats() 8 | 9 | # 非アクティブな状態でゲームを開始する 10 | self.game_active = False 11 | 12 | def reset_stats(self): 13 | """ゲーム中に変更される統計情報を初期化する""" 14 | self.ships_left = self.settings.ship_limit 15 | -------------------------------------------------------------------------------- /実践編/chapter03/2_ゲームをリセットする/images/alien.bmp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/takanory/saitan-python/8196a91a9aac5011bc29782381b93f143b0ae25a/実践編/chapter03/2_ゲームをリセットする/images/alien.bmp -------------------------------------------------------------------------------- /実践編/chapter03/2_ゲームをリセットする/images/ship.bmp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/takanory/saitan-python/8196a91a9aac5011bc29782381b93f143b0ae25a/実践編/chapter03/2_ゲームをリセットする/images/ship.bmp -------------------------------------------------------------------------------- /実践編/chapter03/2_ゲームをリセットする/settings.py: -------------------------------------------------------------------------------- 1 | class Settings: 2 | """エイリアン侵略の全設定を格納するクラス""" 3 | 4 | def __init__(self): 5 | """ゲームの初期設定""" 6 | # 画面に関する設定 7 | self.screen_width = 1200 8 | self.screen_height = 800 9 | self.bg_color = (230, 230, 230) 10 | 11 | # 宇宙船の設定 12 | self.ship_speed = 1.5 13 | self.ship_limit = 3 14 | 15 | # 弾の設定 16 | self.bullet_speed = 1.5 17 | self.bullet_width = 3 18 | self.bullet_height = 15 19 | self.bullet_color = (60, 60, 60) 20 | self.bullets_allowed = 3 21 | 22 | # エイリアンの設定 23 | self.alien_speed = 1.0 24 | self.fleet_drop_speed = 10 25 | # 艦隊の移動方向を表し 1 は右、-1 は左に移動することを表す 26 | self.fleet_direction = 1 27 | -------------------------------------------------------------------------------- /実践編/chapter03/3_レベルアップする/alien.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | from pygame.sprite import Sprite 3 | 4 | class Alien(Sprite): 5 | """艦隊の中の1匹のエイリアンを表すクラス""" 6 | 7 | def __init__(self, ai_game): 8 | """エイリアンを初期化し、開始時の位置を設定する""" 9 | super().__init__() 10 | self.screen = ai_game.screen 11 | self.settings = ai_game.settings 12 | 13 | # エイリアンの画像を読み込み、サイズを取得する 14 | self.image = pygame.image.load('images/alien.bmp') 15 | self.rect = self.image.get_rect() 16 | 17 | # 新しいエイリアンを画面の左上の近くに配置する 18 | self.rect.x = self.rect.width 19 | self.rect.y = self.rect.height 20 | 21 | # エイリアンの実際の位置を格納する 22 | self.x = float(self.rect.x) 23 | 24 | def check_edges(self): 25 | """エイリアンが画面の端に達した場合は True を返す""" 26 | screen_rect = self.screen.get_rect() 27 | if self.rect.right >= screen_rect.right or self.rect.left <= 0: 28 | return True 29 | 30 | def update(self): 31 | """エイリアンを右または左に移動する""" 32 | self.x += (self.settings.alien_speed * self.settings.fleet_direction) 33 | self.rect.x = self.x 34 | -------------------------------------------------------------------------------- /実践編/chapter03/3_レベルアップする/bullet.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | from pygame.sprite import Sprite 3 | 4 | class Bullet(Sprite): 5 | """宇宙船から発射される弾を管理するクラス""" 6 | 7 | def __init__(self, ai_game): 8 | """宇宙船の現在の位置から弾のオブジェクトを生成する""" 9 | super().__init__() 10 | self.screen = ai_game.screen 11 | self.settings = ai_game.settings 12 | self.color = self.settings.bullet_color 13 | 14 | # 弾のrectを(0, 0)の位置に作成してから、正しい位置を設定する 15 | self.rect = pygame.Rect(0, 0, self.settings.bullet_width, 16 | self.settings.bullet_height) 17 | self.rect.midtop = ai_game.ship.rect.midtop 18 | 19 | # 弾の位置を浮動小数点数で保存する 20 | self.y = float(self.rect.y) 21 | 22 | def update(self): 23 | """画面上の弾を移動する""" 24 | # 弾の浮動小数点数での位置を更新する 25 | self.y -= self.settings.bullet_speed 26 | # rectの位置を更新する 27 | self.rect.y = self.y 28 | 29 | def draw_bullet(self): 30 | """画面に弾を描画する""" 31 | pygame.draw.rect(self.screen, self.color, self.rect) 32 | -------------------------------------------------------------------------------- /実践編/chapter03/3_レベルアップする/button.py: -------------------------------------------------------------------------------- 1 | import pygame.font 2 | 3 | class Button: 4 | 5 | def __init__(self, ai_game, msg): 6 | """ボタンの属性を初期化する""" 7 | self.screen = ai_game.screen 8 | self.screen_rect = self.screen.get_rect() 9 | 10 | # ボタンの大きさと属性を設定する 11 | self.width, self.height = 200, 50 12 | self.button_color = (0, 255, 0) 13 | self.text_color = (255, 255, 255) 14 | self.font = pygame.font.SysFont(None, 48) 15 | 16 | # ボタンの rect オブジェクトを生成し画面の中央に配置する 17 | self.rect = pygame.Rect(0, 0, self.width, self.height) 18 | self.rect.center = self.screen_rect.center 19 | 20 | # ボタンのメッセージは一度だけ準備する必要がある 21 | self._prep_msg(msg) 22 | 23 | def _prep_msg(self, msg): 24 | """msgを画像に変換しボタンの中央に配置する""" 25 | self.msg_image = self.font.render(msg, True, self.text_color, 26 | self.button_color) 27 | self.msg_image_rect = self.msg_image.get_rect() 28 | self.msg_image_rect.center = self.rect.center 29 | 30 | def draw_button(self): 31 | # 空白のボタンを描画し、メッセージを描画する 32 | self.screen.fill(self.button_color, self.rect) 33 | self.screen.blit(self.msg_image, self.msg_image_rect) 34 | -------------------------------------------------------------------------------- /実践編/chapter03/3_レベルアップする/game_stats.py: -------------------------------------------------------------------------------- 1 | class GameStats: 2 | """エイリアン侵略ゲームの統計情報を記録する""" 3 | 4 | def __init__(self, ai_game): 5 | """統計情報を初期化する""" 6 | self.settings = ai_game.settings 7 | self.reset_stats() 8 | 9 | # 非アクティブな状態でゲームを開始する 10 | self.game_active = False 11 | 12 | def reset_stats(self): 13 | """ゲーム中に変更される統計情報を初期化する""" 14 | self.ships_left = self.settings.ship_limit 15 | -------------------------------------------------------------------------------- /実践編/chapter03/3_レベルアップする/images/alien.bmp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/takanory/saitan-python/8196a91a9aac5011bc29782381b93f143b0ae25a/実践編/chapter03/3_レベルアップする/images/alien.bmp -------------------------------------------------------------------------------- /実践編/chapter03/3_レベルアップする/images/ship.bmp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/takanory/saitan-python/8196a91a9aac5011bc29782381b93f143b0ae25a/実践編/chapter03/3_レベルアップする/images/ship.bmp -------------------------------------------------------------------------------- /実践編/chapter03/3_レベルアップする/settings.py: -------------------------------------------------------------------------------- 1 | class Settings: 2 | """エイリアン侵略の全設定を格納するクラス""" 3 | 4 | def __init__(self): 5 | """ゲームの固定の設定値を初期化する""" 6 | # 画面に関する設定 7 | self.screen_width = 1200 8 | self.screen_height = 800 9 | self.bg_color = (230, 230, 230) 10 | 11 | # 宇宙船の設定 12 | self.ship_limit = 3 13 | 14 | # 弾の設定 15 | self.bullet_width = 3 16 | self.bullet_height = 15 17 | self.bullet_color = (60, 60, 60) 18 | self.bullets_allowed = 3 19 | 20 | # エイリアンの設定 21 | self.fleet_drop_speed = 10 22 | 23 | # ゲームのスピードアップする速さ 24 | self.speedup_scale = 1.1 25 | self.initialize_dynamic_settings() 26 | 27 | def initialize_dynamic_settings(self): 28 | """ゲーム中に変更される設定値を初期化する""" 29 | self.ship_speed = 1.5 30 | self.bullet_speed = 3.0 31 | self.alien_speed = 1.0 32 | 33 | # 艦隊の移動方向を表し 1 は右、-1 は左に移動することを表す 34 | self.fleet_direction = 1 35 | 36 | def increase_speed(self): 37 | """速度の設定値を増やす""" 38 | self.ship_speed *= self.speedup_scale 39 | self.bullet_speed *= self.speedup_scale 40 | self.alien_speed *= self.speedup_scale 41 | -------------------------------------------------------------------------------- /実践編/chapter03/3_レベルアップする/ship.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | 3 | class Ship: 4 | """宇宙船を管理するクラス""" 5 | 6 | def __init__(self, ai_game): 7 | """宇宙船を初期化し、開始時の位置を設定する""" 8 | self.screen = ai_game.screen 9 | self.settings = ai_game.settings 10 | self.screen_rect = ai_game.screen.get_rect() 11 | 12 | # 宇宙船の画像を読み込み、サイズを取得する 13 | self.image = pygame.image.load('images/ship.bmp') 14 | self.rect = self.image.get_rect() 15 | 16 | # 新しい宇宙船を画面下部の中央に配置する 17 | self.rect.midbottom = self.screen_rect.midbottom 18 | 19 | # 宇宙船の水平位置の浮動小数点数を格納する 20 | self.x = float(self.rect.x) 21 | 22 | # 左右の移動フラグ 23 | self.moving_right = False 24 | self.moving_left = False 25 | 26 | def update(self): 27 | """左右の移動フラグによって宇宙船の位置を更新する""" 28 | # 宇宙船のxの値を更新する(rectではない) 29 | if self.moving_right and self.rect.right < self.screen_rect.right: 30 | self.x += self.settings.ship_speed 31 | if self.moving_left and self.rect.left > 0: 32 | self.x -= self.settings.ship_speed 33 | 34 | # self.xからrectオブジェクトの位置を更新する 35 | self.rect.x = self.x 36 | 37 | def blitme(self): 38 | """宇宙船を現在位置に描画する""" 39 | self.screen.blit(self.image, self.rect) 40 | 41 | def center_ship(self): 42 | """宇宙船を画面の中央に配置する""" 43 | self.rect.midbottom = self.screen_rect.midbottom 44 | self.x = float(self.rect.x) 45 | -------------------------------------------------------------------------------- /実践編/chapter03/4_得点を表示する/alien.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | from pygame.sprite import Sprite 3 | 4 | class Alien(Sprite): 5 | """艦隊の中の1匹のエイリアンを表すクラス""" 6 | 7 | def __init__(self, ai_game): 8 | """エイリアンを初期化し、開始時の位置を設定する""" 9 | super().__init__() 10 | self.screen = ai_game.screen 11 | self.settings = ai_game.settings 12 | 13 | # エイリアンの画像を読み込み、サイズを取得する 14 | self.image = pygame.image.load('images/alien.bmp') 15 | self.rect = self.image.get_rect() 16 | 17 | # 新しいエイリアンを画面の左上の近くに配置する 18 | self.rect.x = self.rect.width 19 | self.rect.y = self.rect.height 20 | 21 | # エイリアンの実際の位置を格納する 22 | self.x = float(self.rect.x) 23 | 24 | def check_edges(self): 25 | """エイリアンが画面の端に達した場合は True を返す""" 26 | screen_rect = self.screen.get_rect() 27 | if self.rect.right >= screen_rect.right or self.rect.left <= 0: 28 | return True 29 | 30 | def update(self): 31 | """エイリアンを右または左に移動する""" 32 | self.x += (self.settings.alien_speed * self.settings.fleet_direction) 33 | self.rect.x = self.x 34 | -------------------------------------------------------------------------------- /実践編/chapter03/4_得点を表示する/bullet.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | from pygame.sprite import Sprite 3 | 4 | class Bullet(Sprite): 5 | """宇宙船から発射される弾を管理するクラス""" 6 | 7 | def __init__(self, ai_game): 8 | """宇宙船の現在の位置から弾のオブジェクトを生成する""" 9 | super().__init__() 10 | self.screen = ai_game.screen 11 | self.settings = ai_game.settings 12 | self.color = self.settings.bullet_color 13 | 14 | # 弾のrectを(0, 0)の位置に作成してから、正しい位置を設定する 15 | self.rect = pygame.Rect(0, 0, self.settings.bullet_width, 16 | self.settings.bullet_height) 17 | self.rect.midtop = ai_game.ship.rect.midtop 18 | 19 | # 弾の位置を浮動小数点数で保存する 20 | self.y = float(self.rect.y) 21 | 22 | def update(self): 23 | """画面上の弾を移動する""" 24 | # 弾の浮動小数点数での位置を更新する 25 | self.y -= self.settings.bullet_speed 26 | # rectの位置を更新する 27 | self.rect.y = self.y 28 | 29 | def draw_bullet(self): 30 | """画面に弾を描画する""" 31 | pygame.draw.rect(self.screen, self.color, self.rect) 32 | -------------------------------------------------------------------------------- /実践編/chapter03/4_得点を表示する/button.py: -------------------------------------------------------------------------------- 1 | import pygame.font 2 | 3 | class Button: 4 | 5 | def __init__(self, ai_game, msg): 6 | """ボタンの属性を初期化する""" 7 | self.screen = ai_game.screen 8 | self.screen_rect = self.screen.get_rect() 9 | 10 | # ボタンの大きさと属性を設定する 11 | self.width, self.height = 200, 50 12 | self.button_color = (0, 255, 0) 13 | self.text_color = (255, 255, 255) 14 | self.font = pygame.font.SysFont(None, 48) 15 | 16 | # ボタンの rect オブジェクトを生成し画面の中央に配置する 17 | self.rect = pygame.Rect(0, 0, self.width, self.height) 18 | self.rect.center = self.screen_rect.center 19 | 20 | # ボタンのメッセージは一度だけ準備する必要がある 21 | self._prep_msg(msg) 22 | 23 | def _prep_msg(self, msg): 24 | """msgを画像に変換しボタンの中央に配置する""" 25 | self.msg_image = self.font.render(msg, True, self.text_color, 26 | self.button_color) 27 | self.msg_image_rect = self.msg_image.get_rect() 28 | self.msg_image_rect.center = self.rect.center 29 | 30 | def draw_button(self): 31 | # 空白のボタンを描画し、メッセージを描画する 32 | self.screen.fill(self.button_color, self.rect) 33 | self.screen.blit(self.msg_image, self.msg_image_rect) 34 | -------------------------------------------------------------------------------- /実践編/chapter03/4_得点を表示する/game_stats.py: -------------------------------------------------------------------------------- 1 | class GameStats: 2 | """エイリアン侵略ゲームの統計情報を記録する""" 3 | 4 | def __init__(self, ai_game): 5 | """統計情報を初期化する""" 6 | self.settings = ai_game.settings 7 | self.reset_stats() 8 | 9 | # 非アクティブな状態でゲームを開始する 10 | self.game_active = False 11 | 12 | # ハイスコアはリセットしない 13 | self.high_score = 0 14 | 15 | def reset_stats(self): 16 | """ゲーム中に変更される統計情報を初期化する""" 17 | self.ships_left = self.settings.ship_limit 18 | self.score = 0 19 | self.level = 1 20 | -------------------------------------------------------------------------------- /実践編/chapter03/4_得点を表示する/images/alien.bmp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/takanory/saitan-python/8196a91a9aac5011bc29782381b93f143b0ae25a/実践編/chapter03/4_得点を表示する/images/alien.bmp -------------------------------------------------------------------------------- /実践編/chapter03/4_得点を表示する/images/ship.bmp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/takanory/saitan-python/8196a91a9aac5011bc29782381b93f143b0ae25a/実践編/chapter03/4_得点を表示する/images/ship.bmp -------------------------------------------------------------------------------- /実践編/chapter03/4_得点を表示する/org/alien.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | from pygame.sprite import Sprite 3 | 4 | class Alien(Sprite): 5 | """A class to represent a single alien in the fleet.""" 6 | 7 | def __init__(self, ai_game): 8 | """Initialize the alien and set its starting position.""" 9 | super().__init__() 10 | self.screen = ai_game.screen 11 | self.settings = ai_game.settings 12 | 13 | # Load the alien image and set its rect attribute. 14 | self.image = pygame.image.load('images/alien.bmp') 15 | self.rect = self.image.get_rect() 16 | 17 | # Start each new alien near the top left of the screen. 18 | self.rect.x = self.rect.width 19 | self.rect.y = self.rect.height 20 | 21 | # Store the alien's exact horizontal position. 22 | self.x = float(self.rect.x) 23 | 24 | def check_edges(self): 25 | """Return True if alien is at edge of screen.""" 26 | screen_rect = self.screen.get_rect() 27 | if self.rect.right >= screen_rect.right or self.rect.left <= 0: 28 | return True 29 | 30 | def update(self): 31 | """Move the alien right or left.""" 32 | self.x += (self.settings.alien_speed * 33 | self.settings.fleet_direction) 34 | self.rect.x = self.x 35 | -------------------------------------------------------------------------------- /実践編/chapter03/4_得点を表示する/org/bullet.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | from pygame.sprite import Sprite 3 | 4 | class Bullet(Sprite): 5 | """A class to manage bullets fired from the ship""" 6 | 7 | def __init__(self, ai_game): 8 | """Create a bullet object at the ship's current position.""" 9 | super().__init__() 10 | self.screen = ai_game.screen 11 | self.settings = ai_game.settings 12 | self.color = self.settings.bullet_color 13 | 14 | # Create a bullet rect at (0, 0) and then set correct position. 15 | self.rect = pygame.Rect(0, 0, self.settings.bullet_width, 16 | self.settings.bullet_height) 17 | self.rect.midtop = ai_game.ship.rect.midtop 18 | 19 | # Store the bullet's position as a decimal value. 20 | self.y = float(self.rect.y) 21 | 22 | def update(self): 23 | """Move the bullet up the screen.""" 24 | # Update the decimal position of the bullet. 25 | self.y -= self.settings.bullet_speed 26 | # Update the rect position. 27 | self.rect.y = self.y 28 | 29 | def draw_bullet(self): 30 | """Draw the bullet to the screen.""" 31 | pygame.draw.rect(self.screen, self.color, self.rect) 32 | -------------------------------------------------------------------------------- /実践編/chapter03/4_得点を表示する/org/button.puy: -------------------------------------------------------------------------------- 1 | 404: Not Found -------------------------------------------------------------------------------- /実践編/chapter03/4_得点を表示する/org/button.py: -------------------------------------------------------------------------------- 1 | import pygame.font 2 | 3 | class Button: 4 | 5 | def __init__(self, ai_game, msg): 6 | """Initialize button attributes.""" 7 | self.screen = ai_game.screen 8 | self.screen_rect = self.screen.get_rect() 9 | 10 | # Set the dimensions and properties of the button. 11 | self.width, self.height = 200, 50 12 | self.button_color = (0, 255, 0) 13 | self.text_color = (255, 255, 255) 14 | self.font = pygame.font.SysFont(None, 48) 15 | 16 | # Build the button's rect object and center it. 17 | self.rect = pygame.Rect(0, 0, self.width, self.height) 18 | self.rect.center = self.screen_rect.center 19 | 20 | # The button message needs to be prepped only once. 21 | self._prep_msg(msg) 22 | 23 | def _prep_msg(self, msg): 24 | """Turn msg into a rendered image and center text on the button.""" 25 | self.msg_image = self.font.render(msg, True, self.text_color, 26 | self.button_color) 27 | self.msg_image_rect = self.msg_image.get_rect() 28 | self.msg_image_rect.center = self.rect.center 29 | 30 | def draw_button(self): 31 | # Draw blank button and then draw message. 32 | self.screen.fill(self.button_color, self.rect) 33 | self.screen.blit(self.msg_image, self.msg_image_rect) -------------------------------------------------------------------------------- /実践編/chapter03/4_得点を表示する/org/game_stats.py: -------------------------------------------------------------------------------- 1 | class GameStats: 2 | """Track statistics for Alien Invasion.""" 3 | 4 | def __init__(self, ai_game): 5 | """Initialize statistics.""" 6 | self.settings = ai_game.settings 7 | self.reset_stats() 8 | 9 | # Start game in an inactive state. 10 | self.game_active = False 11 | 12 | # High score should never be reset. 13 | self.high_score = 0 14 | 15 | def reset_stats(self): 16 | """Initialize statistics that can change during the game.""" 17 | self.ships_left = self.settings.ship_limit 18 | self.score = 0 19 | self.level = 1 -------------------------------------------------------------------------------- /実践編/chapter03/4_得点を表示する/settings.py: -------------------------------------------------------------------------------- 1 | class Settings: 2 | """エイリアン侵略の全設定を格納するクラス""" 3 | 4 | def __init__(self): 5 | """ゲームの固定の設定値を初期化する""" 6 | # 画面に関する設定 7 | self.screen_width = 1200 8 | self.screen_height = 800 9 | self.bg_color = (230, 230, 230) 10 | 11 | # 宇宙船の設定 12 | self.ship_limit = 3 13 | 14 | # 弾の設定 15 | self.bullet_width = 3 16 | self.bullet_height = 15 17 | self.bullet_color = (60, 60, 60) 18 | self.bullets_allowed = 3 19 | 20 | # エイリアンの設定 21 | self.fleet_drop_speed = 10 22 | 23 | # ゲームのスピードアップする速さ 24 | self.speedup_scale = 1.1 25 | # エイリアンの点数が増加する量 26 | self.score_scale = 1.5 27 | 28 | self.initialize_dynamic_settings() 29 | 30 | def initialize_dynamic_settings(self): 31 | """ゲーム中に変更される設定値を初期化する""" 32 | self.ship_speed = 1.5 33 | self.bullet_speed = 3.0 34 | self.alien_speed = 1.0 35 | 36 | # 艦隊の移動方向を表し 1 は右、-1 は左に移動することを表す 37 | self.fleet_direction = 1 38 | 39 | # 点数 40 | self.alien_points = 50 41 | 42 | def increase_speed(self): 43 | """速度の設定値とエイリアンの点数を増やす""" 44 | self.ship_speed *= self.speedup_scale 45 | self.bullet_speed *= self.speedup_scale 46 | self.alien_speed *= self.speedup_scale 47 | 48 | self.alien_points = int(self.alien_points * self.score_scale) 49 | -------------------------------------------------------------------------------- /実践編/chapter04/1_簡単な折れ線グラフを描画する/mpl_squares.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | 3 | input_values = [1, 2, 3, 4, 5] 4 | squares = [1, 4, 9, 16, 25] 5 | 6 | plt.style.use('seaborn') 7 | fig, ax = plt.subplots() 8 | ax.plot(input_values, squares, linewidth=3) 9 | 10 | # グラフのタイトルと軸のラベルを設定する 11 | ax.set_title("Square Numbers", fontsize=24) 12 | ax.set_xlabel("Value", fontsize=14) 13 | ax.set_ylabel("Square of Value", fontsize=14) 14 | 15 | # 目盛りラベルのサイズを設定する 16 | ax.tick_params(axis='both', labelsize=14) 17 | 18 | plt.show() 19 | -------------------------------------------------------------------------------- /実践編/chapter04/1_簡単な折れ線グラフを描画する/scatter_squares.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | 3 | x_values = range(1, 1001) 4 | y_values = [x**2 for x in x_values] 5 | 6 | plt.style.use('seaborn') 7 | fig, ax = plt.subplots() 8 | ax.scatter(x_values, y_values, c=y_values, cmap=plt.cm.Blues, s=10) 9 | 10 | # グラフのタイトルと軸ラベルを設定する 11 | ax.set_title("Square Numbers", fontsize=24) 12 | ax.set_xlabel("Value", fontsize=14) 13 | ax.set_ylabel("Square of Value", fontsize=14) 14 | 15 | # 目盛りラベルのサイズを設定する 16 | ax.tick_params(axis='both', which='major', labelsize=14) 17 | 18 | # 各軸の範囲を設定する 19 | ax.axis([0, 1100, 0, 1100000]) 20 | 21 | plt.show() 22 | -------------------------------------------------------------------------------- /実践編/chapter04/2_ランダムウォーク/random_walk.py: -------------------------------------------------------------------------------- 1 | from random import choice 2 | 3 | class RandomWalk: 4 | """ランダムウォークを生成するためのクラス""" 5 | 6 | def __init__(self, num_points=5000): 7 | """ランダムウォークの属性を初期化する""" 8 | self.num_points = num_points 9 | 10 | # すべてのランダムウォークは(0, 0)から開始する 11 | self.x_values = [0] 12 | self.y_values = [0] 13 | 14 | def fill_walk(self): 15 | """ランダムウォークのすべての点を計算する""" 16 | 17 | # ステップ数が指定した数になるまでランダムウォークを続ける 18 | while len(self.x_values) < self.num_points: 19 | 20 | # 移動する方向と距離を決定する 21 | x_direction = choice([1, -1]) 22 | x_distance = choice([0, 1, 2, 3, 4]) 23 | x_step = x_direction * x_distance 24 | 25 | y_direction = choice([1, -1]) 26 | y_distance = choice([0, 1, 2, 3, 4]) 27 | y_step = y_direction * y_distance 28 | 29 | # どこにも移動しない場合は結果を破棄する 30 | if x_step == 0 and y_step == 0: 31 | continue 32 | 33 | # 新しい位置を計算する 34 | x = self.x_values[-1] + x_step 35 | y = self.y_values[-1] + y_step 36 | 37 | self.x_values.append(x) 38 | self.y_values.append(y) 39 | -------------------------------------------------------------------------------- /実践編/chapter04/2_ランダムウォーク/rw_visual.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | 3 | from random_walk import RandomWalk 4 | 5 | # プログラムが動作している間、新しいランダムウォークを作成しつづける 6 | while True: 7 | # ランダムウォークを作成する 8 | rw = RandomWalk(50_000) 9 | rw.fill_walk() 10 | 11 | # ランダムウォークの点を描画する 12 | plt.style.use('classic') 13 | fig, ax = plt.subplots(figsize=(15, 9)) 14 | point_numbers = range(rw.num_points) 15 | ax.scatter(rw.x_values, rw.y_values, c=point_numbers, cmap=plt.cm.Blues, 16 | edgecolor='none', s=1) 17 | 18 | # 開始点と終了点を強調する 19 | ax.scatter(0, 0, c='green', edgecolors='none', s=100) 20 | ax.scatter(rw.x_values[-1], rw.y_values[-1], c='red', edgecolors='none', 21 | s=100) 22 | 23 | # 軸を削除する 24 | ax.get_xaxis().set_visible(False) 25 | ax.get_yaxis().set_visible(False) 26 | 27 | plt.show() 28 | 29 | keep_running = input("別のランダムウォークを生成する?(y/n): ") 30 | if keep_running == 'n': 31 | break 32 | -------------------------------------------------------------------------------- /実践編/chapter04/3_Plotlyでサイコロを転がす/dice_visual.py: -------------------------------------------------------------------------------- 1 | from plotly.graph_objs import Bar, Layout 2 | from plotly import offline 3 | 4 | from die import Die 5 | 6 | # 2個のD6サイコロを作成する 7 | die_1 = Die() 8 | die_2 = Die() 9 | 10 | # サイコロを転がし、結果をリストに格納する 11 | results = [] 12 | for roll_num in range(1000): 13 | result = die_1.roll() + die_2.roll() 14 | results.append(result) 15 | 16 | # 結果を分析する 17 | frequencies = [] 18 | max_result = die_1.num_sides + die_2.num_sides 19 | for value in range(2, max_result+1): 20 | frequency = results.count(value) 21 | frequencies.append(frequency) 22 | 23 | # 結果を可視化する 24 | x_values = list(range(2, max_result+1)) 25 | data = [Bar(x=x_values, y=frequencies)] 26 | 27 | x_axis_config = {'title': '結果', 'dtick': 1} 28 | y_axis_config = {'title': '発生した回数'} 29 | my_layout = Layout(title='2個の6面サイコロを1000回転がした結果', 30 | xaxis=x_axis_config, yaxis=y_axis_config) 31 | offline.plot({'data': data, 'layout': my_layout}, filename='d6_d6.html') 32 | -------------------------------------------------------------------------------- /実践編/chapter04/3_Plotlyでサイコロを転がす/dice_visual_different_sizes.py: -------------------------------------------------------------------------------- 1 | from plotly.graph_objs import Bar, Layout 2 | from plotly import offline 3 | 4 | from die import Die 5 | 6 | # D6とD10のサイコロを作成する 7 | die_1 = Die() 8 | die_2 = Die(10) 9 | 10 | # サイコロを転がし、結果をリストに格納する 11 | results = [] 12 | for roll_num in range(50_000): 13 | result = die_1.roll() + die_2.roll() 14 | results.append(result) 15 | 16 | # 結果を分析する 17 | frequencies = [] 18 | max_result = die_1.num_sides + die_2.num_sides 19 | for value in range(2, max_result+1): 20 | frequency = results.count(value) 21 | frequencies.append(frequency) 22 | 23 | # 結果を可視化する 24 | x_values = list(range(2, max_result+1)) 25 | data = [Bar(x=x_values, y=frequencies)] 26 | 27 | x_axis_config = {'title': '結果', 'dtick': 1} 28 | y_axis_config = {'title': '発生した回数'} 29 | my_layout = Layout(title='6面サイコロと10面サイコロを50000回転がした結果', 30 | xaxis=x_axis_config, yaxis=y_axis_config) 31 | offline.plot({'data': data, 'layout': my_layout}, filename='d6_d10.html') 32 | -------------------------------------------------------------------------------- /実践編/chapter04/3_Plotlyでサイコロを転がす/die.py: -------------------------------------------------------------------------------- 1 | from random import randint 2 | 3 | class Die: 4 | """1個のサイコロを表すクラス""" 5 | 6 | def __init__(self, num_sides=6): 7 | """6面のサイコロをデフォルトにする""" 8 | self.num_sides = num_sides 9 | 10 | def roll(self): 11 | """1から面の数の間のランダムな数値を返す""" 12 | return randint(1, self.num_sides) 13 | -------------------------------------------------------------------------------- /実践編/chapter04/3_Plotlyでサイコロを転がす/die_visual.py: -------------------------------------------------------------------------------- 1 | from plotly.graph_objs import Bar, Layout 2 | from plotly import offline 3 | 4 | from die import Die 5 | 6 | # D6を作成する 7 | die = Die() 8 | 9 | # サイコロを転がし、結果をリストに格納する 10 | results = [] 11 | for roll_num in range(1000): 12 | result = die.roll() 13 | results.append(result) 14 | 15 | # 結果を分析する 16 | frequencies = [] 17 | for value in range(1, die.num_sides+1): 18 | frequency = results.count(value) 19 | frequencies.append(frequency) 20 | 21 | # 結果を可視化する 22 | x_values = list(range(1, die.num_sides+1)) 23 | data = [Bar(x=x_values, y=frequencies)] 24 | 25 | x_axis_config = {'title': '結果'} 26 | y_axis_config = {'title': '発生した回数'} 27 | my_layout = Layout(title='6面のサイコロを1000回転がした結果', 28 | xaxis=x_axis_config, yaxis=y_axis_config) 29 | offline.plot({'data': data, 'layout': my_layout}, filename='d6.html') 30 | -------------------------------------------------------------------------------- /実践編/chapter05/1_CSVファイル形式/death_valley_highs_lows.py: -------------------------------------------------------------------------------- 1 | import csv 2 | from datetime import datetime 3 | 4 | import matplotlib.pyplot as plt 5 | 6 | filename = 'data/death_valley_2018_simple.csv' 7 | with open(filename) as f: 8 | reader = csv.reader(f) 9 | header_row = next(reader) 10 | 11 | # ファイルから日付と最高気温、最低気温を取得する 12 | dates, highs, lows = [], [], [] 13 | for row in reader: 14 | current_date = datetime.strptime(row[2], '%Y-%m-%d') 15 | try: 16 | high = int(row[4]) 17 | low = int(row[5]) 18 | except ValueError: 19 | print(f"Missing data for {current_date}") 20 | else: 21 | dates.append(current_date) 22 | highs.append(high) 23 | lows.append(low) 24 | 25 | # 最高気温と最低気温をグラフに描画する 26 | plt.style.use('seaborn') 27 | fig, ax = plt.subplots() 28 | ax.plot(dates, highs, c='red', alpha=0.5) 29 | ax.plot(dates, lows, c='blue', alpha=0.5) 30 | plt.fill_between(dates, highs, lows, facecolor='blue', alpha=0.1) 31 | 32 | # グラフにフォーマットを指定する 33 | title = "Daily high and low temperatures - 2018\nDeath Valley, CA" 34 | plt.title(title, fontsize=20) 35 | plt.xlabel('', fontsize=16) 36 | fig.autofmt_xdate() 37 | plt.ylabel("Temperature (F)", fontsize=16) 38 | plt.tick_params(axis='both', which='major', labelsize=16) 39 | 40 | plt.show() 41 | -------------------------------------------------------------------------------- /実践編/chapter05/1_CSVファイル形式/sitka_highs.py: -------------------------------------------------------------------------------- 1 | import csv 2 | from datetime import datetime 3 | 4 | import matplotlib.pyplot as plt 5 | 6 | filename = 'data/sitka_weather_2018_simple.csv' 7 | with open(filename) as f: 8 | reader = csv.reader(f) 9 | header_row = next(reader) 10 | 11 | # ファイルから日付と最高気温を取得する 12 | dates, highs = [], [] 13 | for row in reader: 14 | current_date = datetime.strptime(row[2], '%Y-%m-%d') 15 | high = int(row[5]) 16 | dates.append(current_date) 17 | highs.append(high) 18 | 19 | # 最高気温のグラフを描画する 20 | plt.style.use('seaborn') 21 | fig, ax = plt.subplots() 22 | ax.plot(dates, highs, c='red') 23 | 24 | # グラフにフォーマットを指定する 25 | plt.title("Daily high temperatures - 2018", fontsize=24) 26 | plt.xlabel('', fontsize=16) 27 | fig.autofmt_xdate() 28 | plt.ylabel("Temperature (F)", fontsize=16) 29 | plt.tick_params(axis='both', which='major', labelsize=16) 30 | 31 | plt.show() 32 | -------------------------------------------------------------------------------- /実践編/chapter05/1_CSVファイル形式/sitka_highs_lows.py: -------------------------------------------------------------------------------- 1 | import csv 2 | from datetime import datetime 3 | 4 | import matplotlib.pyplot as plt 5 | 6 | filename = 'data/sitka_weather_2018_simple.csv' 7 | with open(filename) as f: 8 | reader = csv.reader(f) 9 | header_row = next(reader) 10 | 11 | # ファイルから日付と最高気温、最低気温を取得する 12 | dates, highs, lows = [], [], [] 13 | for row in reader: 14 | current_date = datetime.strptime(row[2], '%Y-%m-%d') 15 | high = int(row[5]) 16 | low = int(row[6]) 17 | dates.append(current_date) 18 | highs.append(high) 19 | lows.append(low) 20 | 21 | # 最高気温と最低気温をグラフに描画する 22 | plt.style.use('seaborn') 23 | fig, ax = plt.subplots() 24 | ax.plot(dates, highs, c='red', alpha=0.5) 25 | ax.plot(dates, lows, c='blue', alpha=0.5) 26 | plt.fill_between(dates, highs, lows, facecolor='blue', alpha=0.1) 27 | 28 | # グラフにフォーマットを指定する 29 | plt.title("Daily high and low temperatures - 2018", fontsize=24) 30 | plt.xlabel('', fontsize=16) 31 | fig.autofmt_xdate() 32 | plt.ylabel("Temperature (F)", fontsize=16) 33 | plt.tick_params(axis='both', which='major', labelsize=16) 34 | 35 | plt.show() 36 | -------------------------------------------------------------------------------- /実践編/chapter05/2_地球全体のデータセットを地図に描画する/eq_explore_data.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | from plotly.graph_objs import Scattergeo, Layout 4 | from plotly import offline 5 | 6 | # データの構造を調査する 7 | filename = 'data/eq_data_30_day_m1.json' 8 | with open(filename) as f: 9 | all_eq_data = json.load(f) 10 | 11 | all_eq_dicts = all_eq_data['features'] 12 | 13 | mags, lons, lats, hover_texts = [], [], [], [] 14 | for eq_dict in all_eq_dicts: 15 | mag = eq_dict['properties']['mag'] 16 | lon = eq_dict['geometry']['coordinates'][0] 17 | lat = eq_dict['geometry']['coordinates'][1] 18 | title = eq_dict['properties']['title'] 19 | mags.append(mag) 20 | lons.append(lon) 21 | lats.append(lat) 22 | hover_texts.append(title) 23 | 24 | # 地震の地図 25 | data = [{ 26 | 'type': 'scattergeo', 27 | 'lon': lons, 28 | 'lat': lats, 29 | 'text': hover_texts, 30 | 'marker': { 31 | 'size': [5*mag for mag in mags], 32 | 'color': mags, 33 | 'colorscale': 'Viridis', 34 | 'reversescale': True, 35 | 'colorbar': {'title': 'マグニチュード'}, 36 | }, 37 | }] 38 | my_layout = Layout(title='世界の地震') 39 | 40 | fig = {'data': data, 'layout': my_layout} 41 | offline.plot(fig, filename='global_earthquakes.html') 42 | -------------------------------------------------------------------------------- /実践編/chapter05/2_地球全体のデータセットを地図に描画する/show_color_scales.py: -------------------------------------------------------------------------------- 1 | from plotly import colors 2 | 3 | for key in colors.PLOTLY_SCALES.keys(): 4 | print(key) 5 | -------------------------------------------------------------------------------- /実践編/chapter06/1_Web APIを使う/python_repos.py: -------------------------------------------------------------------------------- 1 | import requests 2 | 3 | # API呼び出しを作成してそのレスポンスを格納する 4 | url = 'https://api.github.com/search/repositories?q=language:python&sort=stars' 5 | headers = {'Accept': 'application/vnd.github.v3+json'} 6 | r = requests.get(url, headers=headers) 7 | print(f"ステータスコード: {r.status_code}") 8 | 9 | # APIレスポンスを変数に格納する 10 | response_dict = r.json() 11 | print(f"全リポジトリ数: {response_dict['total_count']}") 12 | 13 | # リポジトリに関する情報を調べる 14 | repo_dicts = response_dict['items'] 15 | print(f"情報が返されたリポジトリの数: {len(repo_dicts)}") 16 | 17 | print("\n各リポジトリの情報の抜粋:") 18 | for repo_dict in repo_dicts: 19 | print(f"\n名前: {repo_dict['name']}") 20 | print(f"所有者: {repo_dict['owner']['login']}") 21 | print(f"スターの数: {repo_dict['stargazers_count']}") 22 | print(f"リポジトリURL: {repo_dict['html_url']}") 23 | print(f"説明文: {repo_dict['description']}") 24 | -------------------------------------------------------------------------------- /実践編/chapter06/3_Hacker NewsのAPI/hn_article.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import json 3 | 4 | # API呼び出しを作成してそのレスポンスを格納する 5 | url = 'https://hacker-news.firebaseio.com/v0/item/19155826.json' 6 | r = requests.get(url) 7 | print(f"ステータスコード: {r.status_code}") 8 | 9 | # データの構造を調べる 10 | response_dict = r.json() 11 | readable_file = 'data/readable_hn_data.json' 12 | with open(readable_file, 'w') as f: 13 | json.dump(response_dict, f, indent=4) 14 | -------------------------------------------------------------------------------- /実践編/chapter06/3_Hacker NewsのAPI/hn_submissions.py: -------------------------------------------------------------------------------- 1 | from operator import itemgetter 2 | 3 | import requests 4 | 5 | # API呼び出しを作成してそのレスポンスを格納する 6 | url = 'https://hacker-news.firebaseio.com/v0/topstories.json' 7 | r = requests.get(url) 8 | print(f"ステータスコード: {r.status_code}") 9 | 10 | # 各投稿についての情報を処理する 11 | submission_ids = r.json() 12 | submission_dicts = [] 13 | for submission_id in submission_ids[:30]: 14 | # 投稿ごとに、別々のAPI呼び出しを作成する 15 | url = f"https://hacker-news.firebaseio.com/v0/item/{submission_id}.json" 16 | r = requests.get(url) 17 | print(f"id: {submission_id}\tstatus: {r.status_code}") 18 | response_dict = r.json() 19 | 20 | # 各記事の辞書を作成する 21 | submission_dict = { 22 | 'title': response_dict['title'], 23 | 'hn_link': f"http://news.ycombinator.com/item?id={submission_id}", 24 | 'comments': response_dict['descendants'], 25 | } 26 | submission_dicts.append(submission_dict) 27 | 28 | submission_dicts = sorted(submission_dicts, key=itemgetter('comments'), 29 | reverse=True) 30 | 31 | for submission_dict in submission_dicts: 32 | print(f"\nタイトル: {submission_dict['title']}") 33 | print(f"リンクURL: {submission_dict['hn_link']}") 34 | print(f"コメント数: {submission_dict['comments']}") 35 | -------------------------------------------------------------------------------- /実践編/chapter07/2_アプリケーションを開始する/learning_log/learning_logs/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | from .models import Topic, Entry 4 | 5 | admin.site.register(Topic) 6 | admin.site.register(Entry) 7 | -------------------------------------------------------------------------------- /実践編/chapter07/2_アプリケーションを開始する/learning_log/learning_logs/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | class Topic(models.Model): 4 | """ユーザーが学んでいるトピックを表す""" 5 | text = models.CharField(max_length=200) 6 | date_added = models.DateTimeField(auto_now_add=True) 7 | 8 | def __str__(self): 9 | """モデルの文字列表現を返す""" 10 | return self.text 11 | 12 | class Entry(models.Model): 13 | """トピックに関して学んだ具体的なこと""" 14 | topic = models.ForeignKey(Topic, on_delete=models.CASCADE) 15 | text = models.TextField() 16 | date_added = models.DateTimeField(auto_now_add=True) 17 | 18 | class Meta: 19 | verbose_name_plural = 'entries' 20 | 21 | def __str__(self): 22 | """モデルの文字列表現を返す""" 23 | return f"{self.text[:25]}..." 24 | -------------------------------------------------------------------------------- /実践編/chapter07/3_ページを作成する:学習ノートのホームページ/learning_log/learning_log/urls.py: -------------------------------------------------------------------------------- 1 | """learning_logsのURLパターンの定義""" 2 | 3 | from django.urls import path 4 | 5 | from . import views 6 | 7 | app_name = 'learning_logs' 8 | urlpatterns = [ 9 | # ホームページ 10 | path('', views.index, name='index'), 11 | ] 12 | -------------------------------------------------------------------------------- /実践編/chapter07/3_ページを作成する:学習ノートのホームページ/learning_log/learning_logs/templates/learning_logs/index.html: -------------------------------------------------------------------------------- 1 |

学習ノート

2 | 3 |

学習ノートを使えば、好みのトピックについて学習していることを記録して、いつも最新の状態を把握できます。

4 | -------------------------------------------------------------------------------- /実践編/chapter07/3_ページを作成する:学習ノートのホームページ/learning_log/learning_logs/urls.py: -------------------------------------------------------------------------------- 1 | """learning_logsのURLパターンの定義""" 2 | 3 | from django.urls import path 4 | 5 | from . import views 6 | 7 | app_name = 'learning_logs' 8 | urlpatterns = [ 9 | # ホームページ 10 | path('', views.index, name='index'), 11 | ] 12 | -------------------------------------------------------------------------------- /実践編/chapter07/3_ページを作成する:学習ノートのホームページ/learning_log/learning_logs/views.py: -------------------------------------------------------------------------------- 1 | from django.shortcuts import render 2 | 3 | def index(request): 4 | """学習ノートのホームページ""" 5 | return render(request, 'learning_logs/index.html') 6 | -------------------------------------------------------------------------------- /実践編/chapter07/4_追加のページを作成する/learning_log/learning_logs/templates/learning_logs/base.html: -------------------------------------------------------------------------------- 1 |

2 | 学習ノート - 3 | トピック一覧 4 |

5 | 6 | {% block content %}{% endblock content %} 7 | -------------------------------------------------------------------------------- /実践編/chapter07/4_追加のページを作成する/learning_log/learning_logs/templates/learning_logs/index.html: -------------------------------------------------------------------------------- 1 | {% extends "learning_logs/base.html" %} 2 | 3 | {% block content %} 4 |

学習ノートを使えば、好みのトピックについて学習していることを記録して、 5 | いつも最新の状態を把握できます。

6 | {% endblock content %} 7 | -------------------------------------------------------------------------------- /実践編/chapter07/4_追加のページを作成する/learning_log/learning_logs/templates/learning_logs/topic.html: -------------------------------------------------------------------------------- 1 | {% extends 'learning_logs/base.html' %} 2 | 3 | {% block content %} 4 | 5 |

トピック: {{ topic }}

6 | 7 |

記事:

8 | 18 | 19 | {% endblock content %} 20 | -------------------------------------------------------------------------------- /実践編/chapter07/4_追加のページを作成する/learning_log/learning_logs/templates/learning_logs/topics.html: -------------------------------------------------------------------------------- 1 | {% extends "learning_logs/base.html" %} 2 | 3 | {% block content %} 4 | 5 |

トピック一覧

6 | 7 | 16 | 17 | {% endblock content %} 18 | -------------------------------------------------------------------------------- /実践編/chapter07/4_追加のページを作成する/learning_log/learning_logs/urls.py: -------------------------------------------------------------------------------- 1 | """learning_logsのURLパターンの定義""" 2 | 3 | from django.urls import path 4 | 5 | from . import views 6 | 7 | app_name = 'learning_logs' 8 | urlpatterns = [ 9 | # ホームページ 10 | path('', views.index, name='index'), 11 | # すべてのトピックを表示するページ 12 | path('topics/', views.topics, name='topics'), 13 | # 個別トピックの詳細ページ 14 | path('topics//', views.topic, name='topic'), 15 | ] 16 | -------------------------------------------------------------------------------- /実践編/chapter07/4_追加のページを作成する/learning_log/learning_logs/views.py: -------------------------------------------------------------------------------- 1 | from django.shortcuts import render 2 | 3 | from .models import Topic 4 | 5 | def index(request): 6 | """学習ノートのホームページ""" 7 | return render(request, 'learning_logs/index.html') 8 | 9 | def topics(request): 10 | """すべてのトピックを表示する""" 11 | topics = Topic.objects.order_by('date_added') 12 | context = {'topics': topics} 13 | return render(request, 'learning_logs/topics.html', context) 14 | 15 | def topic(request, topic_id): 16 | """1つのトピックとそれについてのすべての記事を表示""" 17 | topic = Topic.objects.get(id=topic_id) 18 | entries = topic.entry_set.order_by('-date_added') 19 | context = {'topic': topic, 'entries': entries} 20 | return render(request, 'learning_logs/topic.html', context) 21 | -------------------------------------------------------------------------------- /実践編/chapter08/1_ユーザーがデータを入力できるようにする/learning_log/learning_logs/forms.py: -------------------------------------------------------------------------------- 1 | from django import forms 2 | 3 | from .models import Topic, Entry 4 | 5 | class TopicForm(forms.ModelForm): 6 | class Meta: 7 | model = Topic 8 | fields = ['text'] 9 | labels = {'text': ''} 10 | 11 | class EntryForm(forms.ModelForm): 12 | class Meta: 13 | model = Entry 14 | fields = ['text'] 15 | labels = {'text': ''} 16 | widgets = {'text': forms.Textarea(attrs={'cols': 80})} 17 | -------------------------------------------------------------------------------- /実践編/chapter08/1_ユーザーがデータを入力できるようにする/learning_log/learning_logs/templates/learning_logs/edit_entry.html: -------------------------------------------------------------------------------- 1 | {% extends "learning_logs/base.html" %} 2 | 3 | {% block content %} 4 | 5 |

{{ topic }}

6 | 7 |

記事を編集:

8 | 9 |
10 | {% csrf_token %} 11 | {{ form.as_p }} 12 | 13 |
14 | 15 | {% endblock content %} 16 | -------------------------------------------------------------------------------- /実践編/chapter08/1_ユーザーがデータを入力できるようにする/learning_log/learning_logs/templates/learning_logs/new_entry.html: -------------------------------------------------------------------------------- 1 | {% extends "learning_logs/base.html" %} 2 | 3 | {% block content %} 4 | 5 |

{{ topic }}

6 | 7 |

新しい記事を追加:

8 |
9 | {% csrf_token %} 10 | {{ form.as_p }} 11 | 12 |
13 | 14 | {% endblock content %} 15 | -------------------------------------------------------------------------------- /実践編/chapter08/1_ユーザーがデータを入力できるようにする/learning_log/learning_logs/templates/learning_logs/new_topic.html: -------------------------------------------------------------------------------- 1 | {% extends "learning_logs/base.html" %} 2 | 3 | {% block content %} 4 |

新規トピックを追加:

5 | 6 |
7 | {% csrf_token %} 8 | {{ form.as_p }} 9 | 10 |
11 | 12 | {% endblock content %} 13 | -------------------------------------------------------------------------------- /実践編/chapter08/1_ユーザーがデータを入力できるようにする/learning_log/learning_logs/templates/learning_logs/topic.html: -------------------------------------------------------------------------------- 1 | {% extends 'learning_logs/base.html' %} 2 | 3 | {% block content %} 4 | 5 |

トピック: {{ topic }}

6 | 7 |

記事:

8 |

9 | 新しい記事を追加 10 |

11 | 12 | 25 | 26 | {% endblock content %} 27 | -------------------------------------------------------------------------------- /実践編/chapter08/1_ユーザーがデータを入力できるようにする/learning_log/learning_logs/templates/learning_logs/topics.html: -------------------------------------------------------------------------------- 1 | {% extends "learning_logs/base.html" %} 2 | 3 | {% block content %} 4 | 5 |

トピック一覧

6 | 7 | 16 | 17 | 新規トピックを追加 18 | 19 | {% endblock content %} 20 | -------------------------------------------------------------------------------- /実践編/chapter08/1_ユーザーがデータを入力できるようにする/learning_log/learning_logs/urls.py: -------------------------------------------------------------------------------- 1 | """learning_logsのURLパターンの定義""" 2 | 3 | from django.urls import path 4 | 5 | from . import views 6 | 7 | app_name = 'learning_logs' 8 | urlpatterns = [ 9 | # ホームページ 10 | path('', views.index, name='index'), 11 | # すべてのトピックを表示するページ 12 | path('topics/', views.topics, name='topics'), 13 | # 個別トピックの詳細ページ 14 | path('topics//', views.topic, name='topic'), 15 | # 新規トピックの追加ページ 16 | path('new_topic/', views.new_topic, name='new_topic'), 17 | # 新規記事の追加ページ 18 | path('new_entry//', views.new_entry, name='new_entry'), 19 | # 記事の編集ページ 20 | path('edit_entry//', views.edit_entry, name='edit_entry'), 21 | ] 22 | -------------------------------------------------------------------------------- /実践編/chapter08/2_ユーザーアカウントを設定する/learning_log/learning_log/urls.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | from django.urls import path, include 3 | 4 | urlpatterns = [ 5 | path('admin/', admin.site.urls), 6 | path('users/', include('users.urls')), 7 | path('', include('learning_logs.urls')), 8 | ] 9 | -------------------------------------------------------------------------------- /実践編/chapter08/2_ユーザーアカウントを設定する/learning_log/learning_logs/templates/learning_logs/base.html: -------------------------------------------------------------------------------- 1 |

2 | 学習ノート - 3 | トピック一覧 - 4 | {% if user.is_authenticated %} 5 | こんにちは {{ user.username }}さん 6 | ログアウト 7 | {% else %} 8 | ユーザー登録 - 9 | ログイン 10 | {% endif %} 11 |

12 | 13 | {% block content %}{% endblock content %} 14 | -------------------------------------------------------------------------------- /実践編/chapter08/2_ユーザーアカウントを設定する/learning_log/users/templates/registration/logged_out.html: -------------------------------------------------------------------------------- 1 | {% extends "learning_logs/base.html" %} 2 | 3 | {% block content %} 4 |

ログアウトしました。ご利用ありがとうございました!

5 | {% endblock content %} 6 | -------------------------------------------------------------------------------- /実践編/chapter08/2_ユーザーアカウントを設定する/learning_log/users/templates/registration/login.html: -------------------------------------------------------------------------------- 1 | {% extends "learning_logs/base.html" %} 2 | 3 | {% block content %} 4 | 5 | {% if form.errors %} 6 |

ユーザー名とパスワードが一致しません。もう一度お試しください。

7 | {% endif %} 8 | 9 |
10 | {% csrf_token %} 11 | {{ form.as_p }} 12 | 13 | 14 | 16 |
17 | 18 | {% endblock content %} 19 | -------------------------------------------------------------------------------- /実践編/chapter08/2_ユーザーアカウントを設定する/learning_log/users/templates/registration/register.html: -------------------------------------------------------------------------------- 1 | {% extends "learning_logs/base.html" %} 2 | 3 | {% block content %} 4 | 5 |
6 | {% csrf_token %} 7 | {{ form.as_p }} 8 | 9 | 10 | 11 |
12 | 13 | {% endblock content %} 14 | -------------------------------------------------------------------------------- /実践編/chapter08/2_ユーザーアカウントを設定する/learning_log/users/urls.py: -------------------------------------------------------------------------------- 1 | """users用URLパターンの定義""" 2 | 3 | from django.urls import path, include 4 | 5 | from . import views 6 | 7 | app_name = 'users' 8 | urlpatterns = [ 9 | # デフォルトの認証URLを取り込む 10 | path('', include('django.contrib.auth.urls')), 11 | # ユーザー登録ページ 12 | path('register/', views.register, name='register'), 13 | ] 14 | -------------------------------------------------------------------------------- /実践編/chapter08/2_ユーザーアカウントを設定する/learning_log/users/views.py: -------------------------------------------------------------------------------- 1 | from django.shortcuts import render, redirect 2 | from django.contrib.auth import login 3 | from django.contrib.auth.forms import UserCreationForm 4 | 5 | def register(request): 6 | """新しいユーザーを登録する""" 7 | if request.method != 'POST': 8 | # 空のユーザー登録フォームを表示する 9 | form = UserCreationForm() 10 | else: 11 | # 入力済みのフォームを処理する 12 | form = UserCreationForm(data=request.POST) 13 | if form.is_valid(): 14 | new_user = form.save() 15 | # ユーザーをログインさせてホームページにリダイレクトする 16 | login(request, new_user) 17 | return redirect('learning_logs:index') 18 | 19 | # 空または無効のフォームを表示する 20 | context = {'form': form} 21 | return render(request, 'registration/register.html', context) 22 | -------------------------------------------------------------------------------- /実践編/chapter08/3_ユーザーが自分のデータを持てるようにする/learning_log/learning_logs/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | from django.contrib.auth.models import User 3 | 4 | class Topic(models.Model): 5 | """ユーザーが学んでいるトピックを表す""" 6 | text = models.CharField(max_length=200) 7 | date_added = models.DateTimeField(auto_now_add=True) 8 | owner = models.ForeignKey(User, on_delete=models.CASCADE) 9 | 10 | def __str__(self): 11 | """モデルの文字列表現を返す""" 12 | return self.text 13 | 14 | class Entry(models.Model): 15 | """トピックに関して学んだ具体的なこと""" 16 | topic = models.ForeignKey(Topic, on_delete=models.CASCADE) 17 | text = models.TextField() 18 | date_added = models.DateTimeField(auto_now_add=True) 19 | 20 | class Meta: 21 | verbose_name_plural = 'entries' 22 | 23 | def __str__(self): 24 | """モデルの文字列表現を返す""" 25 | return f"{self.text[:25]}..." 26 | -------------------------------------------------------------------------------- /実践編/chapter09/1_「学習ノート」にスタイルを設定する/learning_log/learning_logs/templates/learning_logs/index.html: -------------------------------------------------------------------------------- 1 | {% extends "learning_logs/base.html" %} 2 | 3 | {% block page_header %} 4 |
5 |

学んだことを記録しよう

6 | 7 |

自分だけの学習ノートを作成して、学んだことをいつでも 8 | 振り返れるようにしよう。
9 | 何か新しいことを学んだら、その内容を要約した記事を書こう。

10 | 11 | 登録する » 13 |
14 | {% endblock page_header %} 15 | -------------------------------------------------------------------------------- /実践編/chapter09/1_「学習ノート」にスタイルを設定する/learning_log/learning_logs/templates/learning_logs/topic.html: -------------------------------------------------------------------------------- 1 | {% extends 'learning_logs/base.html' %} 2 | 3 | {% block page_header %} 4 |

{{ topic }}

5 | {% endblock page_header %} 6 | 7 | {% block content %} 8 |

9 | 新しい記事を追加 10 |

11 | 12 | {% for entry in entries %} 13 |
14 |

15 | {{ entry.date_added|date:'Y年m月d日 H:i' }} 16 | 17 | 記事を編集 18 |

19 |
20 | {{ entry.text|linebreaks }} 21 |
22 |
23 | {% empty %} 24 |

このトピックにはまだ記事がありません。

25 | {% endfor %} 26 | 27 | {% endblock content %} 28 | -------------------------------------------------------------------------------- /実践編/chapter09/1_「学習ノート」にスタイルを設定する/learning_log/learning_logs/templates/learning_logs/topics.html: -------------------------------------------------------------------------------- 1 | {% extends "learning_logs/base.html" %} 2 | 3 | {% block page_header %} 4 |

トピック一覧

5 | {% endblock page_header %} 6 | 7 | {% block content %} 8 |
    9 | {% for topic in topics %} 10 |
  • 11 | {{ topic }} 12 |

  • 13 | {% empty %} 14 |
  • トピックはまだ作成されていません。

  • 15 | {% endfor %} 16 |
17 | 18 |

新規トピックを追加

19 | 20 | {% endblock content %} 21 | -------------------------------------------------------------------------------- /実践編/chapter09/1_「学習ノート」にスタイルを設定する/learning_log/users/templates/registration/login.html: -------------------------------------------------------------------------------- 1 | {% extends "learning_logs/base.html" %} 2 | {% load bootstrap4 %} 3 | 4 | {% block page_header %} 5 |

アカウントにログイン

6 | {% endblock page_header %} 7 | 8 | {% block content %} 9 |
10 | {% csrf_token %} 11 | {% bootstrap_form form %} 12 | {% buttons %} 13 | 14 | {% endbuttons %} 15 | 16 | 18 |
19 | 20 | {% endblock content %} 21 | -------------------------------------------------------------------------------- /実践編/chapter09/2_「学習ノート」をデプロイする/learning_log/.gitignore: -------------------------------------------------------------------------------- 1 | ll_env/ 2 | __pycache__/ 3 | *.sqlite3 4 | .DS_Store 5 | -------------------------------------------------------------------------------- /実践編/chapter09/2_「学習ノート」をデプロイする/learning_log/Procfile: -------------------------------------------------------------------------------- 1 | web: gunicorn learning_log.wsgi --log-file - -------------------------------------------------------------------------------- /実践編/chapter09/2_「学習ノート」をデプロイする/learning_log/requirements.txt: -------------------------------------------------------------------------------- 1 | beautifulsoup4==4.8.2 2 | dj-database-url==0.5.0 3 | Django==2.2.12 4 | django-bootstrap4==1.1.1 5 | django-heroku==0.3.1 6 | gunicorn==20.0.4 7 | psycopg2==2.8.5 8 | pytz==2019.3 9 | soupsieve==2.0 10 | sqlparse==0.3.1 11 | whitenoise==5.0.1 12 | -------------------------------------------------------------------------------- /実践編/chapter09/2_「学習ノート」をデプロイする/learning_log/runtime.txt: -------------------------------------------------------------------------------- 1 | python-3.8.3 -------------------------------------------------------------------------------- /実践編/chapter09/2_「学習ノート」をデプロイする/learning_log/templates/404.html: -------------------------------------------------------------------------------- 1 | {% extends "learning_logs/base.html" %} 2 | 3 | {% block page_header %} 4 |

リクエストされたページは利用できません (404)

5 | {% endblock page_header %} 6 | -------------------------------------------------------------------------------- /実践編/chapter09/2_「学習ノート」をデプロイする/learning_log/templates/500.html: -------------------------------------------------------------------------------- 1 | {% extends "learning_logs/base.html" %} 2 | 3 | {% block page_header %} 4 |

内部エラーが発生しました (500)

5 | {% endblock page_header %} 6 | -------------------------------------------------------------------------------- /必修編/chapter01/Python3.sublime-build: -------------------------------------------------------------------------------- 1 | { 2 | "cmd": ["python3", "-u", "$file"], 3 | } -------------------------------------------------------------------------------- /必修編/chapter01/hello_world.py: -------------------------------------------------------------------------------- 1 | print("Hello Python world!") 2 | -------------------------------------------------------------------------------- /必修編/chapter02/apostrophe.py: -------------------------------------------------------------------------------- 1 | message = "One of Python's strengths is its diverse community." 2 | print(message) 3 | -------------------------------------------------------------------------------- /必修編/chapter02/comment.py: -------------------------------------------------------------------------------- 1 | # みんなに「こんにちは」と言う 2 | print("こんにちはPython使いのみなさん!") 3 | -------------------------------------------------------------------------------- /必修編/chapter02/full_name.py: -------------------------------------------------------------------------------- 1 | first_name = "ada" 2 | last_name = "lovelace" 3 | full_name = f"{first_name} {last_name}" 4 | message = f"こんにちは{full_name.title()}!" 5 | print(message) 6 | -------------------------------------------------------------------------------- /必修編/chapter02/hello_world.py: -------------------------------------------------------------------------------- 1 | message = "Hello Python world!" 2 | print(message) 3 | 4 | message = "Hello Python短期集中コース 基本編 world!" 5 | print(message) 6 | -------------------------------------------------------------------------------- /必修編/chapter02/name.py: -------------------------------------------------------------------------------- 1 | name = "ada lovelace" 2 | print(name.upper()) 3 | print(name.lower()) 4 | -------------------------------------------------------------------------------- /必修編/chapter03/bicycles.py: -------------------------------------------------------------------------------- 1 | bicycles = ['trek', 'cannondale', 'redline', 'specialized'] 2 | message = f"私の最初の自転車は{bicycles[0].title()}でした。" 3 | 4 | print(message) 5 | -------------------------------------------------------------------------------- /必修編/chapter03/cars.py: -------------------------------------------------------------------------------- 1 | cars = ['bmw', 'audi', 'toyota', 'subaru'] 2 | print(cars) 3 | 4 | cars.reverse() 5 | print(cars) 6 | -------------------------------------------------------------------------------- /必修編/chapter03/motorcycles.py: -------------------------------------------------------------------------------- 1 | motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati'] 2 | print(motorcycles) 3 | 4 | too_expensive = 'ducati' 5 | motorcycles.remove(too_expensive) 6 | print(motorcycles) 7 | print(f"\n{too_expensive.title()}は私には高すぎます。") 8 | -------------------------------------------------------------------------------- /必修編/chapter04/dimensions.py: -------------------------------------------------------------------------------- 1 | dimensions = (200, 50) 2 | print("元のサイズ") 3 | for dimension in dimensions: 4 | print(dimension) 5 | 6 | dimensions = (400, 100) 7 | print("\n変更したサイズ") 8 | for dimension in dimensions: 9 | print(dimension) 10 | -------------------------------------------------------------------------------- /必修編/chapter04/even_numbers.py: -------------------------------------------------------------------------------- 1 | even_numbers = list(range(2, 11, 2)) 2 | print(even_numbers) 3 | -------------------------------------------------------------------------------- /必修編/chapter04/first_numbers.py: -------------------------------------------------------------------------------- 1 | numbers = list(range(1, 6)) 2 | print(numbers) 3 | -------------------------------------------------------------------------------- /必修編/chapter04/foods.py: -------------------------------------------------------------------------------- 1 | my_foods = ['ピザ', 'だんご', 'ケーキ'] 2 | friend_foods = my_foods[:] 3 | 4 | my_foods.append('チョコレート') 5 | friend_foods.append('アイスクリーム') 6 | 7 | print("私が好きな食べ物") 8 | print(my_foods) 9 | 10 | print("\n友達が好きな食べ物") 11 | print(friend_foods) 12 | -------------------------------------------------------------------------------- /必修編/chapter04/magicians.py: -------------------------------------------------------------------------------- 1 | magicians = ['alice', 'david', 'carolina'] 2 | for magician in magicians: 3 | print(f"{magician.title()}は素晴らしい手品を演じた!") 4 | print(f"私は{magician.title()}の次の手品が待ちきれない。\n") 5 | 6 | print("みなさんありがとう。素晴らしい手品ショーでした!") 7 | -------------------------------------------------------------------------------- /必修編/chapter04/players.py: -------------------------------------------------------------------------------- 1 | players = ['charles', 'martina', 'michael', 'florence', 'eli'] 2 | 3 | print("チームの最初の3人の選手です。") 4 | for player in players[:3]: 5 | print(player.title()) 6 | -------------------------------------------------------------------------------- /必修編/chapter04/squares.py: -------------------------------------------------------------------------------- 1 | squares = [value**2 for value in range(1, 11)] 2 | print(squares) 3 | -------------------------------------------------------------------------------- /必修編/chapter05/amusement_park.py: -------------------------------------------------------------------------------- 1 | age = 12 2 | if age < 4: 3 | price = 0 4 | elif age < 18: 5 | price = 2500 6 | elif age < 65: 7 | price = 4000 8 | elif age >= 65: 9 | price = 2000 10 | 11 | print(f"入場料金は{price}円です。") 12 | -------------------------------------------------------------------------------- /必修編/chapter05/banned_users.py: -------------------------------------------------------------------------------- 1 | banned_users = ['andrew', 'carolina', 'david'] 2 | user = 'marie' 3 | 4 | if user not in banned_users: 5 | print(f"{user.title()}はコメントを書き込めます。") 6 | -------------------------------------------------------------------------------- /必修編/chapter05/cars.py: -------------------------------------------------------------------------------- 1 | cars = ['audi', 'bmw', 'subaru', 'toyota'] 2 | 3 | for car in cars: 4 | if car == 'bmw': 5 | print(car.upper()) 6 | else: 7 | print(car.title()) 8 | -------------------------------------------------------------------------------- /必修編/chapter05/magic_number.py: -------------------------------------------------------------------------------- 1 | answer = 17 2 | 3 | if answer != 42: 4 | print("正しい答えではありません。もう一度挑戦してください!") 5 | -------------------------------------------------------------------------------- /必修編/chapter05/toppings.py: -------------------------------------------------------------------------------- 1 | available_toppings = ['マッシュルーム', 'オリーブ', 'ピーマン', 2 | 'ペパロニ', 'パイナップル', 'エクストラチーズ'] 3 | 4 | requested_toppings = ['マッシュルーム', 'フライドポテト', 'エクストラチーズ'] 5 | 6 | for requested_topping in requested_toppings: 7 | if requested_topping in available_toppings: 8 | print(f"ピザに{requested_topping}を追加します。") 9 | else: 10 | print(f"申し訳ありません、{requested_topping}はありません。") 11 | 12 | print("\nピザができました!") 13 | -------------------------------------------------------------------------------- /必修編/chapter05/voting.py: -------------------------------------------------------------------------------- 1 | age = 17 2 | if age >= 18: 3 | print("選挙権がある年齢です!") 4 | print("投票はしましたか?") 5 | else: 6 | print("申し訳ありません、投票するには若すぎるようです。") 7 | print("18歳になったら投票してください!") 8 | -------------------------------------------------------------------------------- /必修編/chapter06/alien.py: -------------------------------------------------------------------------------- 1 | alien_0 = {'x_position': 0, 'y_position': 25, 'speed': 'medium'} 2 | print(f"最初のX座標: {alien_0['x_position']}") 3 | 4 | # エイリアンは右に移動します。 5 | # 現在のスピードによってエイリアンの移動距離を決定します。 6 | if alien_0['speed'] == 'slow': 7 | x_increment = 1 8 | elif alien_0['speed'] == 'medium': 9 | x_increment = 2 10 | else: 11 | # 素早いエイリアン 12 | x_increment = 3 13 | 14 | # 新しい位置は元の位置に移動距離を加算します。 15 | alien_0['x_position'] = alien_0['x_position'] + x_increment 16 | 17 | print(f"新しいX座標: {alien_0['x_position']}") 18 | -------------------------------------------------------------------------------- /必修編/chapter06/alien_no_points.py: -------------------------------------------------------------------------------- 1 | alien_0 = {'color': 'green', 'speed': 'slow'} 2 | 3 | point_value = alien_0.get('points', '点数は設定されていません。') 4 | print(point_value) 5 | -------------------------------------------------------------------------------- /必修編/chapter06/aliens.py: -------------------------------------------------------------------------------- 1 | # エイリアンを格納する空のリストを作成する 2 | aliens = [] 3 | 4 | # 30匹のエイリアンを生成する 5 | for alien_number in range(30): 6 | new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'} 7 | aliens.append(new_alien) 8 | 9 | for alien in aliens[:3]: 10 | if alien['color'] == 'green': 11 | alien['color'] = 'yellow' 12 | alien['speed'] = 'medium' 13 | alien['points'] = 10 14 | 15 | # 最初の5匹のエイリアンの情報を出力する 16 | for alien in aliens[:5]: 17 | print(alien) 18 | print("...") 19 | 20 | # 生成されたエイリアンの数を出力する 21 | print(f"全エイリアンの数: {len(aliens)}") 22 | -------------------------------------------------------------------------------- /必修編/chapter06/favorite_languages.py: -------------------------------------------------------------------------------- 1 | favorite_languages = { 2 | 'jen': 'python', 3 | 'sarah': 'c', 4 | 'edward': 'ruby', 5 | 'phil': 'python', 6 | } 7 | 8 | friends = ['phil', 'sarah'] 9 | for name in favorite_languages.keys(): 10 | print(name.title()) 11 | if name in friends: 12 | language = favorite_languages[name].title() 13 | print(f"\t{name.title()}、あなたの好きなプログラミング言語は{language}ですね!") 14 | -------------------------------------------------------------------------------- /必修編/chapter06/many_users.py: -------------------------------------------------------------------------------- 1 | users = { 2 | 'aeinstein': { 3 | 'first': 'albert', 4 | 'last': 'einstein', 5 | 'location': 'princeton', 6 | }, 7 | 8 | 'mcurie': { 9 | 'first': 'marie', 10 | 'last': 'curie', 11 | 'location': 'paris', 12 | }, 13 | 14 | } 15 | 16 | for username, user_info in users.items(): 17 | print(f"\nユーザー名: {username}") 18 | full_name = f"{user_info['first']} {user_info['last']}" 19 | location = user_info['location'] 20 | 21 | print(f"\t氏名: {full_name.title()}") 22 | print(f"\t場所: {location.title()}") 23 | -------------------------------------------------------------------------------- /必修編/chapter06/pizza.py: -------------------------------------------------------------------------------- 1 | # ピザの注文に関する情報を格納する 2 | pizza = { 3 | 'crust': 'レギュラー', 4 | 'toppings': ['マッシュルーム', 'エクストラチーズ'], 5 | } 6 | 7 | # 注文の要約 8 | print(f"あなたが注文したのは{pizza['crust']}生地のピザで、" 9 | "トッピングは以下のとおりです。") 10 | 11 | for topping in pizza['toppings']: 12 | print("\t" + topping) 13 | -------------------------------------------------------------------------------- /必修編/chapter06/user.py: -------------------------------------------------------------------------------- 1 | user_0 = { 2 | 'username': 'efermi', 3 | 'first': 'enrico', 4 | 'last': 'fermi', 5 | } 6 | 7 | for key, value in user_0.items(): 8 | print(f"\nキー: {key}") 9 | print(f"値: {value}") 10 | -------------------------------------------------------------------------------- /必修編/chapter07/cities.py: -------------------------------------------------------------------------------- 1 | prompt = "\n行ったことのある街を教えてください:" 2 | prompt += "\n(終わったら '終了' と入力してください。) " 3 | 4 | while True: 5 | city = input(prompt) 6 | 7 | if city == '終了': 8 | break 9 | else: 10 | print(f"{city.title()}に行くのって最高です!") 11 | -------------------------------------------------------------------------------- /必修編/chapter07/confirmed_users.py: -------------------------------------------------------------------------------- 1 | # 確認が必要なユーザーから始める 2 | # 確認済みのユーザーを保持するための空のリストを用意する 3 | unconfirmed_users = ['alice', 'brian', 'candace'] 4 | confirmed_users = [] 5 | 6 | # 未確認ユーザーがいなくなるまでユーザーの確認を進める 7 | # 確認済みのユーザーは確認済みリストに移動する 8 | while unconfirmed_users: 9 | current_user = unconfirmed_users.pop() 10 | 11 | print(f"確認中のユーザー: {current_user.title()}") 12 | confirmed_users.append(current_user) 13 | 14 | # 確認済みのユーザーをすべて表示する 15 | print("\n以下のユーザーは確認済みです。") 16 | for confirmed_user in confirmed_users: 17 | print(confirmed_user.title()) 18 | -------------------------------------------------------------------------------- /必修編/chapter07/counting.py: -------------------------------------------------------------------------------- 1 | current_number = 0 2 | while current_number < 10: 3 | current_number += 1 4 | if current_number % 2 == 0: 5 | continue 6 | 7 | print(current_number) 8 | -------------------------------------------------------------------------------- /必修編/chapter07/even_or_odd.py: -------------------------------------------------------------------------------- 1 | number = input("何か数を入力してください。奇数か偶数かを判定します: ") 2 | number = int(number) 3 | 4 | if number % 2 == 0: 5 | print(f"\n数{number}は偶数です。") 6 | else: 7 | print(f"\n数{number}は奇数です。") 8 | -------------------------------------------------------------------------------- /必修編/chapter07/greeter.py: -------------------------------------------------------------------------------- 1 | prompt = "あなたが誰か教えてくれたら、あなた向けのあいさつをします。" 2 | prompt += "\nあなたの名前は? " 3 | name = input(prompt) 4 | print(f"\nこんにちは、{name}!") 5 | -------------------------------------------------------------------------------- /必修編/chapter07/mountain_poll.py: -------------------------------------------------------------------------------- 1 | responses = {} 2 | 3 | # 投票がアクティブなことを示すフラグをセット 4 | polling_active = True 5 | 6 | while polling_active: 7 | # 入力プロンプトで名前と回答を受け付ける 8 | name = input("\nあなたのお名前は? ") 9 | response = input("いつか登りたい山は何ですか? ") 10 | 11 | # 回答を辞書に保存する 12 | responses[name] = response 13 | 14 | # 誰か他に投票する人がいるかどうか確認する 15 | repeat = input("誰か他に回答してくれる人はいますか? (yes/ no) ") 16 | if repeat == 'no': 17 | polling_active = False 18 | 19 | # 投票を終了し、結果を表示する 20 | print("\n--- 投票結果 ---") 21 | for name, response in responses.items(): 22 | print(f"{name}さんが登りたいのは{response}です。") 23 | -------------------------------------------------------------------------------- /必修編/chapter07/parrot.py: -------------------------------------------------------------------------------- 1 | prompt = "\n何か書いてください。繰り返してお返事します。" 2 | prompt += "\nプログラムを止めるには '終了' と入力してください。 " 3 | 4 | active = True 5 | while active: 6 | message = input(prompt) 7 | 8 | if message == '終了': 9 | active = False 10 | else: 11 | print(message) 12 | -------------------------------------------------------------------------------- /必修編/chapter07/pets.py: -------------------------------------------------------------------------------- 1 | pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat'] 2 | print(pets) 3 | 4 | while 'cat' in pets: 5 | pets.remove('cat') 6 | 7 | print(pets) 8 | -------------------------------------------------------------------------------- /必修編/chapter07/rollercoaster.py: -------------------------------------------------------------------------------- 1 | height = input("身長は何センチ? ") 2 | height = int(height) 3 | 4 | if height >= 90: 5 | print("\n乗ってもいいですよ!") 6 | else: 7 | print("\nもうちょっと大きくなったらね。") 8 | -------------------------------------------------------------------------------- /必修編/chapter08/formatted_name.py: -------------------------------------------------------------------------------- 1 | def get_formatted_name(first_name, last_name, middle_name=''): 2 | """フォーマットされたフルネームを返す""" 3 | if middle_name: 4 | full_name = f"{first_name} {middle_name} {last_name}" 5 | else: 6 | full_name = f"{first_name} {last_name}" 7 | return full_name.title() 8 | 9 | musician = get_formatted_name('jimi', 'hendrix') 10 | print(musician) 11 | 12 | musician = get_formatted_name('john', 'hooker', 'lee') 13 | print(musician) 14 | -------------------------------------------------------------------------------- /必修編/chapter08/greet_users.py: -------------------------------------------------------------------------------- 1 | def greet_users(names): 2 | """リストの各ユーザーに対してシンプルなあいさつを出力する""" 3 | for name in names: 4 | msg = f"こんにちは{name.title()}!" 5 | print(msg) 6 | 7 | usernames = ['hannah', 'ty', 'margot'] 8 | greet_users(usernames) 9 | -------------------------------------------------------------------------------- /必修編/chapter08/greeter.py: -------------------------------------------------------------------------------- 1 | def get_formatted_name(first_name, last_name): 2 | """フォーマットされたフルネームを返す""" 3 | full_name = f"{first_name} {last_name}" 4 | return full_name.title() 5 | 6 | # これは無限ループです! 7 | while True: 8 | print("\nあなたの名前を教えてください。") 9 | print("('q' を入力すると終了します)") 10 | 11 | l_name = input("姓を入力してください: ") 12 | if l_name == 'q': 13 | break 14 | 15 | f_name = input("名を入力してください: ") 16 | if f_name == 'q': 17 | break 18 | 19 | formatted_name = get_formatted_name(f_name, l_name) 20 | print(f"\nこんにちは{formatted_name}!") 21 | -------------------------------------------------------------------------------- /必修編/chapter08/making_pizzas.py: -------------------------------------------------------------------------------- 1 | import pizza 2 | 3 | pizza.make_pizza(16, 'ペパロニ') 4 | pizza.make_pizza(12, 'マッシュルーム', 'ピーマン', 'エクストラチーズ') 5 | -------------------------------------------------------------------------------- /必修編/chapter08/person.py: -------------------------------------------------------------------------------- 1 | def build_person(first_name, last_name, age=None): 2 | """人についての情報を辞書で返す""" 3 | person = {'first': first_name, 'last': last_name} 4 | if age: 5 | person['age'] = age 6 | return person 7 | 8 | musician = build_person('jimi', 'hendrix', age=27) 9 | print(musician) 10 | -------------------------------------------------------------------------------- /必修編/chapter08/pets.py: -------------------------------------------------------------------------------- 1 | def describe_pet(pet_name, animal_type='イヌ'): 2 | """ペットについての情報を出力する。""" 3 | print(f"\n私は{animal_type}を飼っています。") 4 | print(f"{animal_type}の名前は{pet_name.title()}です。") 5 | 6 | describe_pet(pet_name='ウィリー') 7 | -------------------------------------------------------------------------------- /必修編/chapter08/pizza.py: -------------------------------------------------------------------------------- 1 | def make_pizza(size, *toppings): 2 | """注文されたピザの要約を出力する""" 3 | print(f"\n{size}インチのピザを、以下のトッピングで作ります。") 4 | for topping in toppings: 5 | print(f"- {topping}") 6 | -------------------------------------------------------------------------------- /必修編/chapter08/printing_models.py: -------------------------------------------------------------------------------- 1 | def print_models(unprinted_designs, completed_models): 2 | """ 3 | リストからなくなるまでデザインを3D印刷する 4 | 各デザインは印刷後に completed_models に移動する 5 | """ 6 | while unprinted_designs: 7 | current_design = unprinted_designs.pop() 8 | print(f"3D印刷中: {current_design}") 9 | completed_models.append(current_design) 10 | 11 | def show_completed_models(completed_models): 12 | """3D印刷されたすべてのモデルの情報を出力する""" 13 | print("\n以下のデザインが3D印刷されました") 14 | for completed_model in completed_models: 15 | print(completed_model) 16 | 17 | unprinted_designs = ['iPhoneケース', 'ロボットのペンダント', '12面体'] 18 | completed_models = [] 19 | 20 | print_models(unprinted_designs, completed_models) 21 | show_completed_models(completed_models) 22 | -------------------------------------------------------------------------------- /必修編/chapter08/user_profile.py: -------------------------------------------------------------------------------- 1 | def build_profile(first, last, **user_info): 2 | """ユーザーの全情報を格納した辞書を作成する""" 3 | user_info['first_name'] = first 4 | user_info['last_name'] = last 5 | return user_info 6 | 7 | user_profile = build_profile('アルバート', 'アインシュタイン', 8 | location='プリンストン', 9 | field='物理学') 10 | print(user_profile) 11 | -------------------------------------------------------------------------------- /必修編/chapter09/car.py: -------------------------------------------------------------------------------- 1 | class Car: 2 | """自動車を表すシンプルな実装例""" 3 | 4 | def __init__(self, make, model, year): 5 | """自動車の特徴となる属性を初期化する""" 6 | self.make = make 7 | self.model = model 8 | self.year = year 9 | self.odometer_reading = 0 10 | 11 | def get_descriptive_name(self): 12 | """フォーマットされた名前を返す""" 13 | long_name = f"{self.year} {self.make} {self.model}" 14 | return long_name.title() 15 | 16 | def read_odometer(self): 17 | """自動車の走行距離を出力する""" 18 | print(f"走行距離は{self.odometer_reading}kmです。") 19 | 20 | def update_odometer(self, km): 21 | """ 22 | 指定された値で走行距離を更新します。 23 | 走行距離を減らそうとする処理は拒否します。 24 | """ 25 | if km >= self.odometer_reading: 26 | self.odometer_reading = km 27 | else: 28 | print("走行距離は減らせません!") 29 | 30 | def increment_odometer(self, km): 31 | """指定された距離を走行距離に追加する""" 32 | self.odometer_reading += km 33 | 34 | my_used_car = Car('subaru', 'outback', 2015) 35 | print(my_used_car.get_descriptive_name()) 36 | 37 | my_used_car.update_odometer(23_500) 38 | my_used_car.read_odometer() 39 | 40 | my_used_car.increment_odometer(100) 41 | my_used_car.read_odometer() 42 | -------------------------------------------------------------------------------- /必修編/chapter09/dog.py: -------------------------------------------------------------------------------- 1 | class Dog: 2 | """イヌをモデル化したシンプルな実装例""" 3 | 4 | def __init__(self, name, age): 5 | """名前と年齢の属性を初期化する""" 6 | self.name = name 7 | self.age = age 8 | 9 | def sit(self): 10 | """イヌに「おすわり」の命令を実行する""" 11 | print(f"{self.name}はおすわりしている。") 12 | 13 | def roll_over(self): 14 | """イヌに「ごろーん」の命令を実行する""" 15 | print(f"{self.name}がごろーんした!") 16 | 17 | my_dog = Dog('ウィリー', 6) 18 | your_dog = Dog('ルーシー', 3) 19 | 20 | print(f"私のイヌの名前は{my_dog.name}です。") 21 | print(f"私のイヌは{my_dog.age}歳です。") 22 | my_dog.sit() 23 | 24 | print(f"\nあなたのイヌの名前は{your_dog.name}です。") 25 | print(f"あなたのイヌは{your_dog.age}歳です。") 26 | your_dog.sit() 27 | -------------------------------------------------------------------------------- /必修編/chapter09/クラスをインポートする/my_car.py: -------------------------------------------------------------------------------- 1 | from car import Car 2 | 3 | my_new_car = Car('audi', 'a4', 2019) 4 | print(my_new_car.get_descriptive_name()) 5 | 6 | my_new_car.odometer_reading = 23 7 | my_new_car.read_odometer() 8 | -------------------------------------------------------------------------------- /必修編/chapter09/クラスをインポートする/my_cars.py: -------------------------------------------------------------------------------- 1 | from car import Car, ElectricCar 2 | 3 | my_beetle = Car('volkswagen', 'beetle', 2019) 4 | print(my_beetle.get_descriptive_name()) 5 | 6 | my_tesla = ElectricCar('tesla', 'roadster', 2019) 7 | print(my_tesla.get_descriptive_name()) 8 | -------------------------------------------------------------------------------- /必修編/chapter09/クラスをインポートする/my_electric_car.py: -------------------------------------------------------------------------------- 1 | from car import ElectricCar 2 | 3 | my_tesla = ElectricCar('tesla', 'model s', 2019) 4 | 5 | print(my_tesla.get_descriptive_name()) 6 | my_tesla.battery.describe_battery() 7 | my_tesla.battery.get_range() 8 | -------------------------------------------------------------------------------- /必修編/chapter10/alice.py: -------------------------------------------------------------------------------- 1 | filename = 'alice.txt' 2 | 3 | try: 4 | with open(filename, encoding='utf-8') as f: 5 | contents = f.read() 6 | except FileNotFoundError: 7 | print(f"ごめんなさい。{filename} は見当たりません。") 8 | else: 9 | # ファイル内のだいたいの単語の数を数える 10 | words = contents.split() 11 | num_words = len(words) 12 | print(f"ファイル {filename} には約{num_words}の単語が含まれます。") 13 | -------------------------------------------------------------------------------- /必修編/chapter10/division_calculator.py: -------------------------------------------------------------------------------- 1 | print("数を2つ教えてください。割り算します。") 2 | print("終了するには 'q' を入力してください。") 3 | 4 | while True: 5 | first_number = input("\n1番目の数: ") 6 | if first_number == 'q': 7 | break 8 | second_number = input("2番目の数: ") 9 | if second_number == 'q': 10 | break 11 | try: 12 | answer = int(first_number) / int(second_number) 13 | except ZeroDivisionError: 14 | print("ゼロで割ることはできません!") 15 | else: 16 | print(answer) 17 | -------------------------------------------------------------------------------- /必修編/chapter10/file_reader.py: -------------------------------------------------------------------------------- 1 | filename = 'pi_digits.txt' 2 | 3 | with open(filename) as file_object: 4 | lines = file_object.readlines() 5 | 6 | for line in lines: 7 | print(line.rstrip()) 8 | -------------------------------------------------------------------------------- /必修編/chapter10/greet_user.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | filename = 'username.json' 4 | 5 | with open(filename) as f: 6 | username = json.load(f) 7 | print(f"おかえりなさい、{username}さん!") 8 | -------------------------------------------------------------------------------- /必修編/chapter10/number_reader.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | filename = 'numbers.json' 4 | with open(filename) as f: 5 | numbers = json.load(f) 6 | 7 | print(numbers) 8 | -------------------------------------------------------------------------------- /必修編/chapter10/number_writer.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | numbers = [2, 3, 5, 7, 11, 13] 4 | 5 | filename = 'numbers.json' 6 | with open(filename, 'w') as f: 7 | json.dump(numbers, f) 8 | -------------------------------------------------------------------------------- /必修編/chapter10/pi_digits.txt: -------------------------------------------------------------------------------- 1 | 3.1415926535 2 | 8979323846 3 | 2643383279 4 | -------------------------------------------------------------------------------- /必修編/chapter10/pi_string.py: -------------------------------------------------------------------------------- 1 | filename = 'pi_million_digits.txt' 2 | 3 | with open(filename) as file_object: 4 | lines = file_object.readlines() 5 | 6 | pi_string = '' 7 | for line in lines: 8 | pi_string += line.strip() 9 | 10 | birthday = input("誕生日をmmddyyフォーマットで入力してください: ") 11 | if birthday in pi_string: 12 | print("円周率の最初の100万桁にあなたの誕生日が見つかりました!") 13 | else: 14 | print("円周率の最初の100万桁にあなたの誕生日は見当たらないようです。") 15 | -------------------------------------------------------------------------------- /必修編/chapter10/remember_me.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | def get_stored_username(): 4 | """保存されたユーザー名があれば取得する。""" 5 | filename = 'username.json' 6 | try: 7 | with open(filename) as f: 8 | username = json.load(f) 9 | except FileNotFoundError: 10 | return None 11 | else: 12 | return username 13 | 14 | def get_new_username(): 15 | """新たなユーザー名の入力を促す。""" 16 | username = input("あなたのお名前は? ") 17 | filename = 'username.json' 18 | with open(filename, 'w') as f: 19 | json.dump(username, f) 20 | return username 21 | 22 | def greet_user(): 23 | """ユーザー名であいさつする。""" 24 | username = get_stored_username() 25 | if username: 26 | print(f"おかえりなさい、{username}さん!") 27 | else: 28 | username = get_new_username() 29 | print(f"戻ってきたときにも名前を覚えていますよ、{username}さん!") 30 | 31 | greet_user() 32 | -------------------------------------------------------------------------------- /必修編/chapter10/word_count.py: -------------------------------------------------------------------------------- 1 | def count_words(filename): 2 | """ファイルに含まれるだいたいの単語の数を数える。""" 3 | try: 4 | with open(filename, encoding='utf-8') as f: 5 | contents = f.read() 6 | except FileNotFoundError: 7 | pass 8 | else: 9 | words = contents.split() 10 | num_words = len(words) 11 | print(f"ファイル {filename} には約{num_words}の単語が含まれます。") 12 | 13 | filenames = ['alice.txt', 'siddhartha.txt', 'moby_dick.txt', 'little_women.txt'] 14 | for filename in filenames: 15 | count_words(filename) 16 | -------------------------------------------------------------------------------- /必修編/chapter10/write_message.py: -------------------------------------------------------------------------------- 1 | filename = 'programming.txt' 2 | 3 | with open(filename, 'a') as file_object: 4 | file_object.write("I also love finding meaning in large datasets.\n") 5 | file_object.write("I love creating apps that can run in a browser.\n") 6 | -------------------------------------------------------------------------------- /必修編/chapter11/language_survey.py: -------------------------------------------------------------------------------- 1 | from survey import AnonymousSurvey 2 | 3 | # 質問文を定義し、アンケート調査を作成する 4 | question = "最初に勉強した言語は何ですか?" 5 | my_survey = AnonymousSurvey(question) 6 | 7 | # 質問を表示し、質問に対する回答を保存する 8 | my_survey.show_question() 9 | print("'q' を入力すると終了します\n") 10 | while True: 11 | response = input("言語: ") 12 | if response == 'q': 13 | break 14 | my_survey.store_response(response) 15 | 16 | # アンケート調査の結果を表示する 17 | print("\nアンケート調査にご協力ありがとうございます!") 18 | my_survey.show_results() 19 | -------------------------------------------------------------------------------- /必修編/chapter11/name_function.py: -------------------------------------------------------------------------------- 1 | def get_formatted_name(first, last, middle=''): 2 | """フォーマットされたフルネームを返す""" 3 | if middle: 4 | full_name = f"{first} {middle} {last}" 5 | else: 6 | full_name = f"{first} {last}" 7 | return full_name.title() 8 | -------------------------------------------------------------------------------- /必修編/chapter11/names.py: -------------------------------------------------------------------------------- 1 | from name_function import get_formatted_name 2 | 3 | print("'q' を入力すると終了します。") 4 | while True: 5 | first = input("\n名を入力してください: ") 6 | if first == 'q': 7 | break 8 | last = input("姓を入力してください: ") 9 | if last == 'q': 10 | break 11 | 12 | formatted_name = get_formatted_name(first, last) 13 | print(f"\tフォーマットされた名前: {formatted_name}.") 14 | -------------------------------------------------------------------------------- /必修編/chapter11/survey.py: -------------------------------------------------------------------------------- 1 | class AnonymousSurvey: 2 | """アンケートの質問に対する匿名の回答を集める""" 3 | 4 | def __init__(self, question): 5 | """質問を格納し、回答を格納する領域を用意する""" 6 | self.question = question 7 | self.responses = [] 8 | 9 | def show_question(self): 10 | """アンケートの質問を表示する""" 11 | print(self.question) 12 | 13 | def store_response(self, new_response): 14 | """質問に対する回答を1件格納する""" 15 | self.responses.append(new_response) 16 | 17 | def show_results(self): 18 | """すべての回答を表示する""" 19 | print("アンケートの回答:") 20 | for response in self.responses: 21 | print(f"- {response}") 22 | -------------------------------------------------------------------------------- /必修編/chapter11/test_name_function.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from name_function import get_formatted_name 3 | 4 | class NamesTestCase(unittest.TestCase): 5 | """name_function.py をテストする""" 6 | 7 | def test_first_last_name(self): 8 | """'Janis Joplin' のような名前で動作するか?""" 9 | formatted_name = get_formatted_name('janis', 'joplin') 10 | self.assertEqual(formatted_name, 'Janis Joplin') 11 | 12 | def test_first_last_middle_name(self): 13 | """'Wolfgang Amadeus Mozart' のような名前で正しく動作するか?""" 14 | formatted_name = get_formatted_name( 15 | 'wolfgang', 'mozart', 'amadeus') 16 | self.assertEqual(formatted_name, 'Wolfgang Amadeus Mozart') 17 | 18 | if __name__ == '__main__': 19 | unittest.main() 20 | -------------------------------------------------------------------------------- /必修編/chapter11/test_survey.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from survey import AnonymousSurvey 3 | 4 | class TestAnonymousSurvey(unittest.TestCase): 5 | """AnonymousSurveyクラスのテスト""" 6 | 7 | def setUp(self): 8 | """ 9 | 全テストメソッドで使用できるアンケート調査インスタンスと回答のリスト 10 | """ 11 | question = "最初に勉強した言語は何ですか?" 12 | self.my_survey = AnonymousSurvey(question) 13 | self.responses = ['英語', 'スペイン語', '中国語'] 14 | 15 | def test_store_single_response(self): 16 | """1件の回答が正しく保存されているかをテストする""" 17 | self.my_survey.store_response(self.responses[0]) 18 | self.assertIn(self.responses[0], self.my_survey.responses) 19 | 20 | def test_store_three_responses(self): 21 | """3件の異なる回答が正しく保存されているかをテストする""" 22 | for response in self.responses: 23 | self.my_survey.store_response(response) 24 | for response in self.responses: 25 | self.assertIn(response, self.my_survey.responses) 26 | 27 | if __name__ == '__main__': 28 | unittest.main() 29 | -------------------------------------------------------------------------------- /必修編/インストール手順/win-install.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/takanory/saitan-python/8196a91a9aac5011bc29782381b93f143b0ae25a/必修編/インストール手順/win-install.png -------------------------------------------------------------------------------- /必修編/インストール手順/windows.md: -------------------------------------------------------------------------------- 1 | # WindowsでのPythonインストール手順 2 | 3 | ## Pythonをインストールする 4 | 5 | はじめに、PCにPythonがインストールされているかを確認します。 6 | スタートメニューに「command」と入力します。 7 | コマンドプロンプトのターミナル画面を表示して、pythonと小文字で入力します。 8 | Pythonプロンプト(`>>>`)が表示されたら、PCにはPythonがインストールされています。 9 | pythonというコマンドが認識できないという意味のエラーメッセージが表示された場合は、Pythonがインストールされていません。 10 | 11 | エラーだった場合またはPythonのバージョンが3.6より古かった場合は、Windows用のPythonインストーラーをダウンロードします。 12 | https://python.org を開き、「Downloads」リンクの上にマウスカーソルを移動します。 13 | 最新バージョンのPythonのダウンロード用ボタンが表示されます。 14 | ボタンをクリックすると、OSに対応したインストーラーのダウンロードが始まります。 15 | ファイルのダウンロードが終了したら、インストーラーを起動します。 16 | 「Add Python 3.8 to PATH」オプションを選択することにより、システムに正しくパス 17 | が設定されます。 18 | 19 | ![Windowsのインストール画面](win-install.png) 20 | 21 | ## Pythonをターミナル上で動かす 22 | 23 | ターミナル画面を開いて小文字でpythonと入力します。 24 | Pythonプロンプト(`>>>`)が表示されます。 25 | これは、先ほどインストールしたPythonをWindowsが見つけたことを意味します。 26 | 27 | ``` 28 | C:¥> python 29 | Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:20:19) [MSC v.1925 32 bit (Intel)] on win32 30 | Type "help", "copyright", "credits" or "license" for more information. 31 | >>> 32 | ``` 33 | 34 | 対話モードを終了するには、 **Ctrl+Z** キーと **Enter** キーを押すか、 `exit()` と入力してください。 35 | 36 | ## Sublime Textをインストールする 37 | 38 | Sublime Textのインストーラーは、Webサイト( https://sublimetext.com/ )からダウンロードできます。 39 | 「Download」リンクをクリックし、Windows用のインストーラーを探します。 40 | インストーラーをダウンロードしたら、実行してインストールします。設定はすべてデフォルトにします。 41 | --------------------------------------------------------------------------------