Most of the functions we have used so far depend on the parameters we pass them. print() prints the variables passed to it, max() computes the maximum of numbers passed to it, math.sqrt() computes the square root of the number passed to it. So, the functions change their behavior depending on the value passed to them. They don’t repeat the same set of actions as the function in the previous exercise did.
To be able to change the behavior based on the parameters, we need to pass the parameters to the function. That can be done by defining the arguments that the function can accept inside the opening and closing brackets ().
def print_volume(h, w, d):
volume = h * w * d
print(volume)
print_volume(2, 3, 4) # 24
print_volume(2, 0, 4) # 0
print_volume(1, 10, 24) # 240
A function can have as many arguments as it’s necessary. They just need to have proper names and be separated by commas.
Challenge
Write a function that would compute the volume of a cylinder and would print it.
As a reminder, the volume of the cylinder is calculated by multiplying the area of the base circle by the height:
The first line of the input will contain an integer n - the number of cylinders for which the volume needs to be calculated. The next n lines contain two integers h and r. The height and the radius of the cylinder.
Call the function you created on each cylinder so that the program output contains n volumes.
Input
Output
115
6
1696.46
Tip
When naming the parameters of the function, it’s a good practice to have names that don’t coincide with other names used in other parts of the code. So, if you have h = int(input()), you might want to name the function parameter height, for instance.