Variables in python
We can initialise variables in python using =
operators. example:
a = 20
_t = "apples"
var34 = 67
what we cannot do is initialise a variable starting with number and any other symbols you see in your numeric pad except for underscore( _ ).
So following will give you these kind of errors.
3 ="oranges"
>>> SyntaxError: cannot assign to literal
!er =79
>>> SyntaxError: invalid syntax
@fg=67
>>> SyntaxError: invalid syntax
What actually happens when you declare a variable ?
When we say a = 20
. In the core, a
is storing a memory reference to the value 20
not the actual value. Basically we can say that a is storing the memory address where the integer 20 is present. we can check this out by using id()
method.
a = 20
>>> print(id(a))
94664460861344
94664460861344
is the memory address where our value 20
is residing
Did you know python caches the integers in the range of -5 to 256 as part of python compilers optimisation
Data types in python
One major advantage of python is that it is a dynamically typed language. So dynamic type means during the declaration of the variables you do not have to mention the type of the variable. Python compiler automatically during the compilation stage take care of that.
That means i can declare the variable a = 20
and at later point of time we can override it and say a = "apples"
. Python does not restrict that.
Most commonly used data types in python
Integer Type
Any number -ve infinity to +ve infinity except for decimal numbers can be considered as integers
a = 20
print(type(a))
>>>
Float Type
Any number having decimals is considered as floats. Even negative numbers with decimal values
a = 11.7
print(type(a))
>>>
String Type
Any value coming in between two double quotes or two single quotes are considered as strings.
a = "orange"
print(type(a))
>>>
Boolean Type
Boolean data types are binary states. Either True
or False
.
a = True
print(type(a))
>>>
List Type
Lists are arrays, which can contain multiple values of different data types, more here.
a = [20,"apple",45.6]
print(type(a))
>>>
Dictionary Type
Dictionary holds key and value pair. A dictionary can store different data types. Dictionaries can be nested too, more here.
a = {"fruit":"apple"}
print(type(a))
>>>
Bytes Type
There is a b
followed by single or double quotes string, this is represented as bytes.
a = b"orange"
print(type(a))
>>>
Set Type
Sets are like lists but closed with curly brackets. Sets store only unique values in them, more here.
a = {"orange"}
print(type(a))
>>>
Tuple Type
Tuples are represented by closing parenthesis, tuples are immutable, once created we cannot replace the value of the tuples, more here.
a = 20
print(type(a))
>>>