# Variable declaration and assignment
x = 5
name = "John"
Here, x is a variable holding an integer value (5) and name is a variable holding a string ("John").
Naming Conventions
Following consistent naming conventions is essential for the writing clean and readable code. Python variables should adhere to the following guidelines:- Start with a letter (a-z, A-Z) or an underscore (_).
- Subsequent characters can include letters, numbers and underscores.
- Avoid using reserved keywords like if, else, for etc.
user_name = "Alice"
Data Types
Python supports various data types and variables can hold values of different types. Common data types include:- int: Integer values (e.g. 42)
- float: Floating-point values (e.g. 3.14)
- str: String values (e.g. "Hello, World!")
- bool: Boolean values (True or False)
- list: Ordered collection of values
- tuple: Immutable ordered collection
- dict: Key-value pairs
- set: Unordered collection of unique values
age = 25 # int
height = 5.9 # float
message = "Hello" # str
is_student = True # bool
my_list = [1, 2, 3] # list
my_tuple = (4, 5, 6) # tuple
my_dict = {"key": "value"} # dict
my_set = {1, 2, 3} # set
Scope of Variables
Understanding variable scope is crucial for preventing naming conflicts and ensuring the correct usage of variables. In Python, variables have either local or global scope.Local Scope: The Variables defined within a function or block have local scope and are only accessible within that scope.
def my_function():
local_variable = "I am local"
print(local_variable)
my_function()
print(local_variable) # This will raise an error
Global Scope: The Variables defined outside any function or block have global scope and can be accessed throughout the program.
global_variable = "I am global"
def another_function():
print(global_variable)
another_function()
print(global_variable) # This will print "I am global"
Best Practices
To write clean and maintainable code consider the following best practices:- Use descriptive variable names for better readability.
- Avoid using single-letter variables except in cases like loop counters (i, j).
- Initialize variables before using them to avoid potential errors.
user_age = 30
total_users = 100
# Avoid single-letter variable names
a = 5 # Less readable