Python Variables
Python Variables
Variable is used to store the values. Basically we can think of variable as a container which contains the value like number, string, boolean, etc. Variables are also called as identifier because they are used to identify a particular value. In other programming languages, before assigning a value to variable you have to declare the varibable with its data type like whether it is integer, string, float or any other. But in Python you don't have to do this. Just pick the name of variable and assign the value. The type of variable is automatically detected in Python. Python is smart right.
We can even change the data type of variable after they have been set. Suppose you make a varable x and assign the integer value to it, but after some time you are giving string value to the same variable then the type of variable will be change from int to string. I told you Python is smart.
For example :
x = 2 ⇒ Here x is integer.
x = 'hello' ⇒ Here it is converted into String.
Some rules to make variable in Python :
- Variable name should start with either letter or underscore. It can not start with any number.
- Variable name can contain alpha numeric characters and underscore ( a-zA-Z, 0-9, _ ).
- Variable name are case sensitive for example, name and NAME are two different variables.
To assign the value to any variable = (equal to) sign is used. In python we can make multiple variables in single line.
a = b = c = 100
print(a) # output : 100
print(b) # output : 100
print(c) # output : 100
x, y, z = 100, 200, 300
print(x) # output : 100
print(y) # output : 200
print(z) # output : 300
Variables are of two types : local and global. Local variable belongs to a particular block of code only, they can not be accessed outside the block. But global variables can be accessed anywhere in the code.
For example the variables declared inside the function can be accessed in that function only, not outside the function. On the other hand, variable declared outside the function can be accessed anywhere in the code.
name = "Harry" #global variable
def printName () : # function
name = "Justin" # local variable
print(name)
printName() # output : Justin
print(name) # output : Harry
If you want to make a global variable inside the function, you can use global keyword for that variable. Suppose you make a variable outside the function and inside the function you want to make the variable with same name and global, we can do this like :
x = "Harry"
def printName():
global x
x = "Justin"
print(x)
printName() #output : Justin
print(x) #output : Justin
It is considered as best practice to declare the variable in lowercase. You should avoid to make the variable name same as any keyword or reserved word in Python.
Comments
Post a Comment