finding the average using functions in python - python

I do not understand how to find the average of two or more numbers. I tried importing the statistics library, so I could use the mean function, but something is not working.
I keep getting the error traceback most recent call last.
import statistics
def findAverage(avg,avg2):
avg= int(input( 'Please enter a number'))
avg2 = int(input('Please enter a number'))
findAverage()
average=statistics.mean()
print(average)

The use is statistics.mean(list_of_values) so
import statistics
def findAverage():
avg = int(input('Please enter a number1: '))
avg2 = int(input('Please enter a number2:'))
return statistics.mean([avg, avg2])
average = findAverage()
print(average)

you can find avg of any quantity numbers using it:
# Python program to get average of a list
def Average(lst):
return sum(lst) / len(lst)
# Number List
lst = [15, 9, 55, 41, 35, 20, 62, 49]
average = Average(lst)
# Printing average of the list
print("Average of the list =", round(average, 2))

I didn't even understand your code what it does?
I think you want to do this?
def findAverage(avg,avg2):
return (avg+avg2)/2
avg= int(input( 'Please enter a number'))
avg2 = int(input('Please enter a number'))
print(findAverage(avg, avg2))

You should have the same number of arguments when defining your function and when calling it. As well as calling the statistics.mean function on a list:
import statistics
def findAverage():
avg1= int(input( 'Please enter a number'))
avg2 = int(input('Please enter a number'))
return statistics.mean([avg1, avg2])
findAverage()

Statistics.mean() takes a list as input data. You supply it with this data by passing the list inside the () after the call, such as this example:
import statistics
data = [1,2,3] # a list of data
average = statistics.mean(data)
print(average)
Here's your fixed up example, with comments to explain what's going on:
import statistics
# anything inside the brackets below is a "parameter", which is
# information which can be passed to function when calling it.
# since this function finds the two numbers on its own, it doesn't
# need to be passed any information, so i've removed avg and avg2
def findAverage():
# the two lines below for collecting numbers are perfect,
# and don't need to be changed
avg = int(input( 'Please enter a number'))
avg2 = int(input('Please enter a number'))
# however since this is a function, we'll expect it to
# return the average value it calculated from the user input.
# we first put our data into a list like below:
data = [avg, avg2]
# then get the average by passing this data to the mean function
average = statistics.mean(data)
# then return this value so it can be printed out
return average
# we can now call our function, and print the result
print(findAverage())

first of all, you need to mention list of value to statistics.mean([avg1,avg2]) . if you only want to find mean of two values, no need to use it. it is enough you use (num1+num2)/2 .
import statistics
def findAverage(num1,num2):
return statistics.mean([num1, num2])
num1= int(input( 'Please enter a number'))
num2= int(input('Please enter a number'))
result=findAverage(num1,num2)
print(result)

Related

How to remember previous numbers inputted in loop?

What I want to do, is to write a program that given a sequence of real numbers entered by the user, calculates the mean. Entering the sequence should be finished by inputting ’end’. To input more than 1 number I try:
num=input("Enter the number: ")
while num!="end":
num = input("Enter the number: ")
But I don't want the program to "forget" the first 'num', because I'll need to use it later to calculate the mean. What should I write to input and then use more than one value, but not a specific number of values? User should can enter the values until they enter 'end'. All of values need to be use later to calculate the mean. Any tip for me?
First, define an empty list.
numbers = []
Then, ask for your input in an infinite loop. If the input is "end", break out of the loop. If not, append the result of that input() to numbers. Remember to convert it to a float first!
while True:
num = input("Enter a number: ")
if num == "end":
break
numbers.append(float(num))
Finally, calculate the mean:
mean = sum(numbers) / len(numbers)
print("Mean: ", mean)
However, note that calculating the mean only requires that you know the sum of the numbers and the count. If you don't care about remembering all the numbers, you can just keep track of the sum.
total = 0
count = 0
while True:
num = input("Enter a number: ")
if num == "end":
break
total += float(num)
count += 1
print("Mean: ", total / count)
Mean is sum of all nos/total nos. Let's take input from user and add it to list, because we can easily use sum() function to find sum and len() function to find total nos. Your code:
obs=[]
while True:
num=input("Enter number: ")
if num=="end":
break
else:
obs.append(int(num))
print("Mean: ",(sum(obs)/len(obs)))

