Declaring Variables and Naming Conventions
π·οΈ Python Basics: Syntax, Variables, and Types / Variables and Assignment
π§ Context Introduction
Variables are the building blocks of any Python program. Think of them as labeled containers that store dataβnumbers, text, lists, or more complex objects. For engineers coming from infrastructure or operations backgrounds, understanding how Python handles variables is essential for writing automation scripts, configuration management tools, or monitoring solutions. This guide covers the fundamentals of declaring variables and the naming conventions that keep your code clean, readable, and maintainable.
βοΈ What Is a Variable in Python?
A variable is a name that refers to a value stored in memory. Unlike some other languages, Python does not require you to declare the type of a variable explicitlyβit is inferred automatically when you assign a value.
Key characteristics:
- Variables are created the moment you assign a value to them.
- Python is dynamically typed, meaning the same variable can hold different types of data over its lifetime.
- Variable names are case-sensitive (e.g., myVar and myvar are different variables).
π οΈ Declaring Variables: Basic Syntax
Declaring a variable in Python is straightforward. Use the assignment operator = to bind a name to a value.
Basic examples:
- name = "server01" creates a variable called name holding the string "server01".
- cpu_cores = 8 creates a variable called cpu_cores holding the integer 8.
- memory_gb = 16.0 creates a variable called memory_gb holding the float 16.0.
- is_active = True creates a variable called is_active holding the boolean True.
Multiple assignments in one line:
- x, y, z = 10, 20, 30 assigns 10 to x, 20 to y, and 30 to z in a single line.
Assigning the same value to multiple variables:
- a = b = c = 0 assigns 0 to all three variables a, b, and c.
π Naming Conventions: Best Practices
Python has a style guide called PEP 8 that recommends specific naming conventions. Following these conventions makes your code more readable and consistent, especially when collaborating with other engineers.
General rules for variable names:
- Names must start with a letter (aβz, AβZ) or an underscore (_).
- The rest of the name can contain letters, digits (0β9), and underscores.
- Names cannot contain spaces or special characters like @, $, %.
- Names are case-sensitive.
- Avoid using Python reserved keywords (e.g., if, for, while, class, import) as variable names.
Recommended naming styles:
| Style | Example | When to Use |
|---|---|---|
| snake_case | server_name, cpu_usage, total_memory | Standard for variables, functions, and module names |
| UPPER_CASE | MAX_RETRIES, DEFAULT_TIMEOUT, API_KEY | Constants (values that should not change) |
| CamelCase | ServerConfig, NetworkMonitor, LogParser | Class names only |
| _single_leading_underscore | _private_var, _internal_value | Internal or "private" variables (convention only) |
| __double_leading_underscore | __private_attribute | Name mangling in classes (advanced use) |
π΅οΈ Common Mistakes and How to Avoid Them
Mistake 1: Using reserved keywords as variable names
- β class = "web-server" (invalid β class is a reserved keyword)
- β server_class = "web-server" (valid)
Mistake 2: Starting a variable name with a number
- β 1st_server = "web01" (invalid)
- β first_server = "web01" or server_1 = "web01" (valid)
Mistake 3: Using spaces in variable names
- β server name = "web01" (invalid)
- β server_name = "web01" (valid)
Mistake 4: Confusing variable reassignment with type changes
- port = 8080 (port is an integer)
- port = "8080" (port is now a string β valid but can cause bugs if you expect an integer)
π§ͺ Practical Examples for Engineers
Example 1: Storing server configuration
- hostname = "prod-db-01"
- ip_address = "10.0.1.50"
- port = 5432
- is_primary = True
Example 2: Tracking resource metrics
- cpu_percent = 75.3
- memory_used_mb = 4096
- disk_usage_gb = 250
- network_rx_bytes = 1024000
Example 3: Using constants for configuration
- MAX_CONNECTIONS = 100
- DEFAULT_TIMEOUT_SECONDS = 30
- LOG_FILE_PATH = "/var/log/app.log"
β Summary Checklist for Variable Declaration
- [ ] Use snake_case for regular variable names.
- [ ] Use UPPER_CASE for constants.
- [ ] Start names with a letter or underscore, never a digit.
- [ ] Avoid reserved keywords.
- [ ] Keep names descriptive but concise (e.g., cpu_usage instead of cu).
- [ ] Be consistent with naming across your entire codebase.
π Next Steps
Now that you understand how to declare variables and follow naming conventions, the next topic in this series will cover Python Data Types β exploring strings, numbers, booleans, and how Python determines types automatically. This knowledge will help you write more precise and reliable automation scripts.
Variables store values in memory so engineers can reuse data throughout their code.
π’ Example 1: Declaring a simple variable with a value
This example shows how to assign a number to a variable name.
engineer_count = 5
print(engineer_count)
π€ Output: 5
π΅ Example 2: Declaring multiple variables on separate lines
This example demonstrates declaring two different variables independently.
team_name = "Platform"
team_size = 12
print(team_name)
print(team_size)
π€ Output: Platform
π€ Output: 12
π‘ Example 3: Using snake_case naming convention
This example shows the standard naming style for variables in Python.
max_temperature_celsius = 85
sensor_reading_voltage = 3.3
print(max_temperature_celsius)
print(sensor_reading_voltage)
π€ Output: 85
π€ Output: 3.3
π Example 4: Variable names with underscores for readability
This example demonstrates how underscores improve clarity in long variable names.
production_server_count = 10
staging_server_count = 3
total_servers = production_server_count + staging_server_count
print(total_servers)
π€ Output: 13
π΄ Example 5: Reassigning a variable to a new value
This example shows that variables can hold different values over time.
build_status = "pending"
print(build_status)
build_status = "completed"
print(build_status)
π€ Output: pending
π€ Output: completed
π£ Example 6: Declaring variables with different data types
This example shows that variables can store strings, integers, and floats.
project_name = "Deploy Pipeline"
version_number = 2
deployment_time_seconds = 45.7
print(project_name)
print(version_number)
print(deployment_time_seconds)
π€ Output: Deploy Pipeline
π€ Output: 2
π€ Output: 45.7
βͺ Example 7: Invalid variable names that cause errors
This example shows what happens when engineers use illegal variable names.
# 1st_attempt = 100 # This would cause an error β starts with a number
first_attempt = 100
print(first_attempt)
π€ Output: 100
Comparison Table
| Naming Rule | Valid Example | Invalid Example |
|---|---|---|
| Start with letter or underscore | engineer_id |
1engineer |
| Use only letters, numbers, underscores | build_time_ms |
build-time-ms |
| Case-sensitive | Total and total are different |
Total and total |
| No Python keywords | status_code |
print (keyword) |
| Use snake_case for readability | max_retry_count |
maxretrycount |
π§ Context Introduction
Variables are the building blocks of any Python program. Think of them as labeled containers that store dataβnumbers, text, lists, or more complex objects. For engineers coming from infrastructure or operations backgrounds, understanding how Python handles variables is essential for writing automation scripts, configuration management tools, or monitoring solutions. This guide covers the fundamentals of declaring variables and the naming conventions that keep your code clean, readable, and maintainable.
βοΈ What Is a Variable in Python?
A variable is a name that refers to a value stored in memory. Unlike some other languages, Python does not require you to declare the type of a variable explicitlyβit is inferred automatically when you assign a value.
Key characteristics:
- Variables are created the moment you assign a value to them.
- Python is dynamically typed, meaning the same variable can hold different types of data over its lifetime.
- Variable names are case-sensitive (e.g., myVar and myvar are different variables).
π οΈ Declaring Variables: Basic Syntax
Declaring a variable in Python is straightforward. Use the assignment operator = to bind a name to a value.
Basic examples:
- name = "server01" creates a variable called name holding the string "server01".
- cpu_cores = 8 creates a variable called cpu_cores holding the integer 8.
- memory_gb = 16.0 creates a variable called memory_gb holding the float 16.0.
- is_active = True creates a variable called is_active holding the boolean True.
Multiple assignments in one line:
- x, y, z = 10, 20, 30 assigns 10 to x, 20 to y, and 30 to z in a single line.
Assigning the same value to multiple variables:
- a = b = c = 0 assigns 0 to all three variables a, b, and c.
π Naming Conventions: Best Practices
Python has a style guide called PEP 8 that recommends specific naming conventions. Following these conventions makes your code more readable and consistent, especially when collaborating with other engineers.
General rules for variable names:
- Names must start with a letter (aβz, AβZ) or an underscore (_).
- The rest of the name can contain letters, digits (0β9), and underscores.
- Names cannot contain spaces or special characters like @, $, %.
- Names are case-sensitive.
- Avoid using Python reserved keywords (e.g., if, for, while, class, import) as variable names.
Recommended naming styles:
| Style | Example | When to Use |
|---|---|---|
| snake_case | server_name, cpu_usage, total_memory | Standard for variables, functions, and module names |
| UPPER_CASE | MAX_RETRIES, DEFAULT_TIMEOUT, API_KEY | Constants (values that should not change) |
| CamelCase | ServerConfig, NetworkMonitor, LogParser | Class names only |
| _single_leading_underscore | _private_var, _internal_value | Internal or "private" variables (convention only) |
| __double_leading_underscore | __private_attribute | Name mangling in classes (advanced use) |
π΅οΈ Common Mistakes and How to Avoid Them
Mistake 1: Using reserved keywords as variable names
- β class = "web-server" (invalid β class is a reserved keyword)
- β server_class = "web-server" (valid)
Mistake 2: Starting a variable name with a number
- β 1st_server = "web01" (invalid)
- β first_server = "web01" or server_1 = "web01" (valid)
Mistake 3: Using spaces in variable names
- β server name = "web01" (invalid)
- β server_name = "web01" (valid)
Mistake 4: Confusing variable reassignment with type changes
- port = 8080 (port is an integer)
- port = "8080" (port is now a string β valid but can cause bugs if you expect an integer)
π§ͺ Practical Examples for Engineers
Example 1: Storing server configuration
- hostname = "prod-db-01"
- ip_address = "10.0.1.50"
- port = 5432
- is_primary = True
Example 2: Tracking resource metrics
- cpu_percent = 75.3
- memory_used_mb = 4096
- disk_usage_gb = 250
- network_rx_bytes = 1024000
Example 3: Using constants for configuration
- MAX_CONNECTIONS = 100
- DEFAULT_TIMEOUT_SECONDS = 30
- LOG_FILE_PATH = "/var/log/app.log"
β Summary Checklist for Variable Declaration
- [ ] Use snake_case for regular variable names.
- [ ] Use UPPER_CASE for constants.
- [ ] Start names with a letter or underscore, never a digit.
- [ ] Avoid reserved keywords.
- [ ] Keep names descriptive but concise (e.g., cpu_usage instead of cu).
- [ ] Be consistent with naming across your entire codebase.
π Next Steps
Now that you understand how to declare variables and follow naming conventions, the next topic in this series will cover Python Data Types β exploring strings, numbers, booleans, and how Python determines types automatically. This knowledge will help you write more precise and reliable automation scripts.
Interactive Views
You are currently in π All-in-One mode. Use the tabs at the top to switch to π Theory Only or π» Code Only views.
Variables store values in memory so engineers can reuse data throughout their code.
π’ Example 1: Declaring a simple variable with a value
This example shows how to assign a number to a variable name.
engineer_count = 5
print(engineer_count)
π€ Output: 5
π΅ Example 2: Declaring multiple variables on separate lines
This example demonstrates declaring two different variables independently.
team_name = "Platform"
team_size = 12
print(team_name)
print(team_size)
π€ Output: Platform
π€ Output: 12
π‘ Example 3: Using snake_case naming convention
This example shows the standard naming style for variables in Python.
max_temperature_celsius = 85
sensor_reading_voltage = 3.3
print(max_temperature_celsius)
print(sensor_reading_voltage)
π€ Output: 85
π€ Output: 3.3
π Example 4: Variable names with underscores for readability
This example demonstrates how underscores improve clarity in long variable names.
production_server_count = 10
staging_server_count = 3
total_servers = production_server_count + staging_server_count
print(total_servers)
π€ Output: 13
π΄ Example 5: Reassigning a variable to a new value
This example shows that variables can hold different values over time.
build_status = "pending"
print(build_status)
build_status = "completed"
print(build_status)
π€ Output: pending
π€ Output: completed
π£ Example 6: Declaring variables with different data types
This example shows that variables can store strings, integers, and floats.
project_name = "Deploy Pipeline"
version_number = 2
deployment_time_seconds = 45.7
print(project_name)
print(version_number)
print(deployment_time_seconds)
π€ Output: Deploy Pipeline
π€ Output: 2
π€ Output: 45.7
βͺ Example 7: Invalid variable names that cause errors
This example shows what happens when engineers use illegal variable names.
# 1st_attempt = 100 # This would cause an error β starts with a number
first_attempt = 100
print(first_attempt)
π€ Output: 100
Comparison Table
| Naming Rule | Valid Example | Invalid Example |
|---|---|---|
| Start with letter or underscore | engineer_id |
1engineer |
| Use only letters, numbers, underscores | build_time_ms |
build-time-ms |
| Case-sensitive | Total and total are different |
Total and total |
| No Python keywords | status_code |
print (keyword) |
| Use snake_case for readability | max_retry_count |
maxretrycount |