Header Ads

Variable & its Types in Python

 In the Blog I have uploaded about Python variable

Variable:

    1) Variables are nothing but reserved memory locations to store values. This means when you create a variable you reserve some space in  memory. Variables can be declared by any name or even alphabets like a, aa, abc, etc. Python constants can be understood as types of variables that hold the value which can not be changed. Usually Python constants are referenced from other files. Python define constant is declared in a new or separate file which contains functions, modules, etc.




  
a=100
print (a)
output:
100


2) Re-declaration Variables:

Variables can be re-declared even after you have declared them for once

Example:

# Declare a variable and initialize it
f=10
print(f)
#re-decaleration the variable 
f='Worldsinfo'
print(f)

OutPut

0
Worldsinfo


3) Python String Concatenation and variable:

Example: 

a="AllaboutStudey"

b=20

print (a+str(b))    #it change (b) variable data type into string. 

OutPut:

AllAboutStudy 20

4) Python Variable types:

There are two types of variable in python 

i) Local Variable     ii) Global Variable

i) If you want to use the variable in a specific function or method, you are use local variable while Python variable declaration. Declare local variable when you want to use it for current function.

ii) When you want to use same variable for rest of your program or module you declare it as a Global variable. Declare Global variable when you want to use the same variable for rest of the program

Variable Global & Local with examples:


Description:

1) Let us define variable in Python where the variable “f” is global in scope and is assigned value 101 which is printed in output


2) Variable f is again declared in function and assumes local scope. It is assigned value “I am learning Python.” which is printed out as an output. This Python declare variable is different from the global variable “f” defined earlier


3) Once the function call is over, the local variable f is destroyed. At line 12, when we again, print the value of “f” is it displays the value of global variable f=101.




Description:

1) Variable “f” is global in scope and is assigned value 101 which is printed in output


2) Variable f is declared using the keyword global. This is NOT a local variable, but the same global variable declared earlier. Hence when we print its value, the output is 101


3) We changed the value of “f” inside the function. Once the function call is over, the changed value of the variable “f” persists. At line 12, when we again, print the value of “f” is it displays the value “changing global variable”.


Delete Variable:

To delete a variable, it uses keyword “del”.

    Example:



No comments

Powered by Blogger.