Home > Software design >  My if and else statement keeps evaluating as false but it is true in Python
My if and else statement keeps evaluating as false but it is true in Python

Time:09-08

my dictionary nested in a list

coins = [
{"Ethereum": "ETH-USD",
 "Bitcoin": "BIT-USD",
 "Solona": "SOL-USD"}
]

my function

def new():

search = input('Enter a coin\n').capitalize()
querystring = {"q": " ", "hl": "en", "gl": "US"}
if search not in coins:
    print('Please enter a valid coin')
else:
    querystring["q"] = search

my input is in the list but for some reason its coming back false and returning

print('Please enter a valid coin')

for some odd reason when I do

if search **in** coins:
    print('Please enter a valid coin')
else:
    querystring["q"] = search

I get the result I am looking for but that is because it is still evaluating as false at the start of the if statement. I feel like I am over looking something small or my knowledge on if and else statements might be a little flawed because I have this issue often when writing if and else statements.

CodePudding user response:

coins = [
{"Ethereum": "ETH-USD",
 "Bitcoin": "BIT-USD",
 "Solona": "SOL-USD"}
]

Here you declare a list which contains a dictionary. When you do x in coins, if x is a string, then the expression will always be false because coins only contains a dictionary, not a string. A string can never be equal to a dictonary.

To fix this, remove the brackets [], so that you only have a dictionary rather than a list with a dictionary.

  • Related