Problems with input results after using an "int ()"

3

Code sample:

idade = input("Qual a sua idade? ")    
int(idade)

if idade >= 45:    
    print("Tá velho cara, já era!")    
else:    
    print("A vida está só começando rapaz!")

Error encountered:

Qual a sua idade? 45
Traceback (most recent call last):
  File "C:/Users/Lucio/Desktop/ProgramasPython.py", line 6, in <module>
    if idade >= 45:
TypeError: '>=' not supported between instances of 'str' and 'int'
    
asked by anonymous 28.12.2018 / 01:49

2 answers

3

In the second line you are converting the contents of the variable idade to integer and discarding the result, then when you check you think you are already an integer, but it is still a string . I guess you wanted to keep this somewhere. And I imagine you think that just by doing the operation on the variable it changes the value of it, but this does not happen, you just manipulate the value of it.

But the most correct would be to create another variable since they are different types. And the error caused shows why it is better not to reuse variable with different types. In Python it would work to play on the same variable, but it is not cool to do this. The good part is that you do not even have to do this, you can read the data and convert at once and only save the converted value, like this:

idade = int(input("Qual a sua idade? "))
if idade >= 45:
    print("Tá velho cara, já era!")
else:
    print("A vida está só começando rapaz!")

See running on ideone . And no Coding Ground . Also I put GitHub for future reference .

This code can still fail, can be written in another way, but basically, to start learning, this is it.

    
28.12.2018 / 02:25
2

You thought that int(idade) would transform the variable idade into an integer, check?

Well, you just saw that that was not what happened. The int(str) constructor when it receives a string creates an object of type int whose value in decimal is the one that would be shown in the string. This was actually done in your code. However, without pointing it at any variable, this object will be created and lost. To not lose, you need to assign this value to a variable. So, you could even do:

idade = input("Qual a sua idade? ")    
idade = int(idade)

But in reality? You want to read an integer, so why not read an integer already? It looks like this:

idade = int(input("Qual a sua idade? "))
    
28.12.2018 / 02:27