-1

enter image description here

I wrote a simple code in python.

Originally my assignment is to receive two inputs(name of person) and print them.

Here's my question. When I try to sum two variables but one of them is int and another one is str, an error occurs. But in this case (the picture) why variable 'a' is recognized as a str not int? I think there must occurs an error but a is recognized as a str and work well.

Yun
  • 11
  • Well in the documentation it clearly says that `input()` converts the argument to a string so you need to cast it to int [1]: https://docs.python.org/3/library/functions.html#input – nidabdella Jan 26 '21 at 13:57

1 Answers1

2

In Python 3, input() always returns a string. (In Python 2, input() would try to interpret – well, evaluate, actually – things, which was not a good idea in hindsight. That's why it was changed.)

If you want to (try to) make it an int, you'll need int(input(...)).

AKX
  • 152,115
  • 15
  • 115
  • 172
  • thanks I learned that python automatically choose the type of variables. But maybe I misunderstood something – Yun Jan 26 '21 at 13:56
  • 1
    @Yun in python variables don't have types. Variables point to objects that have types, but a variable that was pointing to a string object can be changed to point to a integet object. If variables had types you could not do that. – Adirio Jan 26 '21 at 13:58
  • @Adirio pathon variables have types !!, Most of the time interpreter automatically selects appropriate type. But in some cases you need to manually specify required type – 0xB00B Jan 26 '21 at 14:01
  • @TanishqBanyal trust me, they don't. Objects they refer to have types, but variables don't. Variables in python are just tags that point to something. That something is the object and the object is typed. However, the variable is not typed, and that is the reason why you can do `a = 5;a = "Hello"` – Adirio Jan 26 '21 at 14:05
  • 1
    @TanishqBanyal No, they don't. *Values* have types; a variable is just a name, which can be bound to *any* value, regardless of its type. What you think is the type of the variable is just the type of the currently bound value. – chepner Jan 26 '21 at 14:06