EX-BOUNDARY

境界(私)を広げるように生きたい私の日々の日記

python 1日目

pythonのプログラミング学習1日目の記録

progate

やったこと

Lv1
  • if文(if,else,elifの使い方)
Lv2
  • リスト(aaa = [xxx , xxx , xxx])

  • for文(for ... in ...:)

  • 辞書(aaa = {'xxx' : 'yyy' , ....})

  • while文(while i <= n:)、break、continue

  • 買い物システム

money = 1000
items = {'apple': 100, 'banana': 200, 'orange': 400}
for item_name in items:
    print('--------------------------------------------------')
    print('財布には' + str(money) + '円入っています')
    print(item_name + 'は1個' + str(items[item_name]) + '円です')
    
    input_count = input('購入する' + item_name + 'の個数を入力してください:')
    print('購入する' + item_name + 'の個数は' + input_count + '個です')
    
    count = int(input_count)
    total_price = items[item_name] * count
    print('支払い金額は' + str(total_price) + '円です')
    
    if money >= total_price:
        print(item_name + 'を' + input_count + '個買いました')
        money -= total_price
        # if文を用いて、moneyの値が0のときの条件を分岐してください
        if money == 0:
            print('財布が空になりました')
        
    else:
        print('お金が足りません')
        print(item_name + 'を買えませんでした')
        break
# 変数moneyと型変換を用いて、「残金は◯◯円です」となるように出力してください
print('残金は' + str(money) + '円です')
Lv3
  • 関数(def 関数名(引数):)

  • ジャンケンゲーム

script.py

import utils
# randomモジュールを読み込んでください
import random

print('じゃんけんをはじめます')
player_name = input('名前を入力してください:')
print('何を出しますか?(0: グー, 1: チョキ, 2: パー)')
player_hand = int(input('数字で入力してください:'))

if utils.validate(player_hand):
    # randintを用いて0から2までの数値を取得し、変数computer_handに代入してください
    computer_hand = random.randint(0 , 2)
    
    if player_name == '':
        utils.print_hand(player_hand)
    else:
        utils.print_hand(player_hand, player_name)

    utils.print_hand(computer_hand, 'コンピューター')
    
    result = utils.judge(player_hand, computer_hand)
    print('結果は' + result + 'でした')
else:
    print('正しい数値を入力してください')

utils.py

def validate(hand):
    if hand < 0 or hand > 2:
        return False
    return True

def print_hand(hand, name='ゲスト'):
    hands = ['グー', 'チョキ', 'パー']
    print(name + 'は' + hands[hand] + 'を出しました')

def judge(player, computer):
    if player == computer:
        return '引き分け'
    elif player == 0 and computer == 1:
        return '勝ち'
    elif player == 1 and computer == 2:
        return '勝ち'
    elif player == 2 and computer == 0:
        return '勝ち'
    else:
        return '負け'
Lv4

script.py

from menu_item import MenuItem

menu_item1 = MenuItem('サンドイッチ', 500)
menu_item2 = MenuItem('チョコケーキ', 400)
menu_item3 = MenuItem('コーヒー', 300)
menu_item4 = MenuItem('オレンジジュース', 200)

menu_items = [menu_item1, menu_item2, menu_item3, menu_item4]

index = 0

for menu_item in menu_items:
    print(str(index) + '. ' + menu_item.info())
    index += 1

print('--------------------')

order = int(input('メニューの番号を入力してください: '))
selected_menu = menu_items[order]
print('選択されたメニュー: ' + selected_menu.name)

# コンソールから入力を受け取り、変数countに代入してください
count = int(input('個数を入力してください(3つ以上で1割引): '))

# get_total_priceメソッドを呼び出してください
result = selected_menu.get_total_price(count)

