LoginSignup
2
5

Python初心者の備忘録 #01

Last updated at Posted at 2023-06-05

はじめに

今回私は最近はやりのchatGPTに興味を持ち、深層学習について学んでみたいと思い立ちました!
深層学習といえばPythonということなので、最終的にはPythonを使って深層学習ができるとこまでコツコツと学習していくことにしました。
ただ、勉強するだけではなく少しでもアウトプットをしようということで、備忘録として学習した内容をまとめていこうと思います。
この記事が少しでも誰かの糧になることを願っております!
※投稿主の環境はWindowsなのでMacの方は多少違う部分が出てくると思いますが、ご了承ください。
最初の記事:ここ
次の記事:Python初心者の備忘録 #02

この記事はPythonの基礎について書かれています。

■学習に使用している資料

Udemy:米国AI開発者がゼロから教えるPython入門講座

■環境構築

・Python3系の最新verのインストール
・Pycharmのインストール

▶Python3系の最新verのインストール

  1. python.orgにアクセス
  2. Downloadsタブから自分の環境にあったPythonをダウンロード
    python_DL_screen.png
  3. ダウンロードしてきた.exeファイルをダブルクリックで起動して、インストールする。

▶Pycharmのインストール

※今回はIDE(統合開発環境)はPycharmを使用していますが、自分の使い慣れたIDEを使用してもらって大丈夫です。

  1. Pycharmのダウンロードページにアクセス
  2. 自分のOSを選択して、Communityをダウンロード
    Pycharm_DL_screen.png
  3. ダウンロードしてきた.exeファイルを起動して、インストールする。

以上で環境構築は完了です。

■Pythonの基礎

▶Hello World

とりあえず初めて触る言語のお約束、「Hello World」の出力

print("Hello World")

▶文字列型(strings)

ダブルクォーテーション「"」、もしくはシングルクォーテーション「'」で囲んだ文字列が文字列型(str型)として扱われる。

# ダブルクォーテーション
print("String")

# シングルクォーテーション
print('String')

さらに、ダブルクォーテーションかシングルクォーテーションを3つ並べて書くことで、複数行をstr型として扱うことができる。

# 複数行のstr型
print("""
複数行
str型
""")

ほかにも改行やタブ、エスケープ、文字同士の連結などは次のように書くことで反映することができる。

# 改行
print("break\nline")

# タブ
print("tab\tinserted!!")

# \でエスケープ
print("not break\\nline")
print("not tab\\tinserted!!")

# \で'や"をエスケープ可能
print('I\'m fine')

# + で連結
print("hello" + " world" + "!!")

▶変数への代入(assignment)

任意の文字に値を核のすること。
格納先を変数といい、格納することを代入という。

# 変数へ代入
hello = 'hello'
world = 'world'

# 変数を使用して、値を出力
print(hello)
print(world)

# もちろん、変数同士の結合も可能
print(hello + world)

▶変数の命名規則(neming convention)

  1. snake_case(単語と単語はアンダースコアで区切る)
  2. 文字から始まる
  3. 文字、数字、_(アンダースコア)を使う
  4. Case senzitive(大文字と小文字は区別する)

▶文字列に使用できる関数(formatとfstring)

文字列を補完するのに使用する関数で、formatは{}内に指定した文字を補完でき、fstringは文字列内で変数を使用することで、補完することができる。
どちらもできることは同じだが、formatよりfstringのほうが処理が速いのでfstringの使用が推奨されている。
※fstringはPython3.5以降しか対応していないので注意!!

# format
print("{} {}".format(hello, world))  # hello world

name = "John"
print("Hey {}, How are you doing?".format(name))

# fstring
print(f"Hello, {name}")

▶Built in Function

Pythonにもともと定義されている関数のこと。
今まで出てきた、print()やformat()もそれにあたる。
他にもtype()やid()などいろいろとあるので、気になる方は調べてみるのもいいかも!

# type() 渡した引数の"型"を返す
hello_type = type("Hello")
print(hello_type)

# id() 引数のメモリ内でのidを返す
print(id("hello"))

