My if and else statement keeps evaluating as false but it is true in Python

Question:

my dictionary nested in a list

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

my function

def new():

search = input('Enter a coinn').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.

Asked By: drafty

||

Answers:

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.

Answered By: Code-Apprentice
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.