Thursday, December 7, 2017

Types in Python

In Python type has been handled differently than other programming languages.in many programming languages including JAVA or C# .you have to declare variable type before you declare variable itself.that variable type can be int,float,double, String,char Boolean or your own custom types such as Student.So before you even declare variable you have to write something like this.

// C# or java

int answer=42;
String name="Pyhton";

With pyhton take this approach in opposite direction.in pyhton it is not necessary  to declare type anywhere.in fact you will do something like this.

# Python

answer = 42
name = "Python'

And same thing goes with other types including your own type.
Now there are some advantages and disadvantages of this approach.
Pyhton also called dynamically typed language.So not declaring types leads many bugs for example suppose we have simple function they just adds two numbers.will look like below.

def add_numbers(a,b)
print(a+b)

Call the function
add_numbers(5,11)
16. everyhting is fine.

but what if we call like below:

add_numbers(5,"something")

It will give type error:unsupported operand types.
well python does not have any machenism to tell you in advance while other languages have.

There is something called "type hinting".

Type Hinting: this is new features added in Python version 3.5 .they will help you to add data types in your program.it will help your IDE.it will not prevent your wrong  code running.So you can do something like this:

def add_numbers(a: int, b: int)  -> int:
return  a + b

No comments: