MENU

4-02 条件分岐と入力処理

学習目標

  • input()関数を使ってユーザーから入力を受け取れる
  • if文、elif、elseを使った条件分岐ができる
  • 比較演算子と論理演算子を理解する
  • 実際のプログラムで条件分岐を活用できる

前回の復習

前回学んだ内容を簡単に確認しましょう:

# Variables and data types
name = "Yamada Hanako"     # string
age = 17                   # integer
height = 160.5             # float

# Basic calculation
total = 100 + 50
print("Total:", total)

復習問題:自分の名前、年齢、身長を変数に入れて表示してみよう


1. ユーザーからの入力を受け取る

今まではプログラムの中で値を決めていましたが、実行時にユーザーから値を入力してもらうことができます。

ファイルを使った実行方法

PythonAnywhereでは、複数行のコードを実行する時はファイルを作ると便利です:

  1. Filesタブをクリック
  2. New fileで新しいファイルを作成
  3. ファイル名を「lesson2.py」などにする
  4. コードを書いてファイルを保存(Ctrl+S または Cmd+S)
  5. RUNボタンを押して実行

⚠️ 重要な注意点

  • 無料版では同時に2個以上のコンソールを実行できません
  • 前回の授業でコンソールが残っている場合は、Consolesタブで古いコンソールをDeleteしてから新しいファイルを実行してください
  • エラーが出た場合は、不要なコンソールを削除してから再実行しましょう

input()関数の基本

# Get input from user
name = input("Please enter your name: ")
print("Hello, " + name + "!")

💡 PythonAnywhereでの実行方法

  • 方法1:上のコードをまとめてコピー&ペーストして実行
  • 方法2:ファイルに保存して実行(後で説明します)
  • 注意input()の行だけを実行すると入力待ちで止まってしまいます

実習1:上のコードをまとめてコピー&ペーストして実行し、自分の名前を入力してみよう

数値の入力

input()関数は常に文字列として値を受け取ります。数値として使いたい場合は変換が必要です。

# Receive as string
age_str = input("Please enter your age: ")
print("Input value:", age_str, "(Data type:", type(age_str), ")")

# Convert to number
age = int(age_str)
print("Converted value:", age, "(Data type:", type(age), ")")

# Check difference with calculation
print("String calculation:", age_str + age_str)  # String concatenation
print("Number calculation:", age + age)          # Number addition
# Writing in one line
age = int(input("Please enter your age: "))
print("You are", age, "years old (Data type:", type(age), ")")

💡 type()関数:変数のデータ型を確認できる便利な関数です

小数の入力

height = float(input("Please enter your height (cm): "))
print("Your height is", height, "cm")

実習2:年齢と身長を入力して表示するプログラムを作ってみよう


2. 条件分岐の基本(if文)

条件によって処理を変えることができます。これを条件分岐と呼びます。

Python ではインデントがとても重要!

Python では、ifelse の中で実行される処理を インデント(字下げ)で表します。
これは、他の言語で { } を使う代わりに、インデントでブロック(処理のまとまり)を示す仕組みになっているためです。

  • インデントは 半角スペース4つ が一般的(推奨)
  • ブロックの中の行は 同じ幅でインデント する
  • ブロックが終わると インデントを戻す(左端に戻る)

これを守らないと IndentationError(インデントエラー)になります。

基本的なif文

age = int(input("Please enter your age: "))

if age >= 18:
    print("You are an adult")

条件式の終わりには:を必ずつけます。

if-else文

age = int(input("Please enter your age: "))

if age >= 18:
    print("You are an adult")
else:
    print("You are a minor")

実習3:上のコードを実行して、いろいろな年齢を入力してみよう

実習4:インデントを少し変えてみるとどうなるだろうか?やってみよう


3. 比較演算子

条件を作るために使う記号を比較演算子と呼びます。

条件は、「A 比較演算子 B」という形になっています。

演算子意味結果
==等しい5 == 5True
!=等しくない5 != 3True
>より大きい7 > 3True
<より小さい2 < 8True
>=以上5 >= 5True
<=以下3 <= 7True

>=<=左が不等号で右が等号。順番を間違えないように

比較演算子の例

score = int(input("Please enter your test score: "))

if score == 100:
    print("Perfect score! Excellent!")
elif score >= 80:
    print("Great job!")
elif score >= 60:
    print("You passed")
else:
    print("Please try harder")

実習4:上のプログラムを実行して、色々な点数を入力してみよう


4. 複数条件の分岐(elif)

elifを使うと、複数の条件を順番にチェックできます。

elif = else + if

weather = input("Please enter today's weather (sunny/cloudy/rainy/snowy): ")

if weather == "sunny":
    print("Let's hang the laundry outside!")