Prompt user to input 2 numbers, and determine which is smaller. but must be done with custom function, not built in "max" func

i have edited the code to the following and getting more favorable results..
#Python program that will prompt user to enter two numbers, one at a time
and then determine which of the two numbers is smaller.
#define functions
def find_min(first, second):
if first < second:
return first
else:
#second < first
return second
#Get user input
first = int(input('Please type first number: '))
second = int(input('Please type second number: '))
def print_result(first, second):
if first < second:
print(first, 'is smaller than' ,second)
else:
#second < first
print(second, 'is smaller than' ,first)
def main():
#Get user input
first = int(input('Please type first number: '))
second = int(input('Please type second number: '))
print(print_result(first, second))
main()
__
i am getting the code to work now but it is printing 'None' at the end of the result. and function "print_result" is not typing the string 'is smaller than' now.
I see two problems in your code:
as mentioned above you pass in no variables to the find_min function
you do not return a value, you print an answer
your last line should look like this:
print("smallest number is: {}".format(find_min(a,b))

Python- Function that returns a value

Im really struggling with this question, can anyone help me write a code for this program? or at least say where am I going wrong? Ive tried a lot but can't seem to get the desired output.
This is the program description: Python 3 program that contains a function that receives three quiz scores and returns the average of these three scores to the main part of the Python program, where the average score is printed.
The code I've been trying:
def quizscores():
quiz1 = int(input("Enter quiz 1 score: "))
quiz2 = int(input("Enter quiz 2 score: "))
quiz3 = int(input("Enter quiz 3 score: "))
average = (quiz1 + quiz2 + quiz3) / 3
print (average)
return "average"
quizscores(quiz1,quiz2,quiz3)
One, you are returning a string, not the variable. Use return average instead of return "average". You also don't need the print() statement in the function... actually print() the function.
If you call a function the way you are doing it, you need to accept parameters and ask for input outside the function to prevent confusion. Use a loop as needed to repeatedly use the function without having to rerun it every time. So the final code would be:
def quiz_average(quiz1, quiz2, quiz3):
average = (quiz1 + quiz2 + quiz3) / 3
return average
quiz1 = int(input("Enter Quiz 1 score: "))
quiz2 = int(input("Enter Quiz 2 score: "))
quiz3 = int(input("Enter Quiz 3 score: "))
print(quiz_average(quiz1, quiz2, quiz3)) #Yes, variables can match the parameters
You are returning a string instead of the value. Try return average instead of return "average".
There are a few problems with your code:
your function has to accept parameters
you have to return the actual variable, not the name of the variable
you should ask those parameters and print the result outside of the function
Try something like this:
def quizscores(score1, score2, score3): # added parameters
average = (score1 + score2 + score3) / 3
return average # removed "quotes"
quiz1 = int(input("Enter quiz 1 score: ")) # moved to outside of function
quiz2 = int(input("Enter quiz 2 score: "))
quiz3 = int(input("Enter quiz 3 score: "))
print(quizscores(quiz1,quiz2,quiz3)) # print the result
An alternative answer to the already posted solutions could be to have the user input all of their test scores (separated by a comma) and then gets added up and divided by three using the sum method and division sign to get the average.
def main():
quizScores()
'''Method creates a scores array with all three scores separated
by a comma and them uses the sum method to add all them up to get
the total and then divides by 3 to get the average.
The statement is printed (to see the average) and also returned
to prevent a NoneType from occurring'''
def quizScores():
scores = map(int, input("Enter your three quiz scores: ").split(","))
answer = sum(scores) / 3
print (answer)
return answer
if __name__ == "__main__":
main()

What is wrong in the code?

I am very newbie to programming and stack overflow. I choose python as my first language. Today as I was writing some code to refresh and to improve my skills I wrote a little program. But with complete errors.
Here is the Program
a = [1 , 2, 3]
def list_append():
numbers = int(raw_input("Enter the number please"))
a.append(numbers)
print a
def average(list):
for marks in list:
print marks
total = float(sum(list))
total = total / len(list)
print ("Your total average is : %d" %total )
def loop():
add_numbers = raw_input("Do you want to add another number")
if add_numbers == ("y"):
return list_append()
else:
return average()
while True:
loop()
print average(a)
Basically the function of this program is to ask user for the input of the number. Then append to the list and then show the average which is an easy one.
But I want the program to stop after the first input and ask user if they want to give another input ?
Can't understand where is the problem. ** I am not asking for the direct solution. I would rather want an explanation than the solution itself.**
Following is missing in your code:
Need to break any loop, your while loop in going into infinite loop.
while True:
loop()
2. Handle exception during type casting.
numbers = int(raw_input("Enter the number please"))
Create user enter number list in loop function and pass to list_append function to add numbers.
Also return from the loop function to pass argument into average function.
code:
def list_append(numbers):
while 1:
try:
no = int(raw_input("Enter the number please:"))
numbers.append(no)
break
except ValueError:
print "Enter only number."
return list(numbers)
def average(number_list):
avg = float(sum(number_list))/ len(number_list)
return avg
def loop():
numbers = []
while 1:
add_numbers = raw_input("you want to add number in list(Y):")
if add_numbers.lower()== ("y"):
numbers = list_append(numbers)
else:
return list(numbers)
numbers = loop()
avg = average(numbers)
print "User enter numbers:", numbers
print "average value of all enter numbers:", avg
output:
vivek#vivek:~/Desktop/stackoverflow$ python 17.py
you want to add number in list(Y):y
Enter the number please:10
you want to add number in list(Y):y
Enter the number please:e
Enter only number.
Enter the number please:20
you want to add number in list(Y):Y
Enter the number please:30
you want to add number in list(Y):n
User enter numbers: [10, 20, 30]
average value of all enters numbers: 20.0
vivek#vivek:~/Desktop/stackoverflow$
do not use variable names which are already define by python
e.g. list
>>> list
<type 'list'>
>>> list([1,2,3])
[1, 2, 3]
>>> list = [2]
>>> list([1,2,3])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable
>>>
a = []
def average(list):
total = float(sum(list))
total = total / len(list)
print ("Your total average is : %d" %total )
while True:
numbers = raw_input("Enter the number please or 'q' to quit : ")
if numbers == "q":
average(a)
break
else:
a.append(int(numbers))
Hope this helps

Python User Input Average

I'm trying to work on a school assignment that asks the user to input 3 integers, then I need to pass these three integers as parameters to a function named avg that will return the average of these three integers as a float value.
Here's what I've come up with so far, but I get this error:
line 13, in <module>
print (average)
NameError: name 'average' is not defined
Advice?
a = float(input("Enter the first number: "))
b = float(input("Enter the second number: "))
c = float(input("Enter the third number: "))
def avg(a,b,c):
average = (a + b + c)/3.0
return average
print ("The average is: ")
print (average)
avg()
average only exists as a local variable inside the function avg
def avg(a,b,c):
average = (a + b + c)/3.0
return average
answer = avg(a,b,c) # this calls the function and assigns it to answer
print ("The average is: ")
print (answer)
You should print(avg(a,b,c)) because the average variable is only stored in the function and cannot be used outside of it.
You called avg without passing variables to it.
You printed average which is only defined inside the avg function.
You called avg after your print.
Change print (average) to
average = avg(a, b, c);
print(average)

Categories

Resources