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:
- Text Type: str
- Numeric Types: int, float, complex
- Sequence Types: list, tuple, range
- Mapping Type: dict
- Set Types: set, frozenset
- Boolean Type: bool
- Binary Types: bytes, bytearray, memoryview
- 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
- Identifiers must start with a letter (A-Z or a-z) or an underscore (_), followed by letters, digits (0-9), or underscores.
- They cannot start with a digit or contain special characters like @, #, or -.
- Reserved keywords in Python (e.g., if, else, True) cannot be used as identifiers.
- Identifiers are case-sensitive. For example, temp and Temp are different.
- 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:
- Single leading underscore (_var): Indicates a private variable.
- Double leading and trailing underscores (__init__): Denotes special methods or system-defined names.
- Double leading underscores (__var): Used for name mangling to avoid conflicts in subclasses.