2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Python入門 第3章】if文・for文で“考えるプログラム”を書こう🐍🧠

Posted at

こんにちは、 PythonTimesの蛇ノ目いろは です🌿
今回は「条件分岐」と「くり返し処理」について、やさしく解説していくよっ!


🧠 if文:条件によって処理を分ける!

「もし〇〇なら~する」っていうときに使うのが if 文!

score = 80

if score >= 70:
    print("合格です!")
else:
    print("残念、不合格…")

📝 elif を使えば「それ以外の条件」も追加できるよ👇

if score >= 90:
    print("とても優秀!")
elif score >= 70:
    print("合格!")
else:
    print("再チャレンジしよう!")

📌 ポイント

  • : を忘れずに!
  • インデント(スペース4つ)が「処理の範囲」を表すよ

🔁 for文:決まった回数くり返す

リストなどの データを1つずつ取り出す ときに使うのが for 文!

fruits = ["りんご", "みかん", "バナナ"]

for fruit in fruits:
    print(fruit)
りんご  
みかん  
バナナ

range() と組み合わせて数値ループもできる!

for number in range(5):
    print(number)
0  
1  
2  
3  
4

🔁 while文:条件がTrueの間くり返す

「〜になるまで続けたい」処理には while が便利!

count = 0

while count < 3:
    print("回数:", count)
    count += 1

⛔ break / continue

  • break:ループを強制終了!
  • continue:スキップして次のループへ!
for number in range(5):
    if number == 3:
        break
    print(number)

✍️ Pythonの命名スタイル(PEP8)

Pythonでは「読みやすく、わかりやすいコード」を大切にしていて、
PEP8(公式スタイルガイド) という命名ルールがあるよ🐍

種類 書き方ルール
変数名 小文字+アンダースコア(snake_case) user_name, total_score
関数名 同上(snake_case) get_data(), send_mail()
クラス名 単語の先頭だけ大文字(PascalCase) UserInfo, MyClass
定数 全部大文字+アンダースコア MAX_SIZE, PI

📝 ループ変数も意味ある名前で書こう!

# 悪い例(意味がわかりにくい)
for x in data:
    print(x)

# 良い例(何を処理しているか明確)
for user_name in user_names:
    print(user_name)

📌 まとめ

  • if で条件分岐、forwhile でくり返し処理が書ける!
  • range() を使えば数字のループが簡単✨
  • breakcontinue でループを制御!
  • 命名スタイル(PEP8)を守ると、 読みやすいコード になるよ🐍

次回は、
「第4章:関数とモジュール」 をお届け予定🎁
コードをキレイに整理して、再利用できるようにしよう!

フォローしてくれたら嬉しいな🐍🌸

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?