Python Variables and Datatypes
Variable:
A variable is a name given to any storage area or memory location in a program.
In simple words, we can say that a variable is a container that contains some information, and whenever we need that information, we use the name of that container to access it. Let's create a variable:
a = 34 # Variable storing an integer
b = 23.2 # Variable storing real number
Here a and b are variables, and we can use a to access 34 and b to access 23.2. We can also overwrite the values in a and b
Data Types in Python:
Primarily there are the following data types in Python.
1. Integers (
2. Floating point numbers (
3. Strings (
4. Booleans (
5. None: None is literal to describe 'Nothing' in Python
Rules for defining a variable in Python:
A variable name can contain alphabets, digits, and underscores (_). For E.g. : demo_xyz = ‘It’s a string variable’
A variable name can only start with an alphabet and underscore.
It can't start with a digit. For example, 5harry is illegal and not allowed.
No white space is allowed to be used inside a variable name.
Also, reserved keywords are not recommended to be used as variable names.
Examples of few valid variable names are harry, _demo, de_mo, etc.
Python is a fantastic language that automatically identifies the type of data for us. It means we need to put some data in a variable, and Python automatically understands the kind of data a variable is holding. Cool, isn't it?
Have a look at the code below:
# Variable in Python:
abc = "It's a string variable"
_abcnum = 40 # It is an example of int variable
abc123 = 55.854 # It is an example of float variable
print(_abcnum + abc123) # This will give sum of 40 + 55.854
type() Function in Python:
type() function is a function that allows a user to find data type of any variable. It returns the data type of any data contained in the variable passed to it.Have a look at the code below, which depicts the use of type function:
# type() Function in Python:
harry = "40"
demo = 55.5
demo = 40
print (type(harry)) #It will give output as string type
demo3 = type(demo) #It will return data type as float
print(demo3) #It will print that data type
print(type(demo2)) #It will give output as int type
Note – We can't do numbers with strings arithmetic operations, i.e., we can't add a string to any number. Have a look at the example below:
var1 = "It's a String"
var2 = 5
print(var1+var2) ''' It will give an error as we can't add string to any number. '''
Note – We can add (concatenate) two or more strings, and the strings will be concatenated to return another string. Here is the example showing that:
var1 = "My Name is "
var2 = "Harry"
var3 = var1+var2+" & I am a Good Boy."
print(var1+var2) # It will give output 'My Name is Harry'
print(var3)