2016-05-29 4 views
0

私は合計でnoobですので、よろしくお願いします。私は自分のプログラムで整数入力を受け付けることができません。彼らはすべて文字列として出てくる。これを確認するには、現在コメントアウトされているtype()行を追加します。私のプログラムで入力を整数として受け入れるにはどうすればいいですか?ありがとう。数値が入力されていても、Python 3.xの文字列にデフォルトで入力する

あなたはint型に文字列を変換する必要があり
# TIP CALCULATOR 


def main(): 

    cost = input('Please enter the cost of your meal or service.') 
    tip_percentage = input('Please enter what percentage of tip you would like to pay.') 
    #print(type(cost)) 
    #print(type(tip_percentage)) 
    total = tip_percentage * cost + cost 
    return total 


final = main() 
print(final) 

答えて

0

input()機能は、実際にはファイルオブジェクトで、文字列を返すstdinから入力を読み取ります。整数型で入力する場合は、int()関数を使用して、文字列の数字を整数に変換することができます。ただし、ValueErrorを処理するには、try-except式でラップしてください(ユーザーが数字以外のものを入力した場合)。

try: 
    tip_percentage = input('Please enter what percentage of tip you would like to pay.') 
except ValueError: 
    tip_percentage = input('Please enter a valid digit') 
else: 
    # do something with tip_percentage 

そして、あなたは、ユーザーがあなたが真の条件とwhileループで、前のスニペットを入れて、elseセクションでループを破ることができる有効な整数を入力するまで、これを実行したい場合。

0

cost = int(input('Please enter the cost of your meal or service.')) 
関連する問題