Python

Python Variables and DataTypes

Python is pure object-oriented, everything variable is an object. Unlike Java, you no need to declare a variable and specify its datatype. It is intelligent enough to infer the datatype automatically.

Below is the syntax to declare a variable in Python. Just specify name and use (=) operator to assign a value.

a = 6
b = 7
print(a)
print(b)
Output:
6
7

To check the datatype of the variable use – type() method.

type(a)
Output:
class <Int>

You can also explicitly define the variable to specific datatype-like int(value),float(value),str(value)

float_var = float(5)
print(float_var)
print(type(float_var))
Output:
5.0
class <float>

To define a string variable you can use double or Single quotes-

str_var = "Sample String"
str_var2 = 'string value'
print(str_var)
print(type(str_var))
Output:
Sample String
class <string>

Multiple Assignment:
You can assign single value at a time to multiple variable-

a = b = c = 0
print(a,b,c)
Output: 0 0 0

You can assign multiple values to multiple variables in single line-

a = b = c = 0,1,2
print(a,b,c)
Output: 0 1 2

Mixing different variables with different datatypes is not supported. You need to typecast it to achieve the same.

num=1
word = 'One'
print(str(num) + " in words is " + word)
Output: 1 in words is One

In the above example, variable-num is typeCasted to String and concatenated with subsequent strings.

Share This Post

An Ambivert, music lover, enthusiast, artist, designer, coder, gamer, content writer. He is Professional Software Developer with hands-on experience in Spark, Kafka, Scala, Python, Hadoop, Hive, Sqoop, Pig, php, html,css. Know more about him at www.saikumar.me

Lost Password

Register