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.

[code lang=”python”]
a = 6
b = 7
print(a)
print(b)[/code]

Output:
6
7

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

[code lang=”python”]type(a)[/code]

Output:
class <Int>

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

[code lang=”python” highlight=”float(5)” light=”false”]float_var = float(5)
print(float_var)
print(type(float_var))[/code]

Output:
5.0
class <float>

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

[code lang=”python”]str_var = "Sample String"
str_var2 = ‘string value’
print(str_var)
print(type(str_var))[/code]

Output:
Sample String
class <string>

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

[code lang=”python”]a = b = c = 0
print(a,b,c)[/code]

Output: 0 0 0

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

[code lang=”python”]a = b = c = 0,1,2
print(a,b,c)[/code]

Output: 0 1 2

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

[code lang=”python”]num=1
word = ‘One’
print(str(num) + " in words is " + word)[/code]

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.24tutorials.com/sai

Lost Password

Register

24 Tutorials