▶数値型(Numeric)

# int (Integer, 整数)
print(type(1))

# float (浮動小数点)
print(type(0.1))

# ちょうど0.3にはならないので注意
print(0.1 + 0.1 + 0.1)  # 正確には0.300000000000001とかになっている

▶数値演算子(Numeric Operator)

# 四則演算
print(1 + 0.4)  # 1.4
print(1 - 0.4)  # 0.6
print(2 * 3)  # 6
print(1 / 2)  # 0.5 int 同士の演算でもfloatになる

print(5*6 - 3/6)  # 29.5

# floatとintの計算結果はfloatになることに注意
result = 1 + 1.0
print(f"type of result:{result} is {type(result)}")

# その他の演算
print(14 // 3)  # 4 (floor division, 整数部)
print(14 % 3)  # 2 (modulo, 剰余, 余り)
print(2 ** 3)  # 6 (exponentiation, べき乗)

# 結果を変数に代入することも可能
result = 1 + 5
print("1 + 5 = {}".format(result))

# 変数同士の演算も可能
hit_point = 100
attack_point = 40.3
remain = hit_point - attack_point
print(f"remain hit point is {remain}")

# augmented assignment +=, -=, *=, /=
a = 1
a += 1 # a = a + 1 と同じ
print("a is {}".format(a))

hit_point = hit_point - attack_point
hit_point -= attack_point

# floatをfstingやformatで補完するときは,小数点を指定するといい {value:width.precision}
value = 1/3
print(f"value is {value}")  # value is 0.3333333
print(f"value is {value:.4f}")  # value is 0.3333
print(f"value is {value:.2f}")  # value is 0.33
print(f"value is {value:10.2f}")  # value is       0.33
print(f"value is {value:6.2f}")  # value is   0.33

▶Boolean型(bool)

True(真)とFalse(偽)の2つの値しか持たない。
何か条件を比較した際に、その条件が正しければTrue、間違っていればFalseという値になる。

balance = 1000
withdrawal = 500

print(balance > withdrawal) # True
print(balance <= withdrawal) # False

▶比較演算子

上記のコードにもある「>」や「<=」も比較演算子の1つで、基本的には左の式や値と右の式や値を比較して、正しければTrue、間違っていればFalseを結果として返す。

# 比較演算子 >, <, >=, <=, ==, !=
print(5 > 3)  # True
print(2.0 < 1)  # False
print(5 >= 5)  # True
print(5 <= 4)  # False
print(5 == 3)  # イコール、False
print(5 != 3)  # notイコール、True

print(1 == 1.0)  # True
print(1 == "1")  # False
print("1" == "1")  # True

▶is、is not演算子

同じオブジェクトかどうかを判断するために使用する演算子で、一番よくつかわれるのは変数や関数の値がNone(値が何もない、入っていない状態のこと)かどうかの識別に使用される。
同じオブジェクトというのは、メモリ内での格納場所(id)が一致するかどうかで判断されている。

# is演算子:同じオブジェクトかどうかを判定する
a = 1
b = 1
c = 3
d = a
e = 2 - 1  # 1
print(a is b)  # True
print(a is not c) # True
print(f"a's id: {id(a)}")
print(f"b's id: {id(b)}")
print(f"c's id: {id(c)}")
print(f"1's id: {id(1)}")

print(d is a)  # True
print(d is b)  # True
print(a is e)  # True

hello = "hello"
hello2 = "h" + "e" + "l" + "l" + "o"

print(hello, hello2)
print(hello is hello2)  # True

hello = "konnichiwa"
print(hello is hello2)  # False

nothing = None
print(nothing is None)
print(id(nothing))
print(id(None))

▶論理演算子(logical operators)

上記の比較演算子で値や式を評価する際に条件を複数定義したい場合に使用する。
and、or、notなどがあり、それぞれ日本語にすると「かつ、または、ではない」とすることができる。
・and:設定した条件がすべてTrueの場合にTrueを返す。
・or:設定した条件のどれか1つでもTrueの場合はTrueを返す。
・not:設定した条件がFalseの場合にTrueを返す。

# 論理演算子 logical operators
# and, or, not
a = 1
b = 1
c = 10
d = 100
first_condition = a == b
second_condition = c > d
print(first_condition)  # True
print(second_condition)  # False

print(first_condition and second_condition)  # False
print(first_condition or second_condition)  # True
print(not first_condition)  # False

Challenge

変数を使用してprint()で結果を出力してみる。
1.年齢が10以上かつ身長が110㎝以上なら乗れるアトラクション
2.修士号保持もしくは5年以上実務経験があればクレジットカードの審査をパスできる

1の解答例
# challenge1
age = 13
height = 140

print(age >= 10 and height >= 110)
2の解答例
# challenge2
master = False
job_experience = 6
print(master or job_experience >= 5)

# 左側の評価で結果がわかる場合は右側は評価されない
print(10 > 3 or undefined == 20)

▶if文

今まで学習した比較演算子や論理演算子を使用して条件を定義し、その結果によって処理を分岐させることができる。
基本的な構文は下記のようになっており、(条件)がTrueの際は処理1が実行され、Falseの場合は処理2が実行される。
他にも「elif」というもので条件を複数定義することもでき、処理の分岐を増やすことができる。

# 基本的な構文
if (条件):
    処理1
else:
    処理2

# elif
if (条件A):
    処理1
elif (条件B):
    処理2
else:
    処理3

※elseやelifは書かなくてもいい
notを使用して、条件がFalseの時にifのほうの処理を実行する書き方もできる。

# if not
age = int(input("how old are you?"))
if not 0 < age < 120:
    print("the value is invalid!")

Challenge

1.もし残高が引き出し額より大きければ、残高を更新し、そうでなければ引き出せないことを知らせるATM
2.Challenge1のATMに引出上限を100万に設定し、上限を超えての引出はできない機能を追加する

1の解答例
# challenge1
balance = 3000000
withdrawal = 23000

if balance > withdrawal:
    balance -= withdrawal
    print("Your new balance is {}".format(balance))
else:
    print("You don't have money.... do you? ")
2の解答例
# challenge2
withdrawal_limit = 1000000

if withdrawal > withdrawal_limit:
    print("The withdrawal limit is {}".format(withdrawal_limit))
elif balance > withdrawal:
    balance -= withdrawal
    print("Your new balance is {}".format(balance))
else:
    print("You don't have money.... do you? ")

# 別解:論理演算子を使ってもOK
if withdrawal < withdrawal_limit and balance > withdrawal:
    balance -= withdrawal
    print("Your new balance is {}".format(balance))
else:
    print("Withdrawal exceeds limit ({}) or balance ({})".format(withdrawal_limit, balance))

▶if文におけるNoneの扱い方

条件を(<変数> is None)というようにして、値が入っているかどうかの評価をすることができる。
他にもif文の条件は値が入っていればその時点でTrueとなる仕様なので、(not <変数>)とすることで、Noneの判定をすることもできる。

# if文のNoneの取り扱い
a = None
if a is None:
    print("a is None")
else:
    print("a has a value")

# notを使う
if not a:
    print("a is None")
else:
    print("a has a value")

▶input関数

ユーザーからの入力(文字列)を取得し、活用することができる関数。
関数の引数に設定した文字列を入力時に表示することができる。

# 「何歳ですか?:」という表示とともにユーザーの入力を受け付ける
age = input("何歳ですか?:") 
print("あなたは{}歳です.".format(age))

Challenge

  1. ユーザーに年齢を入力してもらい、18歳以上なら入場を許可するカジノを作成する。
  2. カジノに入ったらゲームを選べるようにする。(数や種類は自由)
    選択後は、ゲームの内容を出力する。
1の解答例
# challenge1
age = int(input("何歳ですか?:"))
casino_age = 18

if age >= casino_age:
    print("どうぞお入りください")
else:
    print("{}歳未満の方はカジノへは入れません!".format(casino_age))
2の解答例
# challenge2
age = int(input("何歳ですか?:"))
casino_age = 18
game_text = """プレイするゲームを選択してください. 
1: ルーレット
2: ブラックジャック 
3: ポーカー
:"""

if age >= casino_age:
    print("どうぞお入りください")
    game = input(game_text)
    if game == '1':
        print("あなたはルーレットを選びました")
    elif game == '2':
        print("あなたはブラックジャックを選びました")
    elif game == '3':
        print("あなたはポーカーを選びました")
    else:
        print("1~3を選んでください")
else:
    print("{}歳未満の方はカジノへは入れません!".format(casino_age))

▶リスト型(Lists)

変数では値を1つしか格納することができなかったが、List型では複数の値を格納することができる。
インデックスと呼ばれる0から始まる通し番号を割り振って、それぞれの値を識別して呼び出したり、値の上書きを行うことができる。
List型にもstr型同様に様々なBuilt in Functionが存在し、その関数を使用してList型内の値を管理する。

# リスト(lists): 複数のオブジェクトを順序づけて保存するデータ型
# []で括って,,(カンマ)で各オブジェクトを区切る
fruits = ['apple', 'peach', 'melon', 'grapes']

# 要素のデータ型はなんでもOK リストの中にリストを入れることも可能
hetero_list = ['string', 1, 3.4, True, fruits]

# 要素を取り出すときには[]の中にindexを指定する. indexは0から始める
print(fruits[0])

# indexに負の値を指定すると後ろから数えて要素を取得する
print(fruits[-1])

# 二重リスト(List型の中にList型が格納されている状態)の場合は,二度indexを指定すればOK (3重,4重も同じ)
print(hetero_list[-1][0]) # appleが出力される

# これらは文字列にも使える
print("hello world"[3])

# Built in function
# .append: 新しいオブジェクトを追加する
fruits.append('banana')

# + 演算子でリストを結合する
print([1, 2, 3] + [4, 5, 6]) # [1, 2, 3, 4, 5, 6]

# .insert: 指定したindexに指定したオブジェクトを追加する
fruits.insert(3, 'lemon')

# .remove: マッチした最初のオブジェクトを除く
fruits.remove('peach')

# .sort(): 昇順に並び替える
fruits.sort()

# 降順にする
fruits.sort(reverse=True)

# len(): リストの要素数を取得する
print(len(fruits))

# 文字列にも使用可能
print(len('hello world'))

▶Slicing

List型から複数の値を取り出す方法の一つ。
「:」を使用してインデックスの範囲を指定し、その範囲にある値を取り出すことができる。

even = [2, 4, 6, 8, 10, 12]
# 基本は[開始:未満]
print(even[1:4])

# 以下二つは同じ、開始が「0」の場合は省略できる
print(even[0:4])
print(even[:4])

# 以下二つは同じ、「5」はevenにおける最後のインデックスなので
print(even[3:5])
print(even[3:-1])

# ○○から最後の要素まで取得するときも省略可能
print(even[3:])

# 全ての要素を取得
print(even[:])

# 文字列にも同様
text = "hello world"
print(text[3:])

# [開始:未満:step]、[step]おきに値を取得、下記だと2文字おきに取ってくる。
print(text[2:10:2]) # lowrと出力される

# [::-1]とすると逆順になる
print(text[::-1])

▶joinとsplit

どちらとも文字列とList型を変換するような使い方をする。
・ join:リスト内の値(文字列)を結合する
・ split:文字列を任意の場所、文字で区切ってList型に格納する

# join " "を間に挟んでそれぞれの値を結合している
text = " ".join(['Hi', 'My', 'name', 'is', 'John'])

# split
splited_space = "Hi My name is John".split() # spaceで区切る
splited_slash = "Hi/My/name/is/John".split("/") # "/"で区切る

▶in演算子

List型の中に指定の要素があるかどうかを精査し、要素があればTrueなければFalseを返却する。
notを使用して要素がなければTrueを返却するようにすることもできる。

fruits = ['apple', 'peach', 'grapes', 'banana']
print('apple' in fruits) # appleがあればTrue
print('lemon' not in fruits) # lemonがなければTrue

Challenge

ユーザーに好きなフルーツを入力してもらい、そのフルーツがリストに存在すればそのフルーツをリストから削除し、なければリストに追加する。

解答例
# challenge
favorite = input("好きなフルーツはなんですか?")

if favorite in fruits:
    print("{}ですね.差し上げますよ".format(favorite))
    fruits.remove(favorite)
else:
    print("{}ですね.仕入れました!".format(favorite))
    fruits.append(favorite)

print("今あるフルーツはこちらです.{}".format(fruits))

▶forループ

List型の要素を一つずつ取り出して、その取り出した要素を活用して処理を繰り返すということもできる。
List型だけではなく、ほかにも使用できるオブ弱とは多数存在する。

fruits = ['apple', 'peach', 'grapes', 'banana']

# fruits内の要素を順番に取り出して、fruitという変数に格納して処理を繰り返す
for fruit in fruits:
    print("I love {}!!".format(fruit))

Challenge

  1. 好きなフルーツを入力してもらい、リスト内の各フルーツに対して「好き/好きじゃない」を出力する
  2. リスト内の各フルーツに対して「好き/好きじゃない」をユーザーに聞いて、好きじゃないリストを作成する
1の解答例
# Challenge1
favorite = input("好きなフルーツは?")
for fruit in fruits:
    if fruit == favorite:
        print("I love {}!!".format(favorite))
    else:
        print("{}は別に普通...".format(fruit))
2の解答例
#Challenge2
favorite_fruits = []
normal_fruits = []
for fruit in fruits:
    choice = input(f"{fruit}は好き? y/n")

    if choice == 'y':
        favorite_fruits.append(fruit)
    else:
        normal_fruits.append(fruit)

print(f"favorite fruits: {favorite_fruits}")
print(f"normal fruits: {normal_fruits}")

▶range

forループの数字の範囲を指定して、その指定した回数、もしくは数字を使用して処理を繰り返す。
開始、終了、間隔の3つを指定することができる。
ループは開始 ≦ 数字 < 終了の範囲で行われるので、range(1, 10)であれば、1~9の数字が使用される。

# range(開始, 終了, 間隔)
for i in range(10): # 0~9
    print(i)

for i in range(2, 5): # 2~4
    print(i)

for i in range(4, 13, 2): # 4, 6, 8, 10, 12
    print(i)

# 処理の中で数字を使わない場合はiを_とする
for _ in range(5):
    print("hello!")

Challenge

みんな大好きのFizzBuzz!!(15で割り切れるときはFizzBuzz、3で割り切れるときはFizz、5で割り切れるときはBuzzと出力する)

解答例
# Challenge
for i in range(1, 51):
    if i % 15 == 0:
        print('FizzBuzz')
    elif i % 3 == 0:
        print('Fizz')
    elif i % 5 == 0:
        print('Buzz')
    else:
        print(i)

▶whileループ

ある条件を設定し、その条件がTrueの間は処理を繰り返す。
forループでも使用することができるが、continuebreakでループを飛ばしたり、強制終了させることができる。
・continue:そのループの以降の処理をすべてスキップして、次のループを開始する。
・break:条件がTure/False関係なく、ループ処理を終了する。

count = 0
# countが10未満の間は処理を繰り返す
while count < 10:
    print(count)
    count += 1

# break と continue
while True:
    age = int(input("あなたは何歳ですか?"))
    if not 0 < age < 120:
        print("入力された値が正しくありません")
        continue
    else:
        print(f"あなたは{age}歳です")
        break

Challenge

input関数のchallenge2の解答例を1~3以外の文字が入力された場合、再度ゲームを選択できるように修正する。

解答例
# challenge
age = int(input("何歳ですか?:"))
casino_age = 18
game_text = """プレイするゲームを選択してください. 
1: ルーレット
2: ブラックジャック 
3: ポーカー
:"""

if age >= casino_age:
    print("どうぞお入りください")
    while True:
        game = input(game_text)
        if game == '1':
            print("あなたはルーレットを選びました")
            break
        elif game == '2':
            print("あなたはブラックジャックを選びました")
            break
        elif game == '3':
            print("あなたはポーカーを選びました")
            break
        else:
            print("1~3を選んでください")
else:
    print(f"{casino_age}歳未満の方はカジノへは入れません!")

▶ループ文でのelse

forループやwhileループにもelseを使用することができ、それぞれループの最後や条件がFalseになった際に実行したい処理を記述することができる。

fruits = ['apple', 'peach', 'grapes', 'banana']

# for文の場合 else:はfor文が回り切ったら実行
for fruit in fruits:
    choice = input(f"あなたが探しているフルーツは{fruit}ですか? y/n:")
    if choice == 'y':
        print("見つかってよかったですね")
        break
    else:
        print("そうですか...")
else:
    print("お探しのフルーツは見つかりませんでした.")

# while文の場合 else:は条件がFalseになったら実行
balance = 1000
game_price = 200
while balance >= game_price:
    choice = input(f"1回{game_price}円のゲームに参加しますか?(残高{balance}円)(y/n):")
    if choice == 'y':
        balance -= game_price
    elif choice == 'n':
        print("また遊びましょう")
        break
    else:
        print("yかnで答えてください")
else:
    print(f"あなたの残高は{balance}円です.もうお金なくなっちゃいましたね^^;")

▶enumerate

List型をfor文でループする際に、要素だけではなくインデックスも取り出して扱うことができる。
細かく言うとList型をtuple型(後述)といわれる別のオブジェクトとして取り出しており、そのオブジェクトに対して要素とインデックスを取り出す操作を行っている。

fruits = ['apple', 'peach', 'grapes', 'banana']

# インデックスはidw、要素はfruitに格納される
for idx, fruit in enumerate(fruits):
    print(f"index: {idx}, fruit: {fruit}")

for x in enumerate(fruits):
    # xはtuple型
    print(x) # ('apple', 'peach', 'grapes', 'banana')

▶リスト内包表記(List Comprehension)

List型オブジェクトの定義とforループによる処理を同時に行うことができる書き方。
range()で処理回数を指定したり、if文でフィルターをかけることもできる。

# リスト内包表記を使わない書き方
square_list = []
for i in range(10):
    square_list.append(i ** 2)

# リスト内包表記を使った書き方
square_list = [i ** 2 for i in range(10)]
print(square_list)

# if文を後ろにつけることでフィルタすることが可能
even_square_list = [i ** 2 for i in range(10) if i % 2 == 0]
print(even_square_list)

▶tuple型

List型と同じように複数の要素を格納できるオブジェクトとなっているが、tuple型は格納した要素を後から変更することができない。
変更されたくない要素を格納するのにも使えるが、基本的には変更する必要がない要素を格納するのに使用する。

# tuple (タプル):[]ではなく()を使う
date_of_birth = (1990, 2, 3)

# unpack:tuple内の要素を順番に変数に格納する(enumurateで行われているのはこれ)
year, month, day = date_of_birth
print(year)
print(month)
print(day)

# リスト同様にindexで値を取得できる
print(date_of_birth[0])
print(date_of_birth[-1])
print(date_of_birth[1:])

▶辞書型(dictionaries)

今までのList型やtuple型は0から始まるインデックスでそれぞれの要素を順番に管理していたが、辞書型はそのインデックスがキー(key:任意のオブジェクト)に置き換わったもの。
キーと要素(value)は1対1で対応しており、同じキーで複数のvalueを管理することはできない。
辞書型にもBuilt in Functionが用意されており、.keys() .values() .items() .get() .update()などがある。

# dictionary: キーと値の組み合わせを複数保持するデータ型
fruits_colors = {'apple': 'red', 'lemon': 'yellow', 'grapes': 'purple'}

# []にキーを指定して値を取得する
fruit_key = 'apple'
print(f"{fruit_key} is {fruits_colors[fruit_key]}")

# []にキーを指定して値を更新する(なければ作成)
fruits_colors['peach'] = 'pink'
print(fruits_colors)

# キーと値にはオブジェクトが入る.どんなオブジェクトでも入れることが可能
dict_sample = {1: 'one', 'two': 2, 'three': [1, 2, 3], 'four': {'inner': 'dict'}}
print(dict_sample)

# nested dictionaryも同様に値を取得
print(dict_sample['four']['inner']) # 'dict'が出力される

# dictionaryにオーダー(順序)はない
colors = {}
colors[1] = 'blue'
colors[0] = 'red'
colors[2] = 'green'
print(colors) # 格納された順番で保持する

# in演算子 を使って,キーが存在するかを確認することができる
if 'peach' in fruits_colors:
    print(fruits_colors['peach'])
else:
    print("the key is not found")

# .keys():辞書型のキーを順番に取り出す
for fruit in fruits_colors.keys():
    print(f'{fruit} is {fruits_colors[fruit]}')

# .values():辞書型の値を順番に取り出す
for color in fruits_colors.values():
    # 基本的に値からキーを取得するのにdictionaryは使えないので,colorだけprint()しておく
    print(color)

# そのままforで回すとkeyがxに入る
for x in fruits_colors:
    print(x)

# .items():キーと値を順番に取り出す
for fruit, color in fruits_colors.items():
    print(f'{fruit} is {color}')

# 指定したキーが存在しない場合エラーとなってしまうので、.get()を使うのが良い
# print(fruits_colors['peach']) ⇐ キーが存在しないのでエラーになる
fruit = input("フルーツの名前を指定してください")
print(fruits_colors.get(fruit, 'Nothing')) # キーがなければ、第2引数の値(デフォルトはNone)が返却される

# .update():辞書型のオブジェクトを結合する
fruits_colors2 = {'peach': 'pink', 'kiwi': 'green'}
fruits_colors.update(fruits_colors2)
print(fruits_colors)

Challenge

whileループのChallengeの解答例を下記点に留意してリファクタリングする。
・プレイできるゲームについてのハードコーディングを解消する。
・ゲームを後から追加しても問題なくシステムが動くようにする。

解答例
age = int(input("何歳ですか?:"))
casino_age = 18

game_dict = {'1': 'ルーレット', '2': 'ブラックジャック', '3': 'ポーカー'}

if age >= casino_age:
    print("どうぞお入りください")
    while True:
        print("プレイするゲームを選択してください")
        for num, game_name in game_dict.items():
            print(f"{num}: {game_name}")
        game = input(":")
        if game in game_dict:
            print(f"あなたは{game_dict[game]}を選びました")
            break
        else:
            print("正しい番号を選んでください")
else:
    print(f"{casino_age}歳未満の方はカジノへは入れません!")

▶セット型(sets)

重複要素を含まないリストでリストのようにインデックスを持たないので、インデックスを指定しての取り出しができない。
もし定義する際に同じ値を複数入れたとしても、1つしか格納されない。

fruits = {'apple', 'peach', 'lemon', 'grapes', 'apple'}
# 重複せずに保持
print(fruits)
# オーダーを保持しないので,indexを指定して値を取得することはできない
# print(fruits[0])

# len()で要素数を所得できる
print(len(fruits))

▶型変換(Casting)

str型をint型にしたり、ある型を別の方に変換する関数。
もちろん元の値が変換後の型に対応した形である必要がある。

# strings:'1'
# int:1
# float:1.0
# boolean:True, False
# list:[1, 2, 3, 4, 5]
# tuple:(1, 2, 3)
# dictionary:{"one": 1, "two": 2, "three": 3}
# set:{1, 2, 3, 4, 5}

# Casting: 型変換
# str(), int(), float(), list(), bool(), tuple(), set()
str(1)  # -> "1"
int("1")  # -> 1
float("1")  # -> 1.0
list("hello")  # -> ['h', 'e', 'l', 'l', 'o']
bool(1)  # -> True
bool("1")  # -> True
bool(0)  # -> False
tuple([1, 2, 3, 4])  # -> (1, 2, 3, 4)
set([1, 2, 3, 3, 4, 4, 5])  # -> {1, 2, 3, 4, 5}

次の記事

Python初心者の備忘録 #02

2
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
5