LoginSignup
4
4

Python基礎(if文、for文、リスト内包表記)

Last updated at Posted at 2024-05-21

Pythonで基本的な文法を紹介していくよ~。
今回は、if文、for文、リスト内包表記の3つを書いていくよ。

if文の使い方

pythonはインデントが重要で、if文ならifの中身で処理させたい内容はインデントを1つ下げて書くよ。

if 条件式:
    処理1
処理2

使用例
20歳以下なら、「閲覧権限がありません。」と表示させる。

print("年齢チェック")
age = 19
if age < 20:
    print("閲覧権限がありません。")
print("年齢チェック終了")

# 出力結果
> 年齢チェック
> 閲覧権限がありません
> 年齢チェック終了

for文の使い方

Javaの拡張for文のイメージに近いよ。

for 任意の変数名 in イテラブルオブジェクト

使用例
辞書型のリストから1つずつ取り出し、プリントする。

list = [{"id": 1, "name": "apple"}, {"id": 2, "name": "grape"}, {"id": 3, "name": "peach"}]
for i in list:
    print(i)

# 出力結果
> {"id": 1, "name": "apple"}
> {"id": 2, "name": "grape"}
> {"id": 3, "name": "peach"}

リスト内包表記の基本

リスト内包表記の基本型

[ for 任意の変数名 in イテラブルオブジェクト]

使用例
0~5の数字の2乗を計算し、プリントする。

squared = [i**2 for i in range(6)]
print(squared)

# 出力結果
> [0, 1, 4, 9, 16]

結果をifで分岐させる

[ for 任意の変数名 in イテラブルオブジェクト if 条件式]

使用例
0~5の数字の2乗を計算したうち、奇数だけを取り出し、プリントする。

squared = [i**2 for i in range(6) if i % 2 == 1]
print(squared)

# 出力結果
> [1, 9, 25]
おまけ

辞書型のリストから、任意の値を取り出す。

list = [{"id": 1, "name": "apple"}, {"id": 2, "name": "grape"}, {"id": 3, "name": "peach"}]

# リストから、id=1の場合のnameを取り出す。
get_name = [i["name"] for i in list if i["id"] == 1]
print(get_name)

# 出力結果
> ['apple']

今回はpythonの基本構文を紹介したよ。
リスト内包表記は少し難しい。。。

4
4
2

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
4
4