# 「合計は〇〇円です」となるように出力してください
print('合計は' + str(result) + '円です'

menu_item.py

class MenuItem:
    def __init__(self, name, price):
        self.name = name
        self.price = price

    def info(self):
        return self.name + ': ¥' + str(self.price)

    def get_total_price(self, count):
        total_price = self.price * count
        
        # countが3以上のとき、total_priceに0.9をかけてください
        if count >= 3:
            total_price = total_price * 0.9
        
        # total_priceを四捨五入して、returnしてください
        return round(total_price)
Lv5
  • クラスの継承(food1 = Food(aaa,aaa))

  • オーバーライド、super()

  • 料理注文システム

script.py

from food import Food
from drink import Drink

food1 = Food('サンドイッチ', 500, 330)
food2 = Food('チョコケーキ', 400, 450)
food3 = Food('シュークリーム', 200, 180)

foods = [food1, food2, food3]

drink1 = Drink('コーヒー', 300, 180)
drink2 = Drink('オレンジジュース', 200, 350)
drink3 = Drink('エスプレッソ', 300, 30)

drinks = [drink1, drink2, drink3]

print('食べ物メニュー')
index = 0
for food in foods:
    print(str(index) + '. ' + food.info())
    index += 1

print('飲み物メニュー')
index = 0
for drink in drinks:
    print(str(index) + '. ' + drink.info())
    index += 1

print('--------------------')

food_order = int(input('食べ物の番号を選択してください: '))
selected_food = foods[food_order]

drink_order = int(input('飲み物の番号を選択してください: '))
selected_drink = drinks[drink_order]

# コンソールから入力を受け取り、変数countに代入してください
count = int(input('何セット買いますか?(3つ以上で1割引): '))

# selected_foodとselected_drinkのそれぞれに対して、get_total_priceメソッドを呼び出してください
result = selected_food.get_total_price(count) + selected_drink.get_total_price(count)

# 「合計は〇〇円です」となるように出力してください
print('合計は' + str(result) + '円です')

menu_item.py

class MenuItem:
    def __init__(self, name, price):
        self.name = name
        self.price = price

    def info(self):
        return self.name + ': ¥' + str(self.price)

    def get_total_price(self, count):
        total_price = self.price * count

        if count >= 3:
            total_price *= 0.9

        return round(total_price)

food.py

from menu_item import MenuItem

class Food(MenuItem):
    def __init__(self, name, price, calorie):
        super().__init__(name, price)
        self.calorie = calorie
    
    def info(self):
        return self.name + ': ¥' + str(self.price) + ' (' + str(self.calorie) + 'kcal)'
    
    def calorie_info(self):
        print(str(self.calorie) + 'kcalです')

drink.py

from menu_item import MenuItem

class Drink(MenuItem):
    def __init__(self, name, price, amount):
        super().__init__(name, price)
        self.amount = amount

    def info(self):
        return self.name + ': ¥' + str(self.price) + ' (' + str(self.amount) + 'mL)'

checkiO

やったこと(Home)

Sum Numbers
  • isnumeric関数の扱い方
def sum_numbers(text: str) -> int:
    words = text.split()
    print(words)
    sum_num = 0
    for word in words:
        if word.isnumeric() is True:
            sum_num += int(word)
            print(sum_num)
        else:
            continue
    return int(sum_num)
Even the Last
  • 偶数盤目の取得方法(array[0::2]2個おきに取得の意味)
def checkio(array: list) -> int:
    if len(array) > 0 :
        sum_num = sum(array[0::2])*array[-1]
    else:
        sum_num = sum(array[0::2])
    return sum_num
Right to Left
  • replace関数の使い方

  • joinの使い方

def left_join(phrases: tuple) -> str:
    return ','.join(phrase.replace('right' , 'left') for phrase in phrases)
Three Words
  • isalpha関数

  • インクリメントの考え方

def checkio(words: str) -> bool:
    count = 0
    result = False
    for word in words.split():
        if word.isalpha():
            count += 1
        else:
            count = 0
        if count >= 3:
            return True
    return False
First Word
  • replace/splitの使い方
def first_word(text: str) -> str:
    return text.replace(',',' ').replace('.',' ').split()[0]
Days Between
  • datetime関数の使い方
import datetime

def days_diff(a, b):
    td_a = datetime.date(year=a[0], month=a[1], day=a[2])
    td_b = datetime.date(year=b[0], month=b[1], day=b[2])
    if td_a <= td_b:
        td = td_b - td_a
    else:
        td = td_a - td_b
    return td.days
Count Digits
  • findall関数の使い方

  • reライブラリの使い方

import re

def count_digits(text: str) -> int:
    return len(re.findall('\d',text))
Back Word Each Word
  • reライブラリの使い方

  • join/spritの使い方

import re

def backward_string_by_word(text: str) -> str:
    return " ".join([x[::-1] for x in text.split(" ")])

やったこと(Elementary)

Multiply
def mult_two(a, b):
    return a*b
Easy Unpack
  • 最後からのリストの取得方法list[-x]
def easy_unpack(elements: tuple) -> tuple:
    return (elements[0] , elements[2] , elements[-2])
First Word
  • splitの使い方
def first_word(text: str) -> str:
    return text.split()[0]
Acceptable Password
def is_acceptable_password(password: str) -> bool:
    return len(password) >6

進捗状況

f:id:darwin198712:20200927010655p:plain