Declaring a Variable Type In Python

Python does not require an explicit declaration of the variable type. However there may be situations when one needs to specify the variable type.

For example if i write a program

from math import sin
x= raw_input ("enter the angle")
print sin(x)

This will give a an error like:
Traceback (most recent call last):
File "D:\guido\misc.py", line 24, in
print sin(x)
TypeError: a float is required

A workaround for such a situation would be to declare the variable type using the command var = variabletype(var)

from math import sin
x= raw_input ("enter the angle")
x= float(x) # declaring the variable as float
print sin(x)

We declared the variable type float for this example. You can similarly do a variable declaration for python standard data types:

a) numbers: int, long, float & complex

b) string

c) list

d) tuple

e) dictionary

As a sidenote, when in doubt about the kind of variable that a data represents – you can verify the data type using the type() function. For example if you enter type(x) in the above example :

 >>> type (x)

 

Alternative method of declaring variable type in Python:

You can alternatively simply declare the variable type by assigning it a starting variable in the format wanted.

for example

i = 10          # Declares a variable i which is an integer
x = 55.5       # Declares a floating point variable
foo  = "Scoobydoo"       # Declares a string variable