Categories

Find the PEP errors:

The following code has 10 PEP8 Violations, can you find them all?
Code Sample with PEP 8 Violations

import math,sys;

def example1(x,y): return x+y

def example2(x,y): 
  print(x+y)

class myClass:
  def __init__(self,r):self.radius=r
  def calc_area(self):
    return math.pi*self.radius**2

def run():
    print("Hello, world!")
    print(example1(1,2))
    example2(3, 4)
    C=myClass(5)
    print("Area is:",C.calc_area())

if __name__== "__main__":run()
Answer Key
  1. Import Statements: import math,sys; should be split into separate lines.
    • Corrected:pythonCopy codeimport math import sys
  2. Semicolon: Semicolon at the end of the import statements is unnecessary.
    • Corrected: Remove the semicolon.
  3. Function Naming: Function names should be lowercase with underscores (example1 and example2 are fine, but myClass and calc_area are not consistent).
    • Corrected:pythonCopy codeclass MyClass:
  4. Function Definition: def example1(x,y): return x+y is on a single line.
    • Corrected:pythonCopy codedef example1(x, y): return x + y
  5. Whitespace: Missing whitespace after commas in function arguments.
    • Corrected: Add space after each comma.
  6. Whitespace in Function: def __init__(self,r):self.radius=r has no spaces.
    • Corrected:pythonCopy codedef __init__(self, r): self.radius = r
  7. Operators: self.radius**2 lacks whitespace around the operator.
    • Corrected: self.radius ** 2
  8. Indentation: Inconsistent indentation (use 4 spaces).
    • Corrected: Use 4 spaces for indentation.
  9. Double Equality in If Statement: Use a single space around the == operator.
    • Corrected:pythonCopy codeif __name__ == "__main__":
  10. Whitespace After Print: Remove unnecessary space after print function.
    • Corrected:pythonCopy codeprint("Area is:", C.calc_area())

Leave a Reply

Your email address will not be published. Required fields are marked *