[英]Using a Variable from One Function Inside Another Function then Calling It
# Write a function inCircle that takes a point and a radius as a parameter.
# The function should return True if the point is inside the circle and False otherwise.
import math
# Function for distance equation
def pointCalc(x1, y1, x2, y2):
distance = math.sqrt(((x2 - x1) ** 2) + ((y2 - y1) ** 2))
# Function for whether or not coordinate points are in the in/on the circle
def inCircle(point, radius):
"""Function that returns whether point is inside a circle"""
if pointCalc.distance >= radius:
print(f"Point ({pointCalc.x1},{pointCalc.x2}) is not in circle with radius {radius}")
else:
print(f"Point ({pointCalc.x1},{pointCalc.x2}) is in circle with radius {radius}")
# Prompt user for inputs on coordinate points, center, and radius
print("Enter coordinate points:")
print("---------------------------------------------")
point_x = float(input("Enter a x-coordinate point: "))
point_y = float(input("Enter a y-coordinate point: "))
print("\nEnter coordinate points for the center:")
print("---------------------------------------------")
center_x = float(input("Enter a x-coordinate point for the center: "))
center_y = float(input("Enter a y-coordinate point for the center: "))
r = float(input("\nEnter radius for the circle: "))
# Call functions
pointCalc(point_x, point_y, center_x, center_y)
inCircle(radius=r)
So in essence you want to pass a variable calculated in a function to another function?所以本质上你想把一个函数中计算出的变量传递给另一个函数?
Then the right way to do it (in most of the programming languages) is to return
the value from the function.那么正确的做法(在大多数编程语言中)是从函数
return
值。 You aren't using return
in your functions, and you can't access the variables inside of another function through a syntax like func.variable
- a function isn't an object (kind of) and the variables it declares are destroyed once the function terminates.你没有在你的函数中使用
return
,你不能通过像func.variable
这样的语法访问另一个函数内部的变量 - 一个函数不是一个对象(一种),一旦它声明的变量就会被销毁函数终止。
So in your case:所以在你的情况下:
# Function for distance equation
def pointCalc(x1, y1, x2, y2):
return math.sqrt(((x2 - x1) ** 2) + ((y2 - y1) ** 2))
# Function for whether or not coordinate points are in the in/on the circle
def inCircle(distance, radius):
"""Function that returns whether point is inside a circle"""
if distance >= radius:
print(f"Point ({pointCalc.x1},{pointCalc.x2}) is not in circle with radius {radius}")
else:
print(f"Point ({pointCalc.x1},{pointCalc.x2}) is in circle with radius {radius}")
# ...
# Call functions
d = pointCalc(point_x, point_y, center_x, center_y)
inCircle(distance=d, radius=r)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.