Print of the result of a ternary operator

Asked

Viewed 474 times

0

How to display the output of a ternary operation next to a string, using Python?

I intend to check if the size of the name typed is larger than "Braga". For this condition, I want to use the ternary Python operator to check whether it is "larger" or "smaller" and join this information in the final print string: "Its name is bigger/ smaller than mine!".

def operadorTernario():
  """ Exemplo do operador ternário """

  nome = input('Qual o seu nome? ')
  print('O seu nome é', 'maior' if len(nome) > 'Braga' else 'menor', 'que o meu!')


operadorTernario()

To test online, recommend: Repl.it

  • 1

    "Larger than Braga" makes no sense. Would be bigger than the size of Braga? If yes, should be len('Braga'), or only 5 even, since that value would not change.

  • exactly, as @Andersoncarloswoss you are comparing the size of the name typed with the word Raga...

  • would be a common if and E-if, if it is larger print than, smaller print case than

  • Lucas, you can use the button share from Repl.it to share your code working.

  • @Andersoncarloswoss refers to the size of "Braga". I understood what actually showed the error output in the terminal. Erroneously I was returning a int of the name received in the input and trying to compare with the string "Braga". I’ve fixed using the len('Braga') . Thanks!

2 answers

3


In doing len(nome) > 'Braga' you will be comparing an integer number, which will be returned by the function len, with a string. This doesn’t make any sense, even gives the type error saying that the comparison between int and string is not allowed.

The correct one would be to compare two integer values, the second being obtained by len('Braga'):

'maior' if len(nome) > len('Braga') else 'menor'

Or only 5, since the value is constant:

'maior' if len(nome) > 5 else 'menor'

See working on Repl.it

It is worth noting that the comparison between two strings is also valid, but does not produce the desired result. When comparing strings, you check the alphabetical order of the two, determining the relative position between the two; that is, do 'anderson' < 'lucas' is true, because 'a' comes before 'l', regardless if the amount of character is higher or lower. If you want to compare the size, use len.

  • great answer.

  • Perfect Anderson!

0

You are making the comparison with the very name of the person who typed, should put this way, as I will show below, after all you have to compare to string typed with a value string

print('O seu nome é', 'maior' if (len(nome) > len('Braga')) else 'menor', 'que o meu!');

You can also inform that the name you have entered is if len(nome) > 5 After all the word Braga has 5 characters, but there goes your need

  • Sorry I hadn’t noticed the inattention, I fixed it

Browser other questions tagged

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