Rewrite this function so it follows PEP 8, and say which specific rules the original broke.
The original code breaks three rules of PEP 8. The function name uses capitals in the middle instead of small words joined with underscores. The arguments are all packed onto one line, which makes the line longer than the guide recommends. And the body uses a mix of spaces and tabs for its indentation.
# Before: name style, over-long line, tab indentation
def CalculateTotal(price,quantity,taxRate=0.2):
return price*quantity + (price*quantity*taxRate)
# After: small words with underscores, one argument per line, four spaces
def calculate_total(price, quantity, tax_rate=0.2):
subtotal = price * quantity
return subtotal + (subtotal * tax_rate)
print(calculate_total(20, 3))
The output is 72.0, which is 60 plus a tax of 20 percent, and that tax is 12.
PEP 8 has opinions about other things too, and the corrected version follows them. Function names and variable names use small words joined with underscores. Class names use capitals in the middle. In a def line, an argument has spaces around its equals sign, and a default value has no spaces around its own equals sign. Lines are recommended to stay at 79 characters or fewer, and many projects allow a relaxed limit of 99. Two blank lines separate a definition at the top level of a file, and one blank line separates the methods inside a class.
The bigger point to make in an interview is that PEP 8 is a style guide, and not a rule of the syntax. The interpreter does not check one of those conventions. It only cares that your code can be read as a program. What makes the guide valuable is that everyone makes the same arbitrary choices, and that makes code review faster for every project in the world.