How does dynamic typing work in Python 3.x?

6

I'm new to Python and I had a question when I solved Exercise 1001 of Uri Online (read A and B, assign sum to X and print), when writing the following code, I received concatenation:

a = input()
b = input()

x = a + b

print ("x = ", x)

When exchanging input () for int (input ()) on each of the variables, I get the sum. From what I understand, if I do not declare anything in the input, by default the received type will be a string. I'm accustomed to Java, where it's always necessary to declare the type of the variable. I would like you to explain to me how Python typing works.

    
asked by anonymous 19.06.2016 / 19:05

1 answer

3

In python to declare a variable it is not necessary to declare its type, only its value what is called dynamic typing, other than java or C, that have static typing. In addition python has strong typing, ie it does not perform automatic type conversion during an operation, other than PHP:

    >>> a = 10
    >>> b = "10"
    >>> a + b
    Traceback (most recent call last):
      File "<input>", line 1, in <module>
    TypeError: unsupported operand type(s) for +: 'int' and 'str'

As you can see in this code when trying to perform the operation, it returns an error, which denotes strong typing. In the case of the input () function it always returns a string, what happens is a type conversion by putting int (input ()) that is:

    >>> a = int(input())

It's the same as:

    >>> a = input()
    >>> a = int(a)
    
20.06.2016 / 03:30