简体   繁体   中英

I need help to understand how to select words for a If statement from my function

tequila = input("What do you want to buy? ")

if ---- is tequila:
    
    tequilaprice = 45.67 
    
    print(tequilaprice)
    
else:
    
    print("not tequila! GOODBYE!")

I want my code to run if only the word tequila is typed in the string and not another word like car.

the easiest way to do it is just by creating an if statement.

user_input = input("What do you wanna buy? ")

if user_input == "tequila":
    tequilaprice = 45.67
    print(tequilaprice)
else:
    print("not tequila! GOODBYE!")

something like this should do.

If you want only tequila to be a valid answer it is as simple as you can think:

input_str = input("What do you want to buy? ")

if "tequila" == input_str:
    tequilaprice = 45.67
    print(tequilaprice)

else:
    print("not tequila! GOODBYE!")

In your example you included is . It won't work with it because it compares Python objects rather than values. The literal tequila in the code is a different Python object than the value returned by the input() function even if their value is the same.

If you're using input() you probably also want to ignore all white characters typed by the user like spaces and tabs. You can do that with strip() :

if "tequila" == input_str.strip():

If you want to run the code if tequila is a part of the input string then you can use in :

input_str = input("What do you want to buy? ")

if "tequila" in input_str:
    tequilaprice = 45.67
    print(tequilaprice)

else:
    print("not tequila! GOODBYE!")

Eg I want tequila as an input:

>>> What do you want to buy? I want tequila
>>> 45.67

You can also use input_str.lower() to ignore any letter capitalization. In that case tequila , Tequila and tEqUiLa all will be valid answers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM