Variables and Objects: Python
Variables
Variables are the basic building block of any programming language. In Python everything is object. Variables allow you to attach names to these objects, so you can refer them in future code.
The above statement has an id, type and value. The “=” sign is the assignment operator. You can think of id as where Python stores this object in memory. age is a variable that is assigned to the object. This object has a type, integer, and holds the value 15.
Rebinding Variables
Variables are transferable to other objects. In the above example age was assigned to an integer 15, then it was reassigned to a string “hello”. Changing the type of a variable is easy, but it only confuses you and others while they read and use the code later. So, rebinding the variable is not a good practice.
Naming Variables
- Keywords are reserved for use in Python language constructs, so never use Keywords as variable name. The module keyword has a kwlist attribute, which is a list containing all the current keywords for Python.
- Variable should be lowercase.
- Use an underscore to separate words.
- Do not start with numbers.
- Do not override a built-in function. To find the built-in function type >>>dir(__builtins__)
Objects
The properties of an object is:
- identity:- refers to the object’s location in the computer’s memory. Python has a built-in function called id that tells you the identity of an object.
- type:- the common types of an object are strings, integers, floats, and booleans.
- value:- Many objects are mutable while others are immutable. Mutable objects can change their value in place, but their identity stays the same. Objects that are immutable do not allow you to change their value and their identity changes. In Python, dictionary and list are mutable types. String, tuple, integer and float are immutable type.