Press "Enter" to skip to content

Python Variables

Zigya Acadmey 0

Think of a variable as a name attached to a particular object. In Python, variables need not be declared or defined in advance, as is the case in many other programming languages. To create a variable, you just assign it a value and then start using it. Assignment is done with a single equals sign (=):

>>> n = 10

This is read or interpreted as “n is assigned the value 10.” Once this is done, n can be used in a statement or expression, and its value will be substituted:

>>> print(n)

Just as a literal value can be displayed directly from the interpreter prompt without the need for print(), so can directly call a variable:

>>> n

Later, if you change the value of n and use it again, the new value will be substituted instead:

>>> n = 1000
>>> print(n)
>>> n

Python also allows chained assignment, which makes it possible to assign the same value to several variables simultaneously:

>>> a = b = c = 100
>>> print(a, b, c)
100 100 100

Variable Types in Python

Variables in Python are not subject to this restriction.

>>> var = 23.5
>>> print(var)

>>> var = "Now I'm a string"
>>> print(var)
Now I'm a string


If you want to specify the data type of a variable, this can be done with casting.

x = str(5)    # x will be '5'
y = int(5)    # y will be 5
z = float(5)  # z will be 5.0

Get the Type

You can get the data type of a variable with the type() function.

x = 50
y = "zach"


This tutorial covered the basics of Python variables, including object references and identity, and naming of Python identifiers.

You now have a good understanding of some of Python’s data types and know how to create variables that reference objects of those types.

This brings the end of this Blog. We really appreciate your time.

Hope you liked it.

Do visit our page for more informative blogs on Data Science

Keep Reading! Cheers!

Zigya Academy

Leave a Reply

Your email address will not be published. Required fields are marked *