Python – Variables


It is a name that refers to an object that resides in memory. The object can be one of the types seen (number or text string), or one of the other types existing in Python.

Each variable must have a unique name called an identifier. That is very helpful to think of variables as containers containing data which can be changed later through programming techniques.

Scope of variables 

Variables in Python are local by default. This means that the variables defined and used in the code block of a function only exist within it, and do not interfere with other variables in the rest of the code.

In turn, existing variables outside a function are not visible within it.

In case it is convenient or necessary, a local variable can be converted to a global variable by explicitly declaring it as such with the global statement .

Variable examples 

Here are some examples of using variables :

Example of assigning value to variable

Next, we’ll create a couple of variables as an example. One of type strings and one of type integer :

python variable
>>> c  =  "Hello World"  # character strings 
>>> type ( c )  # check data 
type <type 'str'> 
>>> e  =  23  # integer 
>>> type ( e )  # check type data 
<type 'int'>

As you can see in Python, unlike many other languages, the type of the variable is not declared when it is created. In Java , for example, defining a variable would be like this:

String  c  =  "Hello World" ; 
int  e  =  23 ;

The small example has also served us to present the comments in line in Python: strings of characters that begin with the character and that Python ignores completely. There are more types of comments , which will be covered later.

Example of changing value to variable

Next, the value for a variable of type strings will be changed as an example:

>>> c  =  "Hello World"  # strings 
>>> c 
'Hello World'

Example of assigning multiple values ​​to multiple variables

Next, multiple variables ( integer , floating point , character strings ) will be created by assigning multiple values:

>>> a ,  b ,  c  =  5 ,  3.2 ,  "Hello" 
>>> print  a 
>>> print  b 
>>> print  c 

If you want to assign the same value to multiple variables at the same time, you can do the following:

>>> x  =  y  =  z  =  True 
>>> print  x 
>>> print  y 
>>> print  z 

The second program assigns the same boolean value to all three variables xyz.