【问题标题】:Trying to get main function to display a function in python试图让主函数在python中显示一个函数
【发布时间】:2020-01-17 06:27:56
【问题描述】:

当我运行代码时,我似乎无法让主函数显示区域函数。它显示半径函数。我让面积函数使用半径函数中的变量。

def radius(x, y, a, b):
    d = math.sqrt((x - a)**2 + (y - b)**2)
    print('The distance between the center points: ', d)


def area(d):
    pi = math.pi
    ar = pi * d**2
    print('The area of the circle: ', ar)


def main():
    print('Enter first coordinates:')
    x = int(input('Enter X: '))
    y = int(input('Enter Y: '))
    print('Enter second coordinates: ')
    a = int(input('Enter X: '))
    b = int(input('Enter Y: '))

    radius(x, y, a, b)
    area(d)

main()

【问题讨论】:

  • return ar 添加到radius,然后在main 中添加d = radius...

标签: python function main


【解决方案1】:

作为 Python 世界中一个有抱负的年轻人,您应该尝试习惯使用 return 语句。长大后你会发现你并不总是需要它们,但我们留到以后再说吧。

这里是您更正的代码:

def radius(x, y, a, b):
    r = math.sqrt((x - a)**2 + (y - b)**2) / 2  # you call the function radius but calculate the diameter -> confusing!
    return r


def area(d):
    ar = math.pi * d**2
    return ar


def main():
    print('Enter first coordinates:')
    x = int(input('Enter X: '))
    y = int(input('Enter Y: '))
    print('Enter second coordinates: ')
    a = int(input('Enter X: '))
    b = int(input('Enter Y: '))

    D = 2 * radius(x, y, a, b)
    print('The distance between the center points: ', D)
    A = area(D)
    print('The area of the circle: ', A)
    return

main()

原来的问题是,area(d) 调用上的 d 没有定义,因为 d 没有在该特定范围内声明。

【讨论】:

  • 我看到我的代码做错了什么。不使用返回值,也没有在正确的函数中定义变量。感谢您的帮助!
【解决方案2】:

好问题。

如果你想从你的半径函数中使用变量 d,你必须首先从半径函数中返回它。然后在调用函数时“抓住它”。 这使您可以在另一个上下文中使用它。见下文:

def radius(x, y, a, b):
    d = math.sqrt((x - a)**2 + (y - b)**2)
    print('The distance between the center points: ', d)
    return d



def main():
    print('Enter first coordinates:')
    x = int(input('Enter X: '))
    y = int(input('Enter Y: '))
    print('Enter second coordinates: ')
    a = int(input('Enter X: '))
    b = int(input('Enter Y: '))

    d = radius(x, y, a, b)
    area(d)

【讨论】:

    猜你喜欢
    • 2022-12-11
    • 1970-01-01
    • 1970-01-01
    • 2016-04-04
    • 1970-01-01
    • 2014-01-28
    • 2021-06-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多