Variables in Python

In this article, we will learn how to declare variables in Python and types of variables. It is the continuation sixth article of "Zero To Hero In Python" series.
Everything we will understand step by step. Before read this article go through my previous articles. 

Let's start,

What is Variable ? 
Variable is a memory location which contains the values. When we create any variable then it stores the values of that variable which we declared.

Python do not compile the code it always interpreted the code. In python does not need to define datatype of any variable before it's declared. When we write any variable and assign its value the it automatically defines its datatype according to its values which you assigned.

1. Variables are created when it assigned first.
2. No need to declaration a variable.
3. Variable stores values for accessed or update letter.
4. Before referenced a variable it must be assigned.

Now let's open VS Code editor and create a python file("").

Command for create a file: 

Syntax: $touch 

open the file 

Syntax: $code

Open File:

In the above snapshot,
It means X store integer data type.
x stores string datatype.

Multiple Assignment with same values:

Python allows you to assign a single value to several variables simultaneously. For 



In above snapshot you can see that all the variables which all are store same values with it.


Multiple Assignment with different values:

In multiple assignment declare more that one variable in single line and all variables are assigned with different -2 values with same time.

 In the above code we have declare and assign four variables (A, B, C, D) with  different datatype of values and each and every variable take their values according to the variable & values sequence. 


Type of Variables : 

There are two type of variables. 


2. Global

In python when we want to use same variable inside and outside the module and we declare it global variable, now it treats as both (local & global) variable, when it works like local and global. It is very interesting things let’s understand it with below code.

Code File:


As you can the above snapshot, variable a declare as global and assigned it with 10. After called localGlobal function it's( variable a ) variable assigned within the scope of this function. And it contains different values inside and outside.
Variable a assigned with 10 and same variable inside the function assigned with 200. When we print global variable then it print 10 but print same variable and assigned within function then it prints 200. You can see the output.

No comments

Powered by Blogger.