你在你的代碼錯誤。您正在詢問子三明治名稱,因此您不需要案件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$
我必須說出色的答案。 +1 – sshashank124
謝謝:)也對你+1 –