
Python
Writing code that's easy to read and maintain is just as important as writing code that works. Best practices are conventions and patterns that help you and others understand your code quickly. Following naming standards, using meaningful variable names, choosing appropriate data types, and keeping your code organized makes you a better programmer and makes collaboration easier.
Use descriptive, meaningful names for your variables that clearly explain what they store. Follow Python's naming convention (snake_case): lowercase words separated by underscores. Avoid single-letter names (except for loop counters like i) and cryptic abbreviations that only you understand.
# Clear and descriptive
user_age = 25
customer_email = "alice@email.com"
total_price = 99.99
is_premium_member = True
product_count = 5
# Function names also use snake_case
def calculate_total_cost():
pass
def get_user_age():
pass# Too vague
x = 25
a = "alice@email.com"
tp = 99.99
# Too abbreviated
usr_age = 25
cust_email = "alice@email.com"
# Confusing abbreviations
p = 99.99 # Is this price? Profit? Product?
c = 5 # Count? Category? Cost?Using the right data type makes your code clearer and prevents errors. Use strings for text (names, emails), integers for whole quantities (counts, ages), floats for measurements (prices, heights), and booleans for yes/no values (is_premium, has_license).
# โ
Good - appropriate types
user_name = "Alice" # String for text
user_age = 25 # Integer for whole number
user_height = 5.6 # Float for measurement
is_premium = True # Boolean for flag
# โ Avoid - wrong types
user_name = 25 # Don't store name as number
user_age = "25" # Don't store age as string (harder to calculate)
user_height = "5.6 feet" # Don't mix text with number
is_premium = "yes" # Don't use string for booleanWrite code that's clear enough that someone (including yourself!) can understand it without extensive comments. Use clear variable names and logical organization. Good code explains itself through meaningful names and structure.
# โ Hard to understand - needs comments
p = 99.99
q = 3
d = 0.1
t = p * q * (1 - d)
# Total price with discount
# โ
Clear - explains itself
unit_price = 99.99
quantity = 3
discount_rate = 0.1
total_price = unit_price * quantity * (1 - discount_rate)When you have related data, group it logically in your code. This makes your program easier to follow and shows relationships between variables. Separate unrelated sections with blank lines.
# Good organization - grouped by purpose
print("=== User Information ===")
user_name = "Alice"
user_email = "alice@email.com"
user_age = 25
print("=== Account Status ===")
is_active = True
is_premium = False
created_date = "2023-01-15"
print("=== Address ===")
street = "123 Main St"
city = "New York"
zip_code = "10001"A "magic number" is a mysterious number in your code with no explanation. Instead of using numbers directly, store them in well-named variables. This makes your code clearer and easier to modify later.
# โ Magic numbers - unclear what they mean
weekly_pay = hourly_rate * 40
price_with_tax = price * 1.08
age_group = age // 10
# โ
Clear - meanings explained through variable names
standard_hours_per_week = 40
weekly_pay = hourly_rate * standard_hours_per_week
sales_tax_rate = 0.08
price_with_tax = price * (1 + sales_tax_rate)
age_group_size = 10
age_group = age // age_group_sizeKeep your code formatted consistently: spacing, indentation, and style. Python cares about indentation for code blocks, and consistent spacing makes code easier to read. Follow PEP 8 (Python's style guide) for professional code.
# Good formatting
name = "Alice"
age = 25
city = "New York"
is_adult = age >= 18
print(f"Name: {name}, Age: {age}, City: {city}")
# Avoid irregular spacing
name="Alice"
age=25
city="New York"
# Inconsistent formatting makes code harder to readAfter writing code with variables, test it with different inputs to make sure it works correctly. This catches errors early and helps you understand how your code behaves in different situations.
# Create a simple program and test it
def calculate_bmi(weight_kg, height_m):
bmi = weight_kg / (height_m ** 2)
return bmi
# Test with different inputs
print(calculate_bmi(70, 1.75)) # Normal case
print(calculate_bmi(50, 1.60)) # Lighter person
print(calculate_bmi(100, 1.80)) # Heavier person# โ
Good code - follows best practices
print("=== Personal Information Manager ===\n")
# Get user information
full_name = input("Enter your full name: ")
birth_year = int(input("Enter your birth year: "))
city = input("Enter your city: ")
is_student = input("Are you a student? (yes/no): ").lower() == "yes"
# Calculate derived information
current_year = 2024
age = current_year - birth_year
student_status = "Student" if is_student else "Professional"
# Display formatted profile
profile = f"""
{full_name.upper()}
{'='*40}
Age: {age} years old
City: {city}
Status: {student_status}
{'='*40}
"""
print(profile)โ
Use descriptive variable names
โ
Use snake_case for variable names
โ
Choose appropriate data types
โ
Avoid magic numbers
โ
Group related variables
โ
Use consistent formatting
โ
Write self-documenting code
โ
Test with multiple inputs
โ
Add spaces around operators
โ
Keep lines reasonably shortCongratulations! You now understand:
Ready for more? Consider exploring the Advanced Path to deepen your knowledge!
Advanced Path: What are Variables (Advanced) โ
Ready to practice? Try challenges or take the quiz
Resources
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