LoginSignup
0
1

More than 1 year has passed since last update.

【python】超基礎

Last updated at Posted at 2021-09-20

変数

変数は値を入れておく箱と思ってください。

test_str: str = "test"
test_int: int = 10

test_strという箱に「test」という文字列が入りました。
test_intという箱に「10」という数値が入りました。
文字列は必ずダブルクォーテーションて囲むことが鉄則です。

型という概念があり、今回だとtest_strは文字型、test_intはint型になります。
その他にもリスト型や辞書型などもありますが、おいおいやります。

リスト型

names: list = ["田中", "鈴木", "田代"]
numbers: list = [1, 3, 100]

辞書型

こちらはリスト型のパワーアップバージョンで、キーとバリューで成り立っています。

# "キー": "バリュー"
test_dict: dict = { "田中": 76, "鈴木": 80, "田代": 30 }

上記は、キーが名前でバリューが点数という例です。

if文

もし~だったら~
そのままですね。

test_str: str = "test"

if test_str == "test":
    print("同じ")
else:
    print("違う")

もしtest_str"test"が等しければ「同じ」と表示する。
でなければ、「違う」と表示する。

test_int = 10

if test_int == 10:
    print("test_intは10(等しい)")
elif test_int <= 10:
    print("test_intは10以下")
elif test_int >= 10:
    print("test_intは10以上")

test_intが10と等しければ「test_intは10(等しい)」と表示。
test_intが10以下なら「test_intは10以下」と表示。
test_intは10以上なら「test_intは10以上」と表示。

インデントに注意しましょう!

if test_int == 10:
print("test_intは10(等しい)")

この場合だとprint文はifの中に入っていません。(ネストされていない)
処理が別々になります。
if文の中の処理はなく、print文は必ず表示される状態になってしまっています。

for文(繰り返し処理)

for count in range(5):
    print(count)

こちらは5回繰り返し処理が走ります。
countの中身は0~4までカウントアップされます。
実行結果はこちらになります。

0
1
2
3
4

リスト型をfor文で回す

heroes: list = ["アンパンマン", "さいたま", "キング", "ジェノス"]

for hero in heroes:
    print(hero)

heroesの中身を順にheroに代入して回します。
実行結果はこちらになります。

アンパンマン
さいたま
キング
ジェノス

関数

def show_heroes(heroes: list) -> None:
    for hero in heroes:
        print(hero)


heroes: list = ["アンパンマン", "さいたま", "キング", "ジェノス"]
show_heroes(heroes)

def show_heroes(heroes: list) -> None:こちらが関数になります。
一番下のshow_heroes(heroes)がshow_heroes関数を呼び出しています。
()の中のheroesを引数と言います。
heroesをshow_heroes関数に渡しています。
-> Noneについては返り値がないという意味です。
返り値については次で説明します。

返り値

def squared(test_int: int) -> int:
    squared_int: int = test_int * test_int
    return squared_int


test_int: int = 8
test_2int: int = squared(test_int)
print(test_2int)

こちらはtest_intに8を代入して、squared関数で2乗した値を返してtest_2intに代入しています。
return squared_intsquared_intの値を返すという意味です。
int型を返しているので-> intとしています。

image.png

アノテーション

アノテーションとは、変数代入のときの、

test_int: int = 8

:intの部分になります。

あと、先程の

def squared(test_int: int) -> int:

-> intの部分になります。
本当はこれがなくてもプログラム上では動きます。

なぜアノテーションをつけるかというと、変数ではすぐなんの型かがわかりあとあと、メンテナンス性がいいからです。

def squared(test_int: int) -> int:

こちらも関数の中身を全部見なくても引数がint型が渡ってきていて、返り値がint型であることが一行だけみればわかります。

def squared(test):

アノテーションがない場合、testの中身はなんなのか関数の中処理を見ないとわからないし、返り値の型又は返り値があるかないかなど全くわかりません。

これじゃあ、あとあと修正するときが大変ですよね?

ということでアノテーションはつけましょう!というお話です。

0
1
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
0
1