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)
10
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
10
Later, if you change the value of n
and use it again, the new value will be substituted instead:
>>> n = 1000
>>> print(n)
1000
>>> n
1000
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
Variables in Python are not subject to this restriction.
>>> var = 23.5
>>> print(var)
23.5
>>> 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
You can get the data type of a variable with the type()
function.
x = 50
y = "zach"
print(type(x))
print(type(y))
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 www.zigya.com/blog for more informative blogs on Data Science
Keep Reading! Cheers!
Zigya Academy
BEING RELEVANT
Through the standard form offers different advantages in mathematical calculations and scientific notation. Firstly, it…
Introduction Stress is a feeling caused by an external trigger that makes us frustrated, such…
Sociology is a broad discipline that examines societal issues. It looks at the meaningful patterns…
Some info about Inch Inches are a unique measure that persuades us that even the…
You should be familiar with logarithms to understand antilogarithms in a better manner. Logarithms involve…
यहां "नाटककार सुरेंद्र वर्मा" पुस्तक की पीडीएफ विद्यार्थी, शोधार्थी और जो इसका अभ्यास के लिए…