Variable Assignment in Python
In last chapter, we learned about numbers and how to use it. But, it will be nice if we are able to store it somewhere and use it. So, Variable Assignment come into picture.
for example,
index = 2 ; means value 2 is stored into index variable.
Let’s see rules to follow while assigning variable:
- names should be in lowercase
- Must begin with a letter (a — z, A — B) or underscore (_)
- Other characters can be letters, numbers or _
- avoid using special names for variable such as ‘list’ or ‘str’ because these are in-built keywords in Python
Python uses Dynamic Typing, means you can reassign variable to different data types.
This provides flexibility to python and is different from other languages which are Statically-typed.
let’s see an example:
roll_number = 2
roll_number = [“india”, “england”]
this is OKAY in Python but other languages will not accept it.
Since, we are not mentioning the type for variable it is difficult to remember the data type of the variable. To get the type of variable, we can use:
>>> width = 20
>>> type(width)
int
Pros of Dynamic Typing:
- You don’t need to put data type resulting in faster development time
- Flexibility
Cons of Dynamic Typing:
- May result into unexpected data types
- You have to be aware of type()
- You have to be aware of type()