top of page
Search

Types in Python

Writer's picture: Abhinaw TripathiAbhinaw Tripathi

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 


4 views0 comments

Recent Posts

See All

Lambda Functions in Python

So Lambda Functions are just an anonymous function.they are very simple just saves your space and time.they are useful in case of higher ...

Generator Function - Yield Python

So Yield is a keyword.first let's take an example. student = [] def read_file(): try: f=open("students.txt","r") for student in...

Opening,Reading and Writing Python

Let's save our data in a file and read from that file again when we re-open our app. So let's take an example: Let's take an example: ...

© 2016 by Abhinav Tripathi

  • Facebook Clean Grey
  • Twitter Clean Grey
bottom of page