In: Computer Science
python 3
Post an example of a fruitful function, adding comments to
explain what it does.
Then add an example of how to call the function and use its return
value.
Remember, unless the goal of a function is to print,
there should be no print statements.
A fruitful function uses return to give results back to main.
The function we name main, will take care of getting input, pass it
to other functions, and those functions will return results to
main, and main will then print those results.
Here is the code containing a useful function "mean" and the
"main" function:
#this defines a function named mean
#which takes as argument an array names vals
#and calculates and returns the mean of the array
def mean(vals):
#iterate over values in the array
sumVals = 0
for val in vals:
sumVals += val
#divide by length to get average
return sumVals/len(vals)
#define main function
def main():
#take user input
n = int(input("Enter number of values: "))
vals = []
print("Enter values: ")
for i in range(n):
vals.append(int(input()))
print("Mean is", mean(vals))
#call main function
main()
Here is a screenshot of the code:
Here is a screenshot of a sample output:
Comment in case of any doubts.