Part 1
The volume of a sphere is 4/3πr3, where π has the value of "pi" given in Section 2.1 of your textbook. Write a function called print_volume (r) that takes an argument for the radius of the sphere, and prints the volume of the sphere.
Call your print_volume function three times with different values for radius.
Include all of the following in your Learning Journal:
The code for your print_volume function.
The inputs and outputs to three calls of your print_volume.
Part 2
Write your own function that illustrates a feature that you learned in this unit. The function must take at least one argument. The function should be your own creation, not copied from any other source. Do not copy a function from your textbook or the Internet.
Include all of the following in your Learning Journal:
The code for the function that you invented.
The inputs and outputs to three calls of your invented function.
A description of what feature(s) your function illustrates.
Part 1
Code:
from math import pi
def print_volume(r):
print((4 / 3) * pi * r ** 3)
print_volume(5)
print_volume(1.6)
print_volume(12)
Results:
Input 1:
5
Output 1:
523.5987755982989
Input 2:
1.6
Output 2:
17.157284678805063
Input 3:
12
Output 3: 7238.229473870882
Part 2
Code:
from math import sin
def areas(*args):
if len(args) ==1:
print("Area of square:", args[0] ** 2)
elif len(args) == 2:
print("Area of rectangle:", args[0] * args[1])
elif len(args) == 3 and 0 <= args[2] <= 360:
print("Area of triangle:", 0.5 * args[0] * args[1] * sin(args[2]))
else:
print("You should enter 1, 2 or 3 arguments!")
areas(3)
areas(4, 6)
areas(3, 4, 45)
Results:
Input 1:
3
Output 1:
Area of square: 9
Input 2:
4 6
Output 2:
Area of rectangle: 24
Input 3:
3 4 45
Output 3:
Area of triangle: 5.10542114720471
Description:
The areas() function displays the areas of geometric shapes, depending on the number of arguments entered. Arguments are passed to the *args list, then the number of arguments is checked in the function body using the len() function, which returns the length of the args list. If the argument is one, the area of the square is displayed. If there are two arguments, the area of the rectangle is displayed. If there are three arguments, and the last one is in the range from 0 to 360, the area of the triangle is displayed. The result is calculated using the geometric formulas for areas, as well as the sin() function from the math module of the Python standard library.
Comments
Leave a comment