2014-05-03 317 views
4

我很新的Python和我需要一些幫助,這行代碼:Python的選擇和輸入

sub = float(input("Type in the name of the sub sandwhich which you'd like to know the nutrition facts of.")) 

if sub == bacon: 
    print("282 Calories, 688.4g Fat, 420mg Sodium, 1407mg Potassium, and 33.5g Protein") 

結果輸入查詢後:

ValueError: could not convert string to float: 'bacon 

回答

1

你不能施放一個非數字字符串作爲一個浮動。這樣做如下:

sub = input("Type in the name of the sub sandwhich which you'd like to know the nutrition facts of.") 

if sub == 'bacon':  # 'bacon' not bacon 
    print("282 Calories, 688.4g Fat, 420mg Sodium, 1407mg Potassium, and 33.5g Protein") 
0

您正在要求一個字符串,而不是一個浮點數。使用輸入而不是浮動(輸入)。而if語句,把在報價爲培根

sub = input("Type in the name of the sub sandwhich which you'd like to know the nutrition facts of.") 

if sub == 'bacon': print("282 Calories, 688.4g Fat, 420mg Sodium, 1407mg Potassium, and 33.5g Protein") 
2

你在你的代碼錯誤。您正在詢問子三明治名稱,因此您不需要案件float(input()),只需將它留在input()提示:如果您使用的是python2.x,使用raw_input()代替input()

你的第二個錯誤是,你正在檢查if sub == bacon:sub已被定義,但bacon不是,所以您需要用引號括起來。

這是您編輯的代碼:

sub = input("Type in the name of the sub sandwich which you'd like to know the nutrition facts of:\n") 

if sub == 'bacon': #'bacon' with quotations around it 
    print("282 Calories, 688.4g Fat, 420mg Sodium, 1407mg Potassium, and 33.5g Protein") 

這種形式運行:

bash-3.2$ python3 test.py 
Type in the name of the sub sandwich which you'd like to know the nutrition facts of: 
bacon 
282 Calories, 688.4g Fat, 420mg Sodium, 1407mg Potassium, and 33.5g Protein 
bash-3.2$ 

如果你正在尋找增加更多可能的潛艇,我會建議使用字典,如下所示:

subs = {'bacon':["282", "688.4", "420", "1407", "33.5"], 'ham':["192", "555.2", "340", "1802", "44.3"], "cheese":["123", "558.9", "150", "1230", "12.5"]} 

sub = input("Type in the name of the sub sandwich which you'd like to know the nutrition facts of:\n") 

arr = subs[sub] 
print("%s Calories, %sg Fat, %smg Sodium, %smg Potassium, and %sg Protein" %(arr[0], arr[1], arr[2], arr[3], arr[4])) 

此爲:

bash-3.2$ python3 test.py 
Type in the name of the sub sandwich which you'd like to know the nutrition facts of: 
bacon 
282 Calories, 688.4g Fat, 420mg Sodium, 1407mg Potassium, and 33.5g Protein 
bash-3.2$ python3 test.py 
Type in the name of the sub sandwich which you'd like to know the nutrition facts of: 
ham 
192 Calories, 555.2g Fat, 340mg Sodium, 1802mg Potassium, and 44.3g Protein 
bash-3.2$ python3 test.py 
Type in the name of the sub sandwich which you'd like to know the nutrition facts of: 
cheese 
123 Calories, 558.9g Fat, 150mg Sodium, 1230mg Potassium, and 12.5g Protein 
bash-3.2$ 
+0

我必須說出色的答案。 +1 – sshashank124

+0

謝謝:)也對你+1 –