2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Pythonのinput関数で再入力を促す方法

Last updated at Posted at 2021-02-17

if〜elseとwhileで書いてみた

if〜elseの場合

Input関数を使って外部入力を設定した際に、数値以外が入力された場合に再入力を促す方法です。if〜elseを使い数値以外の場合はreturnで関数を再実行するやり方にしてみました。Trueの時はreturnで入力値が戻るので再利用が可能です。

以下、環境です。
OS : macOSX Catalina 10.15.7
Python : python3.9.1 (pyenv)

# 例:予算入力時に数字だけを入力してもらう (budget_input.py)

def budget_input():                                 #関数budget_inputを定義
    figure = input('ご予算を入力してください : ')   #input関数で入力された値を変数figureに代入
    if figure.isdigit():                            #.isdigit()で数値かどうかを判定
        budget = int(figure)                        #True(真):の場合は、intで数値化
        return budget                               #budget値を数値として返す (後で計算に使える)
    else:
        print('整数値を入力してください : ')        #False(偽)の場合は、再入力を促す表示をする実行し
        return budget_input()                       #関数budget_inputを再実行する。

input_budget = budget_input()
add_bounas_budget = input_budget * 1.05
print('入力されたご予算は' + str(input_budget) + 'になります。')
print('ポイントがご予算の5%分加算され合計で' + str(round(add_bounas_budget)) + '円になります。')
# 出力結果:10000と入力

ご予算をご入力してください :10000
入力されたご予算は10000円になります。
ポイントがご予算の5%分加算され合計で10500円になります。

whileの場合

def budget_input():                                    #関数budget_inputを定義
    while True:                                        #Trueの間は繰り返す
        number = input('ご予算をご入力してください:')  #input関数で入力された値を変数numberに代入
        if number.isdigit():                           #.isdigit()で数値かどうかを判定
            budget = int(number)                       #True(真):の場合は、intで数値
            return budget                              #budget値を数値として返す (後で計算に使える)
            break                                      #breadkでループを終了
        print('整数値を入力して下さい。')


input_budget = budget_input()
add_bounas_budget = input_budget * 1.05
print('入力されたご予算は' + str(input_budget) + '円になります。')
print('ポイントがご予算の5%分加算され合計で' + str(round(add_bounas_budget)) + '円になります。')
# 結果はif〜elseと同じ
# 出力結果:10000と入力

ご予算をご入力してください :10000
入力されたご予算は10000円になります。
ポイントがご予算の5%分加算され合計で10500円になります。
2
0
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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?