I’ll start from the premise that you forgot to put the quotes in your strings. Then the correct tuple would be:
(('joao', 39), ('paulo', 15), ('andre', 14), ('simao', 21))
From this you need to know how to test the type of a variable correctly. You can use the method type()
and compare directly with the type you want, for example:
if type(variavel) == tuple:
print('É uma tupla')
However it is worth remembering that in this way there is no verification of subclasses, ie in the example above, if variavel
is from a subclass of tuple
print would not run because there is no subclass check.
To perform this check just use the method isinstance()
, which checks if the variable is of the asked type or if it is of some subclass of the asked type. Example:
if isinstance(variavel, tuple):
print('É um tupla ou subclasse de tupla')
The use of one or the other will depend on the requirements of your software, but as a general rule I use isinstance()
because the subclass is likely to behave like the parent class.
That said, all you would need to do is test the 4 requirements you want, which are:
- Variable is a
tuple
- This tuple has only two elements
- First element of the tuple is
str
- Second element of the tuple is
int
You’d have something like:
def verifica(variavel):
return isinstance(variavel, tuple) \
and len(variavel) == 2 \
and isinstance(variavel[0], str) \
and isinstance(variavel[1], int)
For curiosity purposes, rather than using and
you can use the method all()
returning True
only if all received parameters are also True
. The whole example would look like this:
def verifica(variavel):
return all((
isinstance(variavel, tuple),
len(variavel) == 2,
isinstance(variavel[0], str),
isinstance(variavel[1], int)
))
dados = (
('joao', 39), # True
(b'andre', 14), # False pois 1º elemento não é str
('paulo', 15.3), # False pois 2º elemento não é int
('simao', 21, 0) # False pois não contém exatamente 2 elementos
)
for d in dados:
print(verifica(d))
Repl.it with code working.
Edit: added tuple size check
(Tip: @Anderson-carlos-woss).
Edit 2
As there still seem to be doubts about how to apply the function verifica()
for all elements of a sequence, and not just one element, I will elaborate.
The function verifica()
receives a tuple and checks if the tuple pattern is correct:
tupla_valida = ('Tupla válida', 0)
verifica(tupla_valida) # True
If you want to check all the tuples of a sequence, you can scroll through this sequence using a loop for
and test one by one. If some of them are False
then you choose what your program should do about it.
Example, check if the sequence contains only valid tuples:
tuplas = (('joao', 39), ('paulo', 15), ('andre', 14), (0, 'Inválida'))
todas_validas = True # Valor inicial
for tupla in tuplas:
if not verifica(tupla):
# se alguma tupla for inválida atribui False e sai do loop
todas_validas = False
break
if todas_validas:
print("Todas as tuplas são válidas")
else:
print("A sequência contém alguma tupla inválida")
Repl.it with code working.
If you have any questions about the above code, study a little about the for
and the break
.
I will leave as an example for study, an alternative to the previous code that uses the method all()
previously mentioned and list comprehensions to achieve the same result.
tuplas = (('joao', 39), ('paulo', 15), ('andre', 14), (0, 'Inválida'))
# aplica a função `verifica` em todos os elementos da tupla e passa
# a lista resultante para o método `all`
# nesse caso o método `all` recebe: (True, True, True, False)
todas_validas = all([verifica(tupla) for tupla in tuplas])
if todas_validas:
print("Todas as tuplas são válidas")
else:
print("A sequência contém alguma tupla inválida")
Repl.it with code working.
Start by confirming the code indentation, and change it so it looks exactly like the one you have in your editor.
– Isac
I put the code just like this in my editor. By the way, I use python 3.3 and Wing IDE 101 as compiler.
– dominion
Seems unlikely, because the way the code is in the question, you have
return
out of functionverifica
. Soon I assume it’s all function codeverifica
but only you can confirm.– Isac