Print of the result of a ternary operator

0

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

I want to check if the size of the name you typed is greater than "Braga". For this condition, I want to use the Python ternary operator to check if it is "larger" or "smaller" and merge this information into the final print string: "Your 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, I recommend: Repl.it

    
asked by anonymous 22.11.2017 / 14:22

2 answers

3

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

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

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

Or just 5, since the value is constant:

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

See working at Repl.it

Note 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 these, determining the relative position between the two; that is, making 'anderson' < 'lucas' is true, since 'a' comes before 'l', regardless of whether the amount of character is greater or less. If you want to compare the size, use len .

    
22.11.2017 / 14:31
0

You are doing the comparison with the name of the person you typed, should put this way, as I will show below, after all you have to compare the 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 entered is if len(nome) > 5 after all the word Braga has 5 characters, but there goes your need

    
22.11.2017 / 14:30