Python selection and input

I am very new to Python and I need help with this line of code:

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")

Results after input:

ValueError: could not convert string to float: 'bacon
+4
source share
3 answers

There are two errors in the code . You are requesting a subshift name , so you do not need to use case float(input()), just leave it in input(). Tip. If you are using python2.x use raw_input()insteadinput()

The second mistake is what you check if sub == bacon:. subalready defined, but baconno, so you need to surround it with quotes.

Here is the code you edited:

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")

This runs as:

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$ 

If you want to add more possible subtitles, I would suggest using a dictionary, for example:

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]))

This runs as:

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$ 
+2

non number float. :

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")
+1

, . float (). 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")
0
source

Source: https://habr.com/ru/post/1539086/


All Articles