Python problem. Please help Find five errors in the following Python program and
ID: 3916230 • Letter: P
Question
Python problem. Please help
Find five errors in the following Python program and give the reasons why they are errors assuming the programmer is defining a class called Moon and creating an object called lunar of type Moon then calling its methods. (Line numbers are not part of the program. They are given for easy identification.)
1. class Moon
2. earthWeight
3. moonWeight = earthWeight/6
4. def setMoonWeight(ew):
5. if ew != 0:
6. earthWeight = ew
7. self.moonWeight = ew/6
8. def getMoonWeight(self):
9. return self.moonWeight
10. def main():
11. earth = float(input("What is the weight of earth: ")
12. Moon lunar
13. setMoonWeight(earth)
14. print("The weight of earth lunar is ", getMoonWeight() )
15. main()
Explanation / Answer
1. invalid syntax at class moon.. ':' should be there... because in python language is a { } free so inorder to specify that its a code block we use :
2. in line 12 Moon lunar.. its another syntactical error.. you are creating a object type Moon .. the syntax be like lunar=Moon();
3. in line 11 you haven't close the float brace.. u have to add the ')' brace at the end of 11 line
4.in line 2 you have to define the earthWeight variable.. what it is.. int? list? etc.. without defining you can't use it in 3rd line.
5. setMoonWeight() function call in line 13.. u cant call a function because main doesn't know anything about it.. it belongs to the lunar object which is the Moon type.. so you should call it like lunar.setMoonWeight()
6. Major flaw is that.. u want to pass the input earth weight to the moon to initialize it.. then you have to create the object with that weight value.. u might consider writing __init__ in class that should initialize that object with that earth weight
7.and each method inside class will take a self parameter so you should mention in line 4 like setMoonWeight(self,ew)
8. in line 14 calling the getMoonWeight method has same problem as in line 13.. you should call it as lunar.getMoonWeight()
by fixing all the above problems your code will be looks like
class Moon:
def __init__(self,wt):
self.earthWeight=wt
def setMoonWeight(self,ew):
if ew != 0:
self.earthWeight = ew
self.moonWeight = ew/6
def getMoonWeight(self):
return self.moonWeight
def main():
earth = float(input("What is the weight of earth: "))
lunar = Moon(earth)
lunar.setMoonWeight(earth)
print("The weight of earth lunar is ", lunar.getMoonWeight() )
main()
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.