在大多数情况下,我的代码有效。如果您运行它并且输入中没有任何错误,它将按预期工作。如果输入错误,它会显示相应的消息并提示您再次输入,但如果您输入了有效的数字,则会出现错误消息:
Traceback (most recent call last):
File "C:\Users\Seren\Documents\~School~\MSON Intro Computer Programming\Earthquake.py", line 92, in <module>
print(r.yourQuakeOutput())
File "C:\Users\Seren\Documents\~School~\MSON Intro Computer Programming\Earthquake.py", line 49, in yourQuakeOutput
joules = r.calcJoules()
File "C:\Users\Seren\Documents\~School~\MSON Intro Computer Programming\Earthquake.py", line 18, in calcJoules
return 10 ** ((1.5 * self.r) + 4.8)
TypeError: unsupported operand type(s) for *: 'float' and 'NoneType'
我根本不明白这意味着什么,或者如何解决它。我认为它与yourQuakeInput函数有关,但我不确定。有没有人有想法?这是代码本身:
class Earthquakes:
def __init__(self, richter):
self.r = richter
def calcJoules(self):
return 10 ** ((1.5 * self.r) + 4.8)
def calcTNT(self):
joules = r.calcJoules()
return joules/(4.184 * 10 ** 9)
def genericQuake(self):
joules = r.calcJoules()
tnt = r.calcTNT()
return "An earthquake with a %s on the Richter scale is equivalent to %s joules and %s tons of exploded TNT." % (self.r, joules, tnt)
def specQuake(self, quake):
joules = r.calcJoules()
tnt = r.calcTNT()
return "The %s earthquake, a %s on the Richter scale, was equivalent to %s joules and %s tons of exploded TNT." % (quake, self.r, joules, tnt)
def yourQuakeInput(self):
richter = float(input("Your earthquake measures what on the Richter scale?"))
if richter < 0:
print("The Richter scale only goes from 0-10. Try again.")
r.yourQuakeInput()
elif richter > 10:
print("The Richter scale only goes from 0-10. Try again.")
r.yourQuakeInput()
elif richter >= 0 and richter <= 10:
return richter
else:
print("Invalid input. Try again.")
r.yourQuakeInput()
def yourQuakeOutput(self):
joules = r.calcJoules()
tnt = r.calcTNT()
return "Your earthquake, a %s on the Richter scale, is equivalent to %s joules and %s tons of exploded TNT." % (self.r, joules, tnt)
def __str__(self):
return "richter=" + str(self.r)
def tryAgain():
answer = input("Would you like to try again?").lower()
if answer == "yes":
pass
elif answer == "no":
quit()
else:
print("Invalid input. Try again.")
tryAgain()
r = Earthquakes (1.0)
print(r.genericQuake())
print("")
r = Earthquakes (5.0)
print(r.genericQuake())
print("")
r = Earthquakes (9.1)
print(r.specQuake("2004 Indonesia"))
print("")
r = Earthquakes (9.2)
print(r.specQuake("1964 Alaska"))
print("")
r = Earthquakes (9.5)
print(r.specQuake("1960 Chile"))
print("")
r = Earthquakes (5.8)
print(r.specQuake("2011 Virginia"))
print("")
while True:
r = Earthquakes (r.yourQuakeInput())
print(r.yourQuakeOutput())
print("")
tryAgain()
答案 0 :(得分:-1)
如果您的向导不正确,您似乎缺少返回声明:
if richter < 0:
print("The Richter scale only goes from 0-10. Try again.")
return r.yourQuakeInput()
elif richter > 10:
print("The Richter scale only goes from 0-10. Try again.")
return r.yourQuakeInput()