In this article, you will learn about Python variables. A Python variable is a container to store a value of any type. Where Container refers to a single memory location on the system. An assignment operator is used to assign a value to the variable.
Variables in Python are created directly when they are needed in the program. Below is the syntax to create a variable in python.
A=5 Name= "john" Length =4.6
Python variables are not declared by specifying any data type. Their data type is automatically assigned on the bases of the value that is going to store in a variable.
Example 1: How to check the data type of python variables
In python, we can check the data type of any variable by using the type () function.
A = 5 Name = "john" Length = 4.6 print(type(A)) print(type(Name)) print(type(Length))
<class 'int'> <class 'str'> <class 'float'>
Example 2: How to specify the Data type of the python variable
We can check it by using python casting. To do this we can use inbuilt functions int(), float() and str().
A= int(5) Name = str("john") Length = float(4.6)
Rules to writing a variable name in python
- Python variable must start with a letter or underscore
- A variable name cannot start with numbers.
- Variable name only contains alpha-numeric (Aa-Zz, 0-9) and underscore “–”
- They are case sensitive, which means that A and a are two different variable names.
Example 3: Some legal variable names in python
Students Subject2 User_Name logic _age
Example4: Some Illegal variable names in Python
Student Marks 2num Your-name !number
Example 5: Assign a single value to multiple variables in Python
Python gives the permission to assign a single value to multiple variables. Below is the example
a = b = c = 1 print(a) print(b) print(c)
1 1 1
Example 6: Assign multiple values to multiple variables in python
a,b,c = "red", "blue", "green" print(a) print(b) print(c)
red blue green