####Square root algorithm as a function ##def sqrt(x, epsilon): ## """Newton's Method to find square root ## with precision epsilon (Heron's algorithm)""" ## ans = 1 ## num_guesses = 0 ## while abs(x/ans - ans) > epsilon: ## ans = (x/ans + ans)/2 ## num_guesses += 1 ## print("found square root in", num_guesses, "guesses") ## return ans ## ##x = float(input("Enter a number:")) ##root = sqrt(x, 0.00001) ##print(root, "is close to the square root of", x) ## ##fourth_root = sqrt(root, 0.00001) ##print(fourth_root, "is close to the fourth root of", x) #### Demonstration of nested function calls ##def sqrt(x, epsilon): ## """Newton's Method to find square root ## with precision epsilon (Heron's algorithm)""" ## ans = 1 ## num_guesses = 0 ## while abs(x/ans - ans) > epsilon: ## ans = (x/ans + ans)/2 ## num_guesses += 1 ## print("found square root in", num_guesses, "guesses") ## return ans ## ##def distance_to_origin(x, y): ## """find the distance from a point at (x, y) to the origin""" ## ans = sqrt(x**2 + y**2, 0.00001) ## return ans ## ##def geometric_mean(x, y): ## """Returns the root of x*y""" ## return sqrt(x*y, 0.00001) ## ##x = float(input("Enter a x-coordinate:")) ##y = float(input("Enter a y-coordinate:")) ##magnitude = distance_to_origin(x, y) ##print("The magnitude of your vector is", magnitude) ##geo_mean = geometric_mean( x, y) ##print("The geometric mean of x and y is", geo_mean) ### check to see if values have changed ##print("x is", x) ##print("y is", y) #### Demonstrates that local variables and global variables #### can have the same name. This can be confusing! ##def add_one(x): ## x = x + 1 # a parameter is always a local variable ## y = x + 1 # assignment: this creates a local variable, y ## print('In the function, x =', x) ## print('In the function, y =', y) ## return x ## ##x = 3 ##y = 3 ##result = add_one(x) ##print('the function returns', result) ##print('outside the function, x =', x) ##print('outside the function, y =', y) ####Demonstrates reading global variables from inside function ##def add_y(x): ## x = x + y # there is no local y, so the global value is used ## print('In the function, x =', x) ## print('In the function, y =', y) ## return x ## ##x = 3 ##y = 5 ##result = add_y(x) ##print('the function returns', result) ##print('outside the function, x =', x) ##print('outside the function, y =', y)