Primitive type int () in Python

1

I'm a beginner (1 semester of TADS), the maximum programming I saw was programming logic and now I started studying > Python .

In the Python course of Video Course he taught that the primitive type int () should be written as:

n1 = int(input('Digite um valor: '))
n2 = int(input('Digite outro valor: '))
s = n1 + n2
print(s)

On the same day I saw a solution that wrote otherwise, like this:

n1 = input('Digite um valor: ')
n2 = input('Digite outro valor: ')
s = int(n1) + int(n2)
print(s)

Can any of the two make any mistakes in the future, or can I use whatever I want?

    
asked by anonymous 27.03.2018 / 02:41

2 answers

3

The two forms are perfectly equivalent when considering only the output produced, but the readability of the code differs. Namely, the native function input always returns a value of type string , even if a number is entered. In the first form, it is explicit in the first lines that it is desired to work with integer values, and thus both n1 and n2 receive the return of input converted to integers. In the second case, both objects will be of type string and since the goal is to add two numbers, it does not make much sense to store them as such. In other words, the first code snippet perfectly translates the program's intent, while the second does not.

  

Note that int in Python is a native class and that when calling int() is not invoking a function with this name, but the initializing method of class int . That is, you are instantiating the class by passing its value to the initializer.

What to use?

In a very general way, I would prefer to use the first variation, given what I mentioned earlier, but that does not imply that the second form is wrong. Depending on the situation, the second one may make more sense: to quote, a problem where you will necessarily need to store the values as strings .

    
27.03.2018 / 02:54
3

If someone said that type int should be written so it is already teaching wrong. The int() function is used to convert some value of another type into an integer, if possible.

Neither has problems, it's the same thing. It's like math, writing the same formula differently does not change the result. But I would do it in a different way.

For a beginner the second way seems to be the easiest to understand. It is taking two values typed by the user and then converting each of them to integer to add up. It is conceptually wrong if you consider that n1 and n2 seem to want to store numbers, and are saving texts. but does not change the result. I like the conceptual right because it takes you on the right path.

The first form also gives a good understanding and in some ways may even be easier to understand. It is more correct in my point of view because n1 and n2 already stores numbers because the conversion is done soon after the data entry.

You could avoid variables:

print(int(input('Digite um valor: ') + int(input('Digite outro valor: '))
    
27.03.2018 / 02:55