将变量从一个函数传递到另一个函数:python

2024-10-02 02:39:00 发布

您现在位置:Python中文网/ 问答频道 /正文


我有两个变量num_of_plantsnum_of_plants2,我想传递给total(),但我收到以下错误:

num_of_plants is undefined

def outer_flowerbed(length,spacing):
    square_area = length ** 2
    side = length/2
    side_ba= (side**2)+(side**2)
    side_c=math.sqrt(side_ba)
    fill_area = side_c**2
    outer_bed = square_area - fill_area
    outer_triangles = outer_bed/4
    conversion = spacing / 12
    num_of_plants = outer_triangles/conversion**2
    print "number of plants in each triangular bed: ",int(num_of_plants)
    return num_of_plants
def circle_area(length,spacing):
    radius = length/4
    a = radius**2 * math.pi
    conversion = spacing/12
    num_of_plants2 = a/conversion**2
    print "number of plants the circle garden has: ",int(num_of_plants2)
    return num_of_plants2
def total(a,b):
    add = a*4 + b
    print "Total plants: ",add

Tags: ofdefarealengthsidenumtotalprint
3条回答

如果函数起作用,则返回两个变量所代表的值。因此,如果您只是将函数直接用作total()的参数,那么它应该可以工作。你知道吗

total(outer_flowerbed(10,2), circle_area(10,2))

看起来你在努力寻找一个花园所需要的植物数量

enter image description here

所以这里有一个过度设计的解决方案(使用一个抽象基类和两个子类):

from abc import ABC, abstractmethod
from math import pi

INCHES_PER_FOOT = 12.

def get_float(prompt):
    """
    Prompt until a float value is entered, then return it
    """
    while True:
        try:
            return float(input(prompt))
        except ValueError:
            pass

class PlantedArea(ABC):
    spacing = 0.5

    @abstractmethod
    def __init__(self, name, *args):
        self.name = name
        self.args = args

    @property
    @abstractmethod
    def area(self):
        return 1

    @property
    def plants(self):
        """
        Return the number of plants which can be placed in `area`
          with `spacing` separation between each plant.

        Note: this is the theoretical maximum number, assuming
          a square planting grid; the actual number needed
          may vary slightly depending on the shape of the border
        """
        return int(self.area / self.spacing**2)

class TriangleArea(PlantedArea):
    def __init__(self, name, width, height):
        self.name   = name
        self.width  = width
        self.height = height

    @property
    def area(self):
        return self.width * self.height / 2

class CircleArea(PlantedArea):
    def __init__(self, name, radius):
        self.name   = name
        self.radius = radius

    @property
    def area(self):
        return pi * self.radius ** 2

def main():
    length  = get_float("What is the garden width (in feet)? ")
    spacing = get_float("What is your plant spacing (in inches)? ") / INCHES_PER_FOOT

    PlantedArea.spacing = spacing
    beds = [
        TriangleArea("NW corner", length/2, length/2),
        TriangleArea("NE corner", length/2, length/2),
        TriangleArea("SW corner", length/2, length/2),
        TriangleArea("SE corner", length/2, length/2),
        CircleArea  ("center",    length/4)
    ]

    total_plants = 0
    for bed in beds:
        plants = bed.plants
        print("The {} bed needs {} plants".format(bed.name, plants))
        total_plants += plants

    print("The whole garden needs a total of {} plants.".format(total_plants))

if __name__ == "__main__":
    main()

就像

What is the garden width (in feet)? 20
What is your plant spacing (in inches)? 6

The NW corner bed needs 200 plants
The NE corner bed needs 200 plants
The SW corner bed needs 200 plants
The SE corner bed needs 200 plants
The center bed needs 314 plants
The whole garden needs 1114 plants.

需要注意的是,num \u of \u plants和num \u of \u plants2是函数的本地函数,不能在函数外调用。但是,既然返回的是值,为什么不将两个函数的结果相加呢。所以你的主要功能是:

def main():
    length = #whatever you have here
    spacing = #whatever you have here
    x,y = outer_flowerbed(length, spacing),circle_area(length,spacing)
    total(x,y)

相关问题 更多 >

    热门问题