Keywords and Identifiers

In this lesson, we will discuss Keywords and Identifiers in Python. These are fundamental concepts that form the building blocks of Python programming.


Keywords in Python

Keywords are reserved words in Python that have a specific meaning and function. These words are part of the language syntax and cannot be used as identifiers (e.g., variable or function names).

Key Characteristics of Keywords:

  • Keywords are predefined and have a fixed meaning.
  • Keywords are case-sensitive (e.g., True is a keyword, but true is not).
  • Python provides a list of keywords that vary slightly between versions.

List of Common Python Keywords:

Here are some of the most commonly used keywords:

False, None, True, and, as, assert, async, await, break, class, continue, def, del, elif, else, except, finally, for, from, global, if, import, in, is, lambda, nonlocal, not, or, pass, raise, return, try, while, with, yield

Example of Keywords:

# Using some keywords in a program
if True:  # True is a keyword
    print("This is a true statement")
def my_function():  # def is a keyword
    pass  # pass is a keyword used as a placeholder

Identifiers in Python

An identifier is the name used to identify variables, functions, classes, modules, or other objects in a program.

Rules for Writing Identifiers:

  1. Allowed Characters:

    • Identifiers can consist of letters (a-z, A-Z), digits (0-9), and underscores (_).
    • They cannot start with a digit.
  2. Case Sensitivity:

    • Python identifiers are case-sensitive. For example, variable, Variable, and VARIABLE are all different.
  3. Reserved Words:

    • Identifiers cannot be the same as Python keywords.
  4. Special Characters:

    • Identifiers cannot contain special characters like @, $, %, etc.
  5. Length:

    • There is no length limit, but it is recommended to use concise yet descriptive names.

Examples of Valid Identifiers:

# Examples of valid identifiers
my_variable = 10  # Valid
result_2 = 20  # Valid
MyClass = "Python Class"  # Valid
calculate_total = 100.50  # Valid

Examples of Invalid Identifiers:

# Examples of invalid identifiers
2variable = 10  # Invalid: Cannot start with a digit
my-variable = 20  # Invalid: Hyphen is not allowed
class = "Test"  # Invalid: 'class' is a keyword

Best Practices for Naming Identifiers

  1. Use Descriptive Names:

    • Choose meaningful names that convey the purpose of the variable, function, or class.

    Example:

    score = 95  # Describes the purpose of the variable
    
  2. Follow Naming Conventions:

    • Use snake_case for variable and function names.
    • Use PascalCase for class names.

    Example:

    my_variable = 10  # snake_case for variables
    class MyClass:  # PascalCase for classes
        pass
    
  3. Avoid Single-Letter Names:

    • Avoid using single letters like x, y, or z unless in loops or mathematical contexts.
  4. Avoid Confusion with Keywords:

    • Do not use identifiers that resemble keywords or built-in functions.

    Example:

    # Avoid using built-in names like 'list', 'str', 'int' as identifiers
    my_list = [1, 2, 3]  # Preferred
    list = [1, 2, 3]  # Avoid this
    
Deep Dive

Naming Conventions in Python

When naming variables, functions, classes, or other identifiers, choosing a consistent naming style improves the readability and maintainability of your code. Below are common naming conventions used in programming, including Python:

  1. snake_case:
    All lowercase letters with words separated by underscores.
    Example: my_variable_name

  2. camelCase:
    The first word is lowercase, and subsequent words are capitalized.
    Example: myVariableName

  3. PascalCase (or UpperCamelCase):
    All words are capitalized with no separators.
    Example: MyVariableName

  4. SCREAMING_SNAKE_CASE:
    All uppercase letters with words separated by underscores, typically used for constants.
    Example: MAX_LIMIT

  5. UPPERFLATCASE:
    All uppercase letters with no separators.
    Example: MYVARIABLENAME

  6. kebab-case (not valid in Python):
    Words are separated by hyphens. This style is commonly used in URLs or CSS but not in Python.
    Example: my-variable-name

  7. flatcase:
    All lowercase letters with no separators.
    Example: myvariablename

  8. Pascal_Snake_Case:
    A mix of PascalCase and snake_case. Words are capitalized and separated by underscores.
    Example: My_Variable_Name

  9. camel_Snake_Case:
    A mix of camelCase and snake_case.
    Example: my_Variable_Name

  10. Train-Case (not valid in Python):
    Similar to PascalCase but with hyphens instead of spaces.
    Example: My-Variable-Name

  11. COBOL-CASE (not valid in Python):
    Similar to SCREAMING_SNAKE_CASE but with hyphens instead of underscores.
    Example: MY-VARIABLE-NAME

Python Recommendations:

  • Follow snake_case for variables, functions, and module names.
  • Use PascalCase for class names.
  • Reserve SCREAMING_SNAKE_CASE for constants.

Adhering to these conventions ensures your code is clean, standardized, and easy for others to understand.


Task

Practice: Keywords and Identifiers

Objective: Write a Python script to explore and practice keywords and identifiers.

  1. Create a Python Script:

    • Name the file keywords_and_identifiers.py.
  2. Experiment with Keywords:

    • Write a script using at least 5 different Python keywords in a meaningful way.

    Example:

    # Example using Python keywords
    for i in range(3):
        if i % 2 == 0:
            print("Even number")
        else:
            print("Odd number")
    
  3. Create Valid Identifiers:

    • Define variables, functions, and classes with valid names.

    Example:

    my_variable = 10
    def calculate_sum(a, b):
        return a + b
    class MyClass:
        pass
    
  4. Demonstrate Invalid Identifiers:

    • Intentionally use invalid identifiers and observe the errors.

    Example:

    # Invalid identifiers
    123name = "Alice"  # SyntaxError
    my-variable = 50  # SyntaxError
    

Understanding keywords and identifiers is crucial for writing clean and error-free Python code. With this knowledge, you can now create meaningful and valid names for your Python objects while avoiding reserved words!

Copyright © 2025 Devship. All rights reserved.

Made by imParth