Python选择和输入

时间:2014-05-03 04:37:55

标签: 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

3 个答案:

答案 0 :(得分: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$ 

答案 1 :(得分: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")

答案 2 :(得分: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")