Ojasa Mirai

Ojasa Mirai

Python

Loading...

Learning Level

🟒 BeginnerπŸ”΅ Advanced
What are Variables?Numbers β€” Integers and FloatsNumber OperationsStrings β€” Creating and Using TextString FormattingBooleans and NoneType ConversionGetting User InputBest Practices
Python/Variables Data Types/What Are Variables

🏷️ What are Variables? β€” Advanced Naming, Conventions, and Style

Professional Python code follows PEP 8 style guidelines and uses consistent, meaningful naming conventions. Variables are more than just containersβ€”they're a form of communication with other programmers. Understanding naming conventions, scope implications, and how variables work internally helps you write maintainable, professional-grade code that follows Python culture and best practices.


🎯 PEP 8 Style Guidelines

PEP 8 is Python's official style guide that standardizes how Python code should be written. Following PEP 8 ensures consistency across projects and makes collaboration smoother. The naming conventions are strict: use snake_case for variables/functions, UPPER_CASE for constants, and CapitalCase for classes.

# βœ… PEP 8 Compliant
# Constants - UPPER_CASE
MAX_RETRIES = 3
DEFAULT_TIMEOUT = 30
PI = 3.14159

# Variables - snake_case
user_name = "Alice"
customer_age = 25
is_premium_member = True

# Functions - snake_case
def calculate_total_price():
    pass

def validate_email_address(email):
    pass

# Classes - CapitalCase (PascalCase)
class UserAccount:
    pass

class DataProcessor:
    pass

πŸ” Meaningful Naming Strategies

Good names are self-documenting. Instead of vague names, use specific, descriptive terms that explain the variable's purpose, type, and scope. Use Boolean prefixes like is_, has_, can_ to make flags obvious. Avoid misleading names that suggest different behavior than actual.

# Specific and clear
user_authentication_token = "abc123..."
database_connection_timeout_seconds = 30
is_payment_processing_enabled = True
has_user_verified_email = False
can_user_delete_post = True

# Boolean naming patterns
users_list = [...]      # Hint: plural means collection
is_active = True        # Hint: is_ prefix means boolean
has_permission = True   # Hint: has_ means boolean
can_proceed = False     # Hint: can_ means boolean

# Method names indicate action
def get_user_profile():
    pass

def set_user_email(email):
    pass

def validate_credit_card(card_number):
    pass

def process_payment_request():
    pass

πŸ” Variable Scope and Naming

Python uses UPPER_CASE for constants and has conventions for private variables (leading underscore). Understanding scope and using naming to indicate visibility level makes large codebases more manageable. Private variables (prefixed with _) indicate internal use, while public names have no prefix.

# Module-level constants
API_BASE_URL = "https://api.example.com"
DATABASE_HOST = "localhost"
MAX_LOGIN_ATTEMPTS = 5

# Public module variables
user_sessions = {}
active_connections = []

# Private module variables (internal use only)
_internal_cache = {}
_debug_log = []

# Class-level examples
class User:
    MAX_USERNAME_LENGTH = 50     # Class constant
    DEFAULT_ROLE = "user"        # Class constant

    def __init__(self, name):
        self.username = name                 # Public attribute
        self._hashed_password = None         # Private attribute
        self.__secret_key = "..."            # Name-mangled (very private)

πŸ“ Naming Anti-Patterns to Avoid

Avoid names that mislead about the variable's type or purpose. Don't use names that shadow built-in functions or module names. Avoid abbreviations unless they're standard in your domain, and never use single letters (except i, j, k in loops).

# ❌ Anti-patterns

# Misleading names
user_list = "John"               # Not a list!
total_price = [10.5, 20.3]       # Not a number!
is_valid = "yes"                 # Not a boolean!

# Shadowing built-ins
list = [1, 2, 3]                 # Shadows built-in list()!
dict = {"a": 1}                  # Shadows built-in dict()!
str = "hello"                    # Shadows built-in str()!

# Too abbreviated
usr = "Alice"                    # Abbreviation unclear
calc_total = 100                 # Could be anything
proc_data()                      # What does it process?

# Single letters (except loops)
x = 25                           # What is x?
y = "hello"                      # What is y?

🎯 Consistency Across Projects

When working on teams, consistency is crucial. Establish naming patterns and stick with them. This makes code reviews easier and helps new team members understand the codebase quickly. Document your naming conventions in project guidelines.

# Consistent pattern throughout
# Nouns for variables holding data
customer_name = "Alice"
product_price = 99.99
order_status = "pending"

# Verbs for variables holding functions
calculate_total = lambda x: sum(x)
format_currency = lambda x: f"${x:.2f}"

# is_/has_/can_ for booleans
is_verified = True
has_permission = False
can_delete = True

# Consistent collection naming
users = [...]           # List of users
products = {...}        # Dict of products
scores = []             # List of scores

πŸ’‘ Advanced Naming Examples

API Client Class

class APIClient:
    DEFAULT_TIMEOUT = 30           # Class constant
    DEFAULT_RETRIES = 3            # Class constant

    def __init__(self, base_url: str):
        self.base_url = base_url                # Public attribute
        self.session_token = None               # Public attribute
        self._retry_count = 0                   # Private counter
        self.__api_key = "secret"               # Very private

    def authenticate_user(self, credentials):
        """Public method for external use."""
        pass

    def _refresh_token(self):
        """Private method for internal use."""
        pass

Data Processing Function

def process_user_records(
    raw_user_data: list,
    filter_inactive: bool = True,
    sort_by_date: bool = True
) -> list:
    """
    Process and filter user records.

    Args:
        raw_user_data: Unprocessed user records
        filter_inactive: Remove inactive users
        sort_by_date: Sort by creation date

    Returns:
        Processed user records
    """
    validated_users = []

    for user_record in raw_user_data:
        if filter_inactive and not user_record.get("is_active"):
            continue
        validated_users.append(user_record)

    if sort_by_date:
        validated_users.sort(key=lambda x: x["created_at"])

    return validated_users

βœ… Key Takeaways

PracticeRemember
Variablessnake_case (user_name)
ConstantsUPPER_CASE (MAX_RETRIES)
ClassesCapitalCase (UserAccount)
Functionssnake_case (calculate_total)
Booleansis_/has_/can_ prefixes
PrivateLeading underscore (_internal)
MeaningfulNames should explain purpose
ConsistentFollow team conventions
AvoidSingle letters, abbreviations, shadowing

πŸ”— What's Next?

Now that you understand naming conventions, let's dive deep into number types and their internals!

Next: Number Types Deep Dive β†’


Ready to deepen your knowledge? Try advanced challenges or take the quiz


Resources

Python Docs

Ojasa Mirai

Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.

Learn Deep β€’ Build Real β€’ Verify Skills β€’ Launch Forward

Courses

PythonFastapiReactJSCloud

Β© 2026 Ojasa Mirai. All rights reserved.

TwitterGitHubLinkedIn