In This Article
Variables in Python are locations inside the computer’s memory where we can store certain values that can be assigned by the user. When we declare a variable with some values the Python interpreter automatically detects its data type. Every value in Python is characterized by different data types like Numbers, List, Tuple, Strings, Dictionary, etc.
Declaring a Variable in Python
Declaring variables in Python and printing them using the print() function can be a very easy task.
city = "Kolkata"
sum = 100
a = 6.10
print(city)
print(sum)
print(a)
The output of this will be:
Kolkata
100
6.10
Here, we can see that we created three variables city, sum & a. Each one of them was of different data types, city was a string, sum was an integer & a was float type of data.
Assigning Multiple Variables in Python
We can assign multiple variables with different values together in a single line in Python.
city,sum,a = "Kolkata",100,6.10
print(city)
print(sum)
print(a)
The output of this will be:
Kolkata
100
6.10
Here, we created three variables in Python in a single line of code. Then we used the print() function to print them out one by one.
Rules for Variables in Python
Python variables are written under a certain set of rules:
- Variables can be a combination of lowercase and uppercase letters, numbers, or underscore( _ ).
- Variables cannot start with a number.
- We cannot use special characters like $, (, * % etc in declaring a variable.
- Variables in Python cannot be named using any Keywords.
- Variables are case-sensitive.
Re-declaring Variables in Python
We can re-declare the value of a variable in Python.
Example:
a = "Kolkata"
print(a)
a = 100
print(a)
The output of this will be:
Kolkata
100
Here, we can see that the variable a was string data type in beginning, and then we changed it to an integer data type.
Local & Global Variables in Python
Two major types of variables in Python are the Local and the Global types.
Example:
x = 5
y = 10
def add(a,b)
sum = a + b
return sum
print(add(x,y))
The output of this will be:
15
Here, we declare two variables x & y in the beginning. These are known as global variables because we can use them anywhere in the Python program. We use a variable named sum inside the add function. This variable cannot be used anywhere else outside the add function. So this makes it a local variable.
Deleting Variables in Python
We can delete a variable in Python using the del keyword.
Example:
a = 100
del a
print(a)
The output of this will be:
Traceback (most recent call last):
File "main.py", line 3, in
print(a)
NameError: name 'a' is not defined
Here, we declared an integer variable and then deleted it using the del keyword. When we tried the print() function, it gave an error.