Variable in Python
- Variable is a name of storage space which is used to store data.
- Variable value may be changed.
- Mainly variable always contains last value stored to it.
- There is no need to declare a variable in python.
- Variable is created by assigning a value to it.
Variable Initialization
name="SUNAGAR" rollno =205 marks =85.6
- In Above example name rollno and marks are the name of variables.
- Value of name is SUNAGAR, rollno is 205 and marks is 85.6
Printing value of variable
- We can also print the value of a variable using print() function.
#creating variables name="SUNAGAR"
rollno=205 marks=85.6 #printing value of varibales print("Name:",name) print("Roll:",rollno) print("Marks:",marks) """ ***Output*** Name: SUNAGAR Roll: 205 Marks: 85.6 """
Assigning one value to multiple variable
- We can assign a single/one value to multiple variables using single statement in python.
#creating variables a=b=c=90 #printing value of varibales print("a:",a) print("b:",b) print("c:",c) """ ***Output*** a: 90 b: 90 c: 90 """
Assigning multiple values to multiple variables
- We can also assign multiple values to multiple variables using single statement in python.
#creating variables a,b,c=70,80,90 #printing value of varibales print("a:",a) print("b:",b) print("c:",c) """ ***Output*** a: 70 b: 80 c: 90 """
Rules to define a variable
- 1st letter of a variable should be alphabet or underscore(_).
- 1st letter of variable should not be digit.
- After 1st character it may be combination of alphabets and digits.
- Empty spaces are not allowed in variable name.
- Variable name must not be a keyword.
- Variable names are case sensitive for example marks and MARKS are different variables.
Local Variable
- A variable declared within the body of the operate is named native/local variable.
- Local variable may be used only within that operate during which it's defined.
#function definition def add(): #creating variable x=50 y=30 z=x+y print("Add=",z) #Calling funtion add() #This line will raise an error #because x is local variable #and it can't be accessed #outside function print(x) """ ***Output*** Add= 80 NameError: name 'x' is not defined """
Global Variable
- variable which is defined outside a function is called global variable.
- Global variable can be used anywhere in the program.
#creating global variable x=50 y=30 def add(): #accessing global variable #inside a function print("Inside function Sum=",x+y) #Calling funtion add() #accessing global variable #outside a function print("Outside function Sum=",x+y) """ ***Output*** Inside function Sum= 80 Outside function Sum= 80 """
Local and Global variable with same name
#creating global variable x=50 def add(): x=20 # this line will print 20 print("Inside function x=",x) #Calling funtion add() #this line will print 50 print("Outside function x=",x) """ ***Output*** Inside function x= 20 Outside function x= 50 """