I didn’t quite understand the "use string as value" part, but rather it is possible to check whether a string is inside a list, tuple and other iterable.
In your example code, the comparison returned False
because a string is different of a tuple containing strings, as well as "1"
is different from 1
. To check if a string is inside an iterable (in your case a string tuple), you must replace the operator ==
for in
. See how it would look:
valores = ('M', 'F')
print(valores)
sexo = input('Digite o seu sexo [M/F]: ').upper()[0].strip()
print(sexo)
if sexo in valores:
print('Valor registado com sucesso.')
else:
print('Dados incorretos. Digite novamente.')
The operator in
unlike ==
, checks whether an object (can be an object of any type) is inside an eternal, or rather, it checks whether the target object contains the object you are specifying.
You can do this check not only with strings, but also with objects of other types. See the examples below:
"Masculino" in ["Masculino", "Feminino"] # True
17 in [19, 23, 3, 1023, 17, 65] # True
3 in ["3", 2, True, "bola"] # False ("3" é diferente de 3)
True in [False, True, False, False] # True
Remember I told you in
checks if an object contains an element ? Then... this verification occurs through the method __contains__
that takes a value and checks whether or not the object is passed. Example:
class MinhaClasse():
def __contains__(self, value):
if value == 7:
return True
else:
return False
objeto = MinhaClasse()
3 in objeto # False
7 in objeto # True
Note that the object to be checked is always before the operator. So if I reversed the code to objeto in 7
, I’d be checking if the object is in the number 7
and besides not working, would still generate an error, because int
does not have the method __contains__
.
I can’t detect my mistake
– Ruben Maurício
Only one detail: in Python 3,
input
already returns a string, no need to dostr(input(...))
. And if you already get her first character (with[0]
), also need not callstrip
after (if the first character is a space, either remove it or not, since you will check if it is M or F and it will not make a difference)– hkotsubo