2014-09-23 7 views
1

Мне нужно передать значение ширины в calcRectArea в calcTriArea, чтобы я мог вычислить область фронтона, не запрашивая ширину второй раз. Я очень новичок в Python и программировании вообще, так что простите меня, если это глупый вопрос.Как передать значение одной функции другой функции?

def main(): 

    ''' 
main adds rectangular area and triangular area to compute the total area 
    ''' 

    rectarea=0 
    rectarea=calcRectArea(rectarea) 
    print("Rectangular area is now",rectarea) 

    triarea=0 
    triarea=calcTriArea(triarea) 
    print("Triangular area is now",triarea) 

    totalarea=triarea+rectarea 
    print("The total area of the first house is",totalarea) 

    print("For the second house: ") 

    rectarea2=0 
    rectarea2=calcRectArea(rectarea2) 
    print("Rectangular area of second house is now",rectarea2) 

    triarea2=0 
    triarea2=calcTriArea(triarea2) 
    print("Triangular area of the second house is now",triarea2) 

    totalarea2=triarea2+rectarea2 
    print("The total area of the second house is",totalarea2) 

    totalbothhouses=totalarea+totalarea2 
    print("The combined area of both houses is",totalbothhouses) 


def calcRectArea(RectAreaTotal): 

    ''' 
calcRectArea prompts the user to enter width, height, and length, computes the 
front and side areas, and adds them to compute rectangular area 
''' 

    width=input("Enter the width: ") 
    width=int(width) 

    height=input("Enter the height: ") 
    height=int(height) 

    length=input("Enter the length: ") 
    length=int(length) 

    front=(width*height) 
    side=(length*height) 

    RectAreaTotal=(front*2)+(side*2) 
    return RectAreaTotal 

def calcTriArea(totalgablearea): 

    ''' 
    calcTriArea has the user enter the gable height and computes triangular area 
    ''' 

    gableheight=input("Enter the gable height: ") 
    gableheight=int(gableheight) 

    totalgablearea=(gableheight)   
    return totalgablearea      

main() 
+0

у разве Вы trake входы в основной функции ... таким образом, вы Willl быть в состоянии эти входы в любой функции – Tushar

+0

Спасибо за предложения, но я закончил просто глобализацию переменных. –

+0

@JoeyCartella НЕТ НЕТ НЕТ! Не делай этого. ** ВСЕГДА ** избегайте глобализации, когда можете. –

ответ

1

Вы могли бы рассмотреть вопрос об обращении к значениям вне ваших вычислительных функций:

def get_dimensions(): 
    height = int(input("Enter the height: ")) 
    width = int(input("Enter the width: ")) 
    length = int(input("Enter the length: ")) 

height, width, length = get_dimensions() 

# go on to pass the values to your functions 

Есть другие гораздо более продвинутые варианты, но это должно вам начать работу. Если вам интересно, я могу добавить другие варианты этого ответа.

0

Вы можете получить значения из основного и передать его на две функции, calcRectArea и calcTriArea

Проверьте определения функций, включая main осуществить изменение:

def main(): 

    ''' 
main adds rectangular area and triangular area to compute the total area 
    ''' 

    rectarea=0 
    width=input("Enter the width: ") 
    width=int(width) 
    rectarea=calcRectArea(rectarea,width) 
    print("Rectangular area is now",rectarea) 

    triarea=0 
    triarea=calcTriArea(triarea,width) 
    print("Triangular area is now",triarea) 

    totalarea=triarea+rectarea 
    print("The total area of the first house is",totalarea) 

    print("For the second house: ") 

    rectarea2=0 
    width=input("Enter the width: ") 
    width=int(width) 
    rectarea2=calcRectArea(rectarea2, width) 
    print("Rectangular area of second house is now",rectarea2) 

    triarea2=0 
    triarea2=calcTriArea(triarea2, width) 
    print("Triangular area of the second house is now",triarea2) 

    totalarea2=triarea2+rectarea2 
    print("The total area of the second house is",totalarea2) 

    totalbothhouses=totalarea+totalarea2 
    print("The combined area of both houses is",totalbothhouses) 


def calcRectArea(RectAreaTotal, width): 

    ''' 
calcRectArea prompts the user to enter width, height, and length, computes the 
front and side areas, and adds them to compute rectangular area 
''' 



    height=input("Enter the height: ") 
    height=int(height) 

    length=input("Enter the length: ") 
    length=int(length) 

    front=(width*height) 
    side=(length*height) 

    RectAreaTotal=(front*2)+(side*2) 
    return RectAreaTotal,width 

def calcTriArea(totalgablearea, width): 

    ''' 
    calcTriArea has the user enter the gable height and computes triangular area 
    ''' 

    gableheight=input("Enter the gable height: ") 
    gableheight=int(gableheight) 

    totalgablearea=(gableheight)   
    return totalgablearea 
1

Давайте посмотрим на то, что функция выглядит.

можно написать некоторую произвольную функцию называют Foo таким образом, что она имеет один вход и выход:

def foo(a): 
    return a 

f = foo(1) # f == 1 

можно также записать его с 4 входами и 4 выходами:

def foo(a, b, c, d): 
    return a, b, c, d 

f, g, h, i = foo(1, 2, 3, 4) # f = 1, g = 2, h = 3, i = 4 

функция, определение позволяет указать любое количество желаемых вами входов. Вы также заметите, что в python вы можете вернуть несколько значений! В вашем примере вы можете просто изменить текущую функцию, чтобы принять дополнительное значение.

def calcTriArea(totalgablearea): 

становится

def calcTriArea(totalgablearea, calcRectArea): 

Теперь вы должны изменить обратный Постулаты в rectArea вернуть дополнительное значение.

return RectAreaTotal, width 

и теперь ваш доступа может calcRectArea «s ширина в вашей в функции triArea! Теперь нужно просто передать его функции следующим образом:

rectarea, width=calcRectArea(rectarea) 
print("Rectangular area is now",rectarea) 

triarea=0 
triarea=calcTriArea(triarea, width) 
print("Triangular area is now",triarea) 
Смежные вопросы