Variables

VARIABLES & TYPES IN PYTHON


Variables are containers that can hold data values. Variables in Python are dynamically typed, meaning the datatype is inferred from their assigned value.

Python has the following data types built-in by default, in these categories:

  1. Text Type: str
  2. Numeric Types: int, float, complex
  3. Sequence Types: list, tuple, range
  4. Mapping Type: dict
  5. Set Types: set, frozenset
  6. Boolean Type: bool
  7. Binary Types: bytes, bytearray, memoryview
  8. None Type: NoneType

There is a function to check the datatype of a variable or data structure. The command is:

type(variable_name)
'''
  output:
    <class 'datatype'>
'''

It returns the class the variable belongs to.

Why does this return a class?

In Python, datatypes are implemented using classes. There are classes called int, str, float, complex, and more. When we create a variable of a type, we are effectively creating an object of the class of the datatype.

Simple exercise:

a = 12       # int
b = 12.42      # float
c = "Django tutorial"      # str

print("a: ", type(a))
print("b: ", type(b))
print("c: ", type(c))
'''
    output:
        a: <class 'int'>
        b: <class 'float'>
        c: <class 'str'>
'''

How to name Variables and classes ?

In Python, identifiers are user-defined names used to label variables, functions, classes, or modules. They are case-sensitive, meaning `name`, `Name`, and `NAME` are treated as distinct identifiers. This sensitivity allows flexibility but requires careful naming to avoid errors. 

Rules for Naming Identifiers 

  1. Identifiers must start with a letter (A-Z or a-z) or an underscore (_), followed by letters, digits (0-9), or underscores.
  2. They cannot start with a digit or contain special characters like @, #, or -.
  3. Reserved keywords in Python (e.g., if, else, True) cannot be used as identifiers.
  4. Identifiers are case-sensitive. For example, temp and Temp are different.
  5. There is no length limit, but overly long names are discouraged for readability.

Examples of Valid Identifiers

variable1 = 10
_variable = "Python"
var_123 = [1, 2, 3]

Examples of Invalid Identifiers

1variable = 10 # Starts with a digit
var@name = "Python" # Contains special character '@'
if = 5 # Uses a reserved keyword

Checking Identifier Validity

Python provides the str.isidentifier() method to check if a string is a valid identifier. However, it does not account for reserved keywords. To ensure a name is valid, combine it with keyword.iskeyword().

import keyword
def is_valid_identifier(name):
   return name.isidentifier() and not keyword.iskeyword(name)
print(is_valid_identifier("variable")) # True
print(is_valid_identifier("1var")) # False
print(is_valid_identifier("for")) # False

Reserved Classes of Identifiers

Python reserves certain naming conventions:

  1. Single leading underscore (_var): Indicates a private variable.
  2. Double leading and trailing underscores (__init__): Denotes special methods or system-defined names.
  3. Double leading underscores (__var): Used for name mangling to avoid conflicts in subclasses.