elif weather == "cloudy":
    print("You might want to bring an umbrella")
elif weather == "rainy":
    print("Don't forget your umbrella!")
elif weather == "snowy":
    print("Dress warmly when you go out")
else:
    print("I don't understand the weather")

実習5:天気予報プログラムを実行してみよう


5. 論理演算子

複数の条件を組み合わせることができます。

演算子意味
andかつ(両方とも真)age >= 18 and age < 65
orまたは(どちらか真)day == "土曜日" or day == "日曜日"
not否定(真偽を逆転)not (score < 60)

条件は3つ一度に組み合わせることもできる。
A and B and C とすると、3つの条件A,B,Cの全てを満たす必要があり、
A or B or C とすると、3つの条件A,B,Cのいずれかを満たせば良い。

論理演算子の例

age = int(input("Please enter your age: "))
student = input("Are you a student? (yes/no): ")

if age < 18 and student == "yes":
    print("Student discount applies")
elif age >= 65:
    print("Senior discount applies")
elif student == "yes":
    print("Student discount applies")
else:
    print("Regular price")

実習6:割引判定プログラムを実行してみよう


6. 実践的な条件分岐

例1:BMI計算と判定

print("=== BMI Calculator ===")
height = float(input("Please enter your height (m): "))
weight = float(input("Please enter your weight (kg): "))

bmi = weight / (height * height)
print("Your BMI is", round(bmi, 1))

if bmi < 18.5:
    print("Underweight")
elif bmi < 25:
    print("Normal weight")
elif bmi < 30:
    print("Overweight")
else:
    print("Obese")

例2:じゃんけんゲーム

import random

print("=== Rock Paper Scissors Game ===")
user = input("Please enter your choice (rock/scissors/paper): ")

# Computer chooses randomly
choices = ["rock", "scissors", "paper"]
computer = random.choice(choices)

print("Computer:", computer)
print("You:", user)

if user == computer:
    print("It's a tie")
elif (user == "rock" and computer == "scissors") or \
     (user == "scissors" and computer == "paper") or \
     (user == "paper" and computer == "rock"):
    print("You win!")
else:
    print("Computer wins")

実習7:BMI計算プログラムまたはじゃんけんゲームを実行してみよう


7. エラーへの対処

ユーザーが予想外の入力をした場合の対処法を学びましょう。

try文とは

try文は、エラーが発生する可能性のあるコードを安全に実行するための仕組みです。

基本的な構文:

try:
    # Code that may cause errors
    risky_code()
except ErrorType:
    # Handling when an error occurs
    handle_error()

数値入力のエラー対処

try:
    age = int(input("Please enter your age: "))
    print("You are", age, "years old")
except ValueError:
    print("Please enter a number")

実習8:文字を入力してエラー処理を確認してみよう


7. 文字列の長さを調べる

プログラムでは文字列の長さ(文字数)を調べることがよくあります。

# Check string length with len() function
name = input("Please enter your name: ")
print("Number of characters in name:", len(name))

if len(name) <= 2:
    print("Short name")
elif len(name) <= 4:
    print("Good length name")
else:
    print("Long name")

実習9:上のプログラムを実行して、いろいろな名前を入力してみよう


8. 課題

課題1:成績判定プログラム

5教科の点数を入力して、平均点を計算し、以下の基準で判定するプログラムを作ってください:

  • 90点以上:優秀
  • 80点以上:良好
  • 70点以上:合格
  • 70点未満:不可

課題2:料金計算プログラム

映画館の料金計算プログラムを作ってください:

  • 大人(18歳以上):1800円
  • 高校生(15-17歳):1000円
  • 中学生以下(14歳以下):800円
  • シニア(65歳以上):1200円 年齢を入力すると料金を表示する

課題3:パスワード判定プログラム

パスワードの強度を判定するプログラムを作ってください:

  • 8文字以上:「強い」
  • 5文字以上8文字未満:「普通」
  • 5文字未満:「弱い」

💡 ヒント:文字数を数えるにはlen()関数を使います

# Example of checking character count
password = "abc123"
print("Password length:", len(password))  # Result: 6

発展課題:診断ゲーム

好きな色、好きな動物、好きな食べ物を入力すると、性格を診断するゲームを作ってみてください(診断結果は自由に考えてOK)。


まとめ

今日学んだこと:

  • input()関数でユーザー入力を受け取る
  • int()float()での型変換
  • ifelifelseを使った条件分岐
  • 比較演算子(==, !=, >, <, >=, <=)
  • 論理演算子(and, or, not)
  • エラー処理の基本(try-except)

次回は、繰り返し処理(for文、while文)について学習します。

宿題:課題1〜3を完成させ、可能であれば発展課題にもチャレンジしてみましょう。

コメント

コメントする