Python Variables

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

Variable Types in Python

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

Casting

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"
print(type(x))
print(type(y))

Conclusion

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

Zigya Acadmey

Recent Posts

Understanding Standard Form of Numbers: An Explanation With Examples

Through the standard form offers different advantages in mathematical calculations and scientific notation. Firstly, it…

5 months ago

How to deal with stress and anxiety in college

Introduction Stress is a feeling caused by an external trigger that makes us frustrated, such…

6 months ago

Why is Sociology Important These Days?

Sociology is a broad discipline that examines societal issues. It looks at the meaningful patterns…

6 months ago

How to Convert Inches to mm

Some info about Inch Inches are a unique measure that persuades us that even the…

8 months ago

Antilogarithms – Definition, Methods, and Examples

You should be familiar with logarithms to understand antilogarithms in a better manner. Logarithms involve…

10 months ago

नाटककार सुरेंद्र वर्मा

यहां "नाटककार सुरेंद्र वर्मा" पुस्तक की पीडीएफ विद्यार्थी, शोधार्थी और जो इसका अभ्यास के लिए…

10 months ago