Why do I not need to explicitly define int data type in this exercise function? | Sololearn: Learn to code for FREE!
+ 3

Why do I not need to explicitly define int data type in this exercise function?

I'm confused on something that I don't think was explained in python course material... When I'm defining a function and having it perform a math operation, why does the following code work and not require explicit data type assignment? Why does this work: ------------- #function definition def double(number): print(number*2) #function call double(6) ----------- Wouldn't I need to do: ----- #function definition def double(number): number=int(number) print(number*2) #function call double(6) -------

4th Jul 2024, 2:03 PM
Michael Berggren
Michael Berggren - avatar
3 ответов
+ 6
Perhaps the lack of explanation was due to the design to keep the lesson material small (bite-sized). As it was presented as a mere example, the lesson did not anticipate an event where the learner questions why, this or that, or requires extra details. The example was just that - an example to show the learner how to write a function. Just to answer your curiosity, in that example, the function `double` was invoked passing an integer (6) as an argument. That is enough to tell us - we pass integer 6 on to it and it will display the result of the integer multiplied by 2. No type specification nor type conversion was necessary. Mind that some types may not support a certain operation (here it's multiplication). For example, `set` and `dict` does not support multiplication, thus an exception will be raised when you try to pass an object created from either one of these classes as argument for function 'double' call. Please clarify if I misunderstood you :)
4th Jul 2024, 3:16 PM
Ipang
+ 6
the method which is used to detect a *data type* is called *type inference*. it refers to the automatic detection of the type of an expression in a formal programming language. this is not limited to python.
4th Jul 2024, 5:06 PM
Lothar
Lothar - avatar
+ 4
Michael Berggren In python don't need to define data type. Python understand it self. 6 -> int 6.0 -> double "6" -> String int(number) -> here int is a function which is used to convert value in int. int(6.0) => 6 int("6") => 6
4th Jul 2024, 3:28 PM
A͢J
A͢J - avatar