有人可以调用函数错误吗?

时间:2016-03-18 02:43:23

标签: python-3.x

我正在编写一个关于如何为学校模拟汽车的计划。我已经完成了大部分程序,但我对错误感到难过。 我在程序中调用了这些函数:

find_gallons(total_distance, mpg)

find_total_cost (gallon, cost_per_gallon)

def find_gallons(total_distance, mpg):

    try:
       gallon = total_distance / mpg 
       print(gallon)
    except ZeroDivisionError:
        print("MPG is Zero!")

    return gallon

def find_total_cost(gallon, cost_per_gallon):

    total_cost = gallon * cost_per_gallon 

    return total_cost

错误是没有定义find_gallons和find_total_cost。

2 个答案:

答案 0 :(得分:1)

在定义它们之前,您正在调用find_gallons(total_distance, mpg)和另一个函数。

def find_gallons(total_distance, mpg):

    try:
       gallon = total_distance / mpg 
       print(gallon)
    except ZeroDivisionError:
        print("MPG is Zero!")

    return gallon

def find_total_cost(gallon, cost_per_gallon):

    total_cost = gallon * cost_per_gallon 

    return total_cost

find_gallons(total_distance, mpg)
find_total_cost (gallon, cost_per_gallon) # Now calling after defining.

答案 1 :(得分:0)

您的代码格式化并不完全清楚,但在定义之前无法在python中调用函数。将调用移到定义下面。

def find_gallons(total_distance, mpg):
try:
   gallon = total_distance / mpg 
   print(gallon)
except ZeroDivisionError:
    print("MPG is Zero!")

return gallon
def find_total_cost(gallon, cost_per_gallon):

total_cost = gallon * cost_per_gallon 

return total_cost

find_gallons(total_distance, mpg)

find_total_cost (gallon, cost_per_gallon)