0

I am a fresh beginner in learning Python, and need some hints to understand the following exercise :

the goal is to write a script that uses the cube function in the calculus of the volume of a sphere.

Also please don't mind my grammar errors as English is not my first language. Thank you !

r = float(input("choose a number :"))

def volume_sphere(cube(r)):

    pi = 3.14
    cube = int(r**3)
    return(cube)

  volume_sphere = float(4/3*pi*cube(r))
  return(volume_sphere)

volume_sphere(r)

#volume_sphere = volume_sphere(cube(r)) 

Is this possible to do ? This is how I understand the relationship between both functions

print("the volume of the sphere is : , volume_sphere(r)")

deadshot
  • 8,881
  • 4
  • 20
  • 39
KokoKara
  • 11
  • 2

1 Answers1

0

You would define two separate functions, and then one function can call the other. In this case volume_sphere can call cube.

import math

def cube(x):
    return x**3

def volume_sphere(r):
    return math.pi * cube(r)

Then you would just call this like

radius = float(input("choose a number :"))
volume = volume_sphere(radius)
print("the volume of the sphere is : {}".format(volume))

Note that you are free to define a function within another function.

def volume_sphere(r):
    def cube(x):
        return x**3
    return math.pi * cube(r)

In this particular case I don't see a strong reason to do so. These are typically used for closures or wrappers.

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • okay thank you !! So putting a function in another one is impossible, right ? Like that : def volume_sphere(cube(r)): – KokoKara Feb 28 '21 at 14:28
  • @KokoKara I've edited my answer. You *can* define a nested function, though in this specific case I don't think you *should*. – Cory Kramer Feb 28 '21 at 14:31
  • all right, thank you. Lastly, is calling a function the same as saying "return" ? – KokoKara Feb 28 '21 at 14:35