Checking if a value in an array is equivalent

I am new to python (and generally programming) and I cannot find a solution for this myself. I want to check that the first letter of a string is equal to any letter stored in the array, something like this:

letter = ["a", "b", "c"] word = raw_input('Enter a word:') first = word[0] if first == letter: print "Yep" else: print "Nope" 

But this does not work, does anyone know how it will be? Thanks in advance!

+6
source share
4 answers

You need to use the in operator. Use if first in letter:

 >>> letter = ["a", "b", "c"] >>> word = raw_input('Enter a word:') Enter a word:ant >>> first = word[0] >>> first in letter True 

And one False test,

 >>> word = raw_input('Enter a word:') Enter a word:python >>> first = word[0] >>> first in letter False 
+9
source

Try using the in keyword:

 if first in letter: 

In the current code, you are comparing a string character ( first , which is equal to the first character in word ) in the list. So let my input be "a word" . Actually your code:

 if "a" == ["a", "b", "c"]: 

which will always be false.

Using the in keyword does:

 if "a" in ["a", "b", "c"]: 

which checks if "a" member of ["a", "b", "c"] and returns true in this case.

+4
source

Hint in your question. Use any . This uses a generator expression to check if it is True or False.

 any(first == c for c in letter) 
+3
source

The problem, as I see it, is that you are asking if the character matches an array. This will always return false.

Try using a loop to check the β€œfirst” for each element in the β€œletter”. Let me know if you need help figuring out how to do this.

0
source

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


All Articles