Pages

Sunday, July 28, 2024

Python : About : Variables

 Variables in Python

Variables are used to:

  • Name an object.
  • Remind us about the usability of an object.
  • Allow us to reuse same object in multiple places in our code.

When we say: 

amount = 4543

we are assigning the label amount to the object 4543
OR
We are saying that amount is a reference to the object 4543







Why do we call amount in the above example as a variable?

Ans: Because the object to which amount is pointing to can change, or in case of mutable objects the state of object can change.
















Note: in the above example, memory address of variable amount is same and the state of list it is referring to has changed.

How does variable assignment happen in Python?

Example is shown as below:









So, in Python RHS is evaluated first and then the resultant is assigned to the LHS

















In the example shown above the RHS is evaluated first and then is assigned to LHS.


Variable Naming:

  • Are case sensitive.
  • Must follow certain rules:
    • Start with letter (a-z A-Z) or a underscore (_).
    • Not Start with numbers.
    • Cannot be reserved words like True, False, if, def, and, or ….  
  • Should follow certain conventions as defined in PEP8 Style Guide:


Terminology followed to name a variable:

  • Camel case --> Separate words are distinguished by upper case letters.
    • Example:  minBalance
  • Snake case --> separate words are distinguished by underscores.
    • Example:  min_balance


Mostly Snake case is used in Python programming paradigm.




1 comment:

Python : About : Variables

  Variables in Python Variables are used to: Name an object. Remind us about the usability of an object. Allow us to reuse same object in mu...