2017-07-02 11 views
2

私は初心者でもPythonでのプログラミングでもあり、私は現在コードアカデミーを使って学習しています。だから、自分でプログラムを作り、自分自身でプログラムを作って、エラーメッセージにこだわることにしました:タイプ 'float'のnon-intでシーケンスを掛けることはできませんエラーメッセージが表示され続ける:「float型」の非int型シーケンスを掛けることはできません

プログラムはとてもシンプルです。ユーザに情報を入力して、プログラムにチップの量と総額を決定させるように要求する。そして、それは数学のポイントまでは大丈夫です。私はそれが "きれい"ではないことを知っていますが、私は本当にそれを動作させる方法を理解しようとしています。どんな助けでも大歓迎です!

print ("Restuarant Bill Calculator") 
print ("Instructions: Please use only dollar amount with decimal.") 

# ask the user to input the total of the bill 
original = raw_input ('What was the total of your bill?:') 
cost = original 
print (cost) 

# ask the user to put in how much tip they want to give 
tip = input('How much percent of tip in decimal:') 
tipamt = tip * cost  
print "%.2f" % tipamt 

# doing the math 
totalamt = cost + tipamt 
print (totalamt) 
+2

エラーの完全なエラーメッセージを追加してください。より一般的には、[mcve]と[ask]をお読みください。 (あなたはたぶん文字列に浮動小数点を乗算しようとしています) –

答えて

1

それはあなたのコードから、あなたはpython2を使用しているようだ:ここで

は、私がこれまで持っているものです。 Python2では、ユーザ入力を受け取る関数は raw_inputです。自動的に evalになると、 dangerousであるので、python2でユーザーデータを受け入れるときに input関数を使用しないでください。

ヘッドアップ:python3では、関数はinputであり、raw_inputはありません。

元の問題では、文字列として返されるので、入力関数が返す値を型キャストする必要があります。

だから、あなたが必要があると思います:

... 
cost = float(original) 
... 
tip = float(raw_input('How much percent of tip in decimal:')) 
tipamt = tip * cost 
... 

そして、これは動作するはずです。

+1

ハスキーちょっと時間: –

+0

"* python3では、関数が入力されていて、raw_inputはありません。質問、それじゃない? –

+0

@AndrasDeakハハ、ポストが書かれているので、思考プロセスは進化する傾向があります。 –

0

あなたはフロートにSTRを変換するのを忘れ:

original = raw_input('What was the total of your bill?:') 
cost = float(original) 
print (cost) 

#ask the user to put in how much tip they want to give 
tip = input('How much percent of tip in decimal:') 
tipamt = tip * cost  
print("%.2f" % tipamt) 

#doing the math 
totalamt = cost + tipamt 
print (totalamt) 
0

あなたの問題は、あなたがraw_input()と混合input()を使用していることです。これは、初心者にとってよくある間違いです。 input()はコードをPython式であるかのように評価し、結果を返します。しかしraw_input()は、単に入力を取得して文字列として返します。あなたが行うとき

だから:

tip * cost 

何が本当にやっていることは何かのように:

:もちろん、意味がないとPythonはエラーが発生します

2.5 * '20' 

>>> 2.5 * '20' 
Traceback (most recent call last): 
    File "<pyshell#108>", line 1, in <module> 
    '20' * 2.5 
TypeError: can't multiply sequence by non-int of type 'float' 
>>> 

最初にraw_input()を使用してコストを取得し、それを整数にキャストする必要があります。次にtaw_input()を使用してヒントを文字列として取得し、入力をfloatにキャストします。

#ask the user to input the total of the bill 

# cast input to an integer first! 
original = int(raw_input('What was the total of your bill?:')) 
cost = original 
print (cost) 

#ask the user to put in how much tip they want to give 

# cast the input to a float first! 
tip = float(raw_input('How much percent of tip in decimal:')) 
tipamt = tip * cost  
print "%.2f" % tipamt 

#doing the math 
totalamt = cost + tipamt 
print (totalamt) 
関連する問題