In this article, you will learn about Python variables and data types. 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.
Code
A = 5
Name = "john"
Length = 4.6
print(type(A))
print(type(Name))
print(type(Length))
Output
<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().
Syntax
A= int(5)
Name = str("john")
Length = float(4.6)
Rules for writing a variable name in Python
- Python variables 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 permission to assign a single value to multiple variables. Below is the example
a = b = c = 1
print(a)
print(b)
print(c)
Output
1
1
1
Example 6: Assign multiple values to multiple variables in Python
Code
a,b,c = "red", "blue", "green"
print(a)
print(b)
print(c)
Output
red
blue
green