Opa friends, I wonder why in the code below the answer only comes out right if before writing the word (holy) I give a space. : /

Asked

Viewed 78 times

0

cidade = str(input('Digite o nome da sua cidade: ')).title()
p = cidade.find('Santo')
if p == True:
   print('A sua cidade começa com Santo.')
else:
   print('A sua cidade não começa com Santo.')

1 answer

3


The need for space added at the beginning of the input is due to the misuse of the method str.find() and a disastrous type conversion.

The method str.find() returns an integer numeric value (zero or positive) that is the index of the first substring appearance, passed by parameter, within a string. Or else it returns -1 if the string is not found.

So on the line:

p = cidade.find('Santo')

The variable p substring-independent 'Santo' whether or not contained in cidade the result will always be an object of type int.

Wrong conversion happens on the line:

if p == True:

Where do you compare p who’s kind int with True which is one of the two logical constants.
It turns out that when there is a comparison between instances of different classes the interpreter first tries to convert the second operand to the same type of the first so that there can be a comparison. But by converting True in int...

>>> print(int(True))
1

The result is 1 and which makes its code equivalent to:

cidade = str(input('Digite o nome da sua cidade: ')).title()
p = cidade.find('Santo')
if p == 1: #substituindo a constante lógica True por sua conversão numérica.
   print('A sua cidade começa com Santo.')
else:
   print('A sua cidade não começa com Santo.')

Meaning the comparison will only be true if the substring 'Santo' appear in the index 1 string. Remembering that the index of the first character of a string is 0.

To fix just make the code correctly compare the substring position 'Santo' and position of interest:

cidade = str(input('Digite o nome da sua cidade: ')).title()
p = cidade.find('Santo')
if p == 0: #Verifica se o substring 'Santo' aparece a partir da primeira letra.
   print('A sua cidade começa com Santo.')
else:
   print('A sua cidade não começa com Santo.')
  • thanks for the explanation, clarified my doubt enough!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.