Before understanding Python Variables let’s first discuss what variables means?
What are variables?
Variables are used to store the values in programming languages. Values are like integer, decimal, Boolean, string etc. every language has its own way to create variables. So we will discuss here variables in Python and how we can create Python variables and use it.
If you want to know how to create Python variable, then it’s very easy. You have to just write the name of the variable and assign the value to it that’s it. You are done with python variable.
Example: Let’s take example
age = 20 print (age)
here age is variable in python whose value is 20. When we run this program we will get 20.
Unlike other language, Python variables are very easy to declare and use, as they don’t require any data type. E.g. in java if variable will hold integer value then it will have defined as int age, but in python its nothing like that. We have to simply write the variable name only, no data type required here. Which make python variables very easy to create and use.
Points to remember about Python variables:
- Python Variables are case-sensitive. It means variable age is different and Age will be different variable.
Here age and Age are two different variables.
- Python variable can only be start with letter and underscore (_). Variable cannot be start with any special character other than underscore.
spoon=20 – valid
_tree = 20 – valid
(glass = 20 – invalid
- Python variable cannot be start with number, but number in-between is allowed.
1age = 20 –Invalid
Age123 = 20- valid
Examples of Python Variables
Let’s see some examples of python Variable
- Store number value in variable
- Store decimal value in variable
- Store String value in variable
Name= "Python" print(Name)
Concatenation of variables: we can concatenate two or more variables.
greeting="hi! " Name= "Python" print (greeting + Name)
Here we have concatenate two python variable greeting and Name
Important point: String to string variables, number to number, decimal to decimal, number to decimal variable we can concatenate directly, but for string and number numbers we have to type cast them
greeting="hi!" Name= "Python" age=30 print (greeting + Name + str(age))
Here age is number and other two variables are String, so before concatenate the number, we have to type cast into String.
If we don’t typecast age to String, we will get following error:
TypeError: must be str, not int
Get type of Python variable
In Python, we can also get the type of the variable means what type of variable it is. Its whether number, or String etc.
There is a type() function in python, which determine the type of variable in python.
Example: let’s take the same example, now we will find the data type of variables
greeting="hi!" Name= "Python" age=30 print (type(greeting)) print (type(age))
Output will be
Variable greeting is of type string and age variable is of type integer (number).