LoginSignup

This article is a Private article. Only a writer and users who know the URL can access it.
Please change open range to public in publish setting if you want to share this article with other users.

More than 3 years have passed since last update.

Python練習問題2 回答編

Last updated at Posted at 2019-11-19

練習問題2回答

while True:
    try:
        time = int(input("何時ですか?(0〜24): "))
    except:
        continue
    if 0 <= time <= 24:
        break

if  5 <= time <= 10:
    print("おはよう")
elif 11 <= time <= 18:
    print("こんにちわ")
else:
    print("こんばんわ")

解説

  1. while文と if文でbreakを使って で0から24以外の数字を入力された際に繰り返す処理を行う
  2. try exceptのエラー処理で数字以外が入力された場合の処理を入れる
  3. inputされた数値は、そのあとのif文で数値比較するためにintに変換する
  4. inputされ、数値変換した情報を time(変数名はなんでも良い)に代入する
  5. if文を条件に合わせて記載する
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