Writing code that works is important, but writing code that is easy to read and maintain is equally important. Here are three key practices.
Use variable names that describe their contents. This makes your code much easier to understand.
# Poor variable names
x = 10.0
y = 5.0
z = 2.0
a = x * y * z
# Good variable names
length = 10.0
width = 5.0
depth = 2.0
volume = length * width * depth
Initialise your variables at the top of your program so you can see at a glance what data your program uses.
Comments explain why your code does something, not just what it does. Use the # symbol to add comments:
# Calculate the volume of the swimming pool
length = float(input("Enter the length: "))
width = float(input("Enter the width: "))
depth = float(input("Enter the depth: "))
volume = length * width * depth # length × width × depth
print("The volume is", volume)
Good comments:
Avoid obvious comments like # print the result above print(result).
Use blank lines to separate logical sections of your program. This makes the code easier to read:
# Get user input
name = input("Enter your name: ")
age = int(input("Enter your age: "))
# Calculate future age
future_age = age + 10
# Display results
print("Hello,", name)
print("In 10 years you will be", future_age)
Can you improve the following poorly written program?
x=input("n?")
y=int(input("a?"))
z=int(input("h?"))
print(x,y,z+10)
# Get user details
name = input("Enter your name: ")
age = int(input("Enter your age: "))
height = int(input("Enter your height in cm: "))
# Display details with age in 10 years
print(name, age, height + 10)
Key improvements:
name, age, height instead of x, y, z)