Skip to main content

Python Identifiers

Python Identifiers

Identifiers are names given to variables, functions, classes, modules, and other objects in Python. They help us reference these objects in our code.


Rules for Python Identifiers

  • Must start with a letter (a-z, A-Z) or an underscore (_).
  • Can contain letters, numbers (0-9), and underscores.
  • Cannot be a Python keyword (like if, for, while, etc.).
  • Are case-sensitive (myVar and myvar are different).

Valid Identifiers

name = "Alice"       # Starts with a letter  
_age = 25            # Starts with an underscore  
MAX_VALUE = 100      # Constants are usually UPPER_CASE  
first_name = "Dave"  # Uses underscore (hyphens are invalid) 
user1 = "Bob"        # Contains a number (but doesn't start with it)   

# Function name with underscore  
def greet_user(username):  
    print(f"Hello, {username}!")  

# Class name in PascalCase
class Car:
    def __init__(self, model):  
        self.model = model  # Instance variable  
  

Explanation:

  • name - A simple variable name that starts with a letter.
  • _age - Valid because it starts with an underscore.
  • MAX_VALUE - Constants are usually written in uppercase.
  • first_name - Uses underscores for readability.
  • user1 - Contains a number but does not start with one.
  • greet_user - Function names typically use underscores.
  • Car - Follows PascalCase convention for class names.

Invalid Identifiers

2name = "Charlie"  
# Starts with a number (SyntaxError)  

class = "Math"  
# Uses a Python keyword "class" (SyntaxError)  

first-name = "Dave"  
# Hyphen is not allowed (SyntaxError)  

$price = 10.99  
# Special characters not allowed (SyntaxError)  

user@name = "Eve"  
# @ symbol is invalid (SyntaxError)  

def 1st_func():  
    pass  
# Function name starts with a number (SyntaxError)  
  

Explanation:

  • 2name - Starts with a number, which is not allowed.
  • class - Cannot use a reserved keyword as an identifier.
  • first-name - Hyphens are not allowed; use underscores instead.
  • $price - Special characters like $ are not allowed.
  • user@name - @ is not a valid identifier character.
  • 1st_func - Cannot start with a number.



Comments