Python variables and datatypes

Generally, variables are containers for storing values. A variable is a memory location where you store a value. The value that you have stored may change in the future according to the specifications.

How are variables created in python?

Variables are easily created in python by assigning a value to them.  Every variable in Python is an object. Let's create a variable as follows;

name = "Vincent"

The variable name is created and assigned to a value of ''Vincent". The variable name is the container used for storing the value "Vincent".

Rules for naming a variable in python.

There are important rules we have to consider while declaring a variable in python. These include

  • Variables in Python are case-sensitive. For example, name = "Vincent" is not the same as Name = "John". The variable name starts with lowercase "n" while the other variable Name starts with an uppercase "N". They are the same in English but not in python. 
  • The variable name cannot start with a number. A variable name can only start with a character or an underscore. For example _number = 20 but not 1number = 20.
  • Special characters are prohibited in naming variables examples are  !, @, #, $, %, etc.

Bonus: It is conventional to name variables using the camelcase method. For example schoolName = "Cambridge"

Datatypes in python.

Every value that we declare in python has a data type. Variables can store data of different types. In Python, the data type is set when you assign a value to a variable. Python has the following datatype built in by default.

Numerical data types:

  • Floats: number = 4.598
  • Integer: number = 254
  • Complex: number = 2j

String data types:

text = "Vincent"

Boolean type:

The boolean datatypes are only True and False.

message = True

Sequence types:

  • List: list1 = ["brain", 2, "tongue"]
  • Tuple: tuple1  = ["train", 3, "corn"]

Dictionary types:

dict1 = {"name": "James", "age": 50}

Python set types:

  • Set: set1 = {"train", "silvia", "James"} 
  • frozenset

How to Know the type of any object.

You can get the data type of any object by using the type() function:

name = "Bliss"
age = 30
answer = True
list1 = ["water", "bottles", "spoon"]
tuple1 = ("Milk", "yogurt", "sink")
number = 23.89

print(type(name)) #<class 'str'> string
print(type(age)) #<class 'int'> integer
print(type(answer)) #<class 'bool'> boolean
print(type(list1)) #<class 'list'> list
print(type(tuple1)) #<class 'tuple'> tuple
print(type(number)) # <class 'float'> float