2014-05-03 134 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 –