Python Variable Assignment

 

Variable Assignment

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 = 300

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

>>>
>>> print(n)
300

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

>>>
>>> n
300

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 = 300
>>> print(a, b, c)
300 300 300

The chained assignment above assigns 300 to the variables ab, and c simultaneously.

Comments

Popular posts from this blog

Variable Names in python

What is a python