2017-09-24 4 views
0

家を買うためのいくつかの値を計算するコードを作成しています。ユーザーに多くの入力を要求し、非整数を入力した場合にプログラムが整数を要求していることを確認したい。 PythonでValueError入力を評価することはできますか?

Iは入力が整数であるかどうかをチェックする機能を作ったが、インタプリタは値のみエラーIを入力する場合、文字列を返します。入力した後に文字列を整数チェック関数で実行することは可能ですか?

var=True 

print('Welcome to the interest calculator program.') 

def integer_check(input): 
    try: 
     return True 
    except ValueError: 
     return False 

while var==True: 
    num=int(input('Enter the price of your dream house: \n')) 
    if integer_check(num)==True: 
     if num>=0: 
      print('yay') 
     elif num<=0: 
      print('House price must be a positive number only. Please try again.') 
    elif integer_check(num)==False: 
     print("Sorry, that's not a number. Please try again.") 
+0

「integer_check」の正しいバージョンが含まれていますか?このバージョンは常に 'True'を返すように見えます。 –

+0

[例外の処理](https://docs.python.org/3/tutorial/errors.html#handling-exceptions) – wwii

答えて

1

サラウンドtry .. except ..周りint(..)コール。入力文字列が整数文字列でなかった場合は、制御フローが届かないのでint()呼び出しの戻り値に対してチェックする、例外が発生したら意味がありません。

try: 
    num = int(input('Enter the price of your dream house: \n')) 
except ValueError: 
    # Non-integer 
else: 
    # Integer 

関数に文字列を渡して、関数がint型に変換しようとする必要があります

print('Welcome to the interest calculator program.') 

def integer_check(s): 
    try: 
     int(s) 
     return True 
    except ValueError: 
     return False 
    return True 

while True: 
    num = input('Enter the price of your dream house: \n') 
    if integer_check(num): 
     num = int(num) 
     if num >= 0: 
      print('yay') 
      break 
     else: # Use else 
      print('House price must be a positive number only. Please try again.') 
    else: # No need to call integer_check(..) again 
     print("Sorry, that's not a number. Please try again.") 
0

あなたはキャストを入力することができます:あなたが唯一持っているので、また、

def integer_check(i): 
    try: 
     int(i) # will successfully execute if of type integer 
     return True 
    except ValueError: # otherwise return False 
     return False 

を合格/あなたのメインプログラムで条件を失敗し、変更:

if integer_check(num)==True: 
    ... 
elif integer_check(num)==False: 
    ... 

to:

if integer_check(num): 
    ... 
else: 
    ... 
関連する問題