How does dynamic typing work in Python 3.x?

Asked

Viewed 1,093 times

7

I am new to Python and a question came to me when solving exercise 1001 of Uri Online (read A and B, assign sum to X and print), when writing the following code, I received the concatenation:

a = input()
b = input()

x = a + b

print ("x = ", x)

when exchanging input() for int(input()) for 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 used to Java, where it is always necessary to declare the type of the variable. I would like you to explain how the Python typing works.

  • in python it is not necessary to declare the type of the variable as it is automatically assigned you can try a data type conversion

1 answer

4


In python to declare a variable it is not necessary to declare its type, only its value which is called dynamic typing, other than java or C, which have static typing. Also python has strong typing, IE, does not perform automatic conversion of types 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 can be observed in this code when trying to perform the operation it returns an error, which denotes strong typing. In the case of the function input() it always returns a string, what happens is a type conversion when placing int(input()) you transform the entire content, ie:

    >>> a = int(input())

Is the same as:

    >>> a = input()
    >>> a = int(a)

Browser other questions tagged

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