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)
Related
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)
Write a program that contains ADD and AVERAGE user defined functions. On execution your program prompts for three numbers from user and call the AVERAGE function. Send the entered three numbers to AVERAGE function. The AVERAGE function call ADD function and send the three user entered numbers to it. The ADD function accepts the numbers from AVERAGE function and calculate sum. Send this sum value back to calling point (AVERAGE function). The AVERAGE function receive the sum value and calculates average for that sum of three numbers. The AVERAGE function send the average value to its calling point (outside of both functions). At the end display the average value from outside these functions.
The output should be:
a: 2
b: 3
c: 4
Average: 3.0
def add(a,b,c):
return a+b+c
def average(a,b,c):
d = add(a,b,c)
e = d/3
return e
f = average(2,3,3)
print(f)
Output:
f = 2.6666666666666665
Generic way of doing this :
def adder(num):
return sum(num)
def avg(*num):
return adder(num)/len(num)
print("Average: ",avg(1,2,3,4))
Now you can pass as much numbers as you want.
The best practice tactics will solve it, like;
n1 = int(input("Enter Number 1: " ))
n2 = int(input("Enter Number 2: " ))
n3 = int(input("Enter Number 3: " ))
def ADD(a,b,c):
return a+b+c
def AVERAGE(a,b,c):
X = ADD(a,b,c)
Y = X/3
return Y
F = AVERAGE(n1, n2, n3)
print(F)
Good luck!
Regards: Khairullah Hamsafar
I have this code in Python
def receipt(array):
sum = 0.0
for i in range(len(array)):
sum = sum + array[i]
return sum
array = []
while True:
print("Calculating Price")
n = input("Enter a price: ")
if n == "":
print("Goodbye")
break
array.append(n)
totalCost = receipt(n)
print("The total cost is " + str(totalCost))
And I'm wondering why this code won't work. There seems to be some error in the fourth line
sum = sum + array[i]
But I can't figure out which part of it is wrong. I believe I used the array[i] component correctly. Perhaps it's a string issue?
Question:
Which part of the code doesn't work?
What is my error?
I'm relatively new to computer science in general. Thanks for the help. Anything is appreciated!
I ran your code and got this error:
$ python test.py
Calculating Price
Enter a price: 24
Traceback (most recent call last):
File "test.py", line 14, in <module>
totalCost = receipt(n)
File "test.py", line 4, in receipt
sum = sum + array[i]
TypeError: unsupported operand type(s) for +: 'float' and 'str'
This means that in your sum = sum + array[i] line, the types don't match up. You need to wrap array[i] in a float() function to match array[i] to the type of sum, which is a float since you initialized it to 0.0. The docs say the input() function returns a string, and since you're appending n to array, you are trying to sum a string with a float. The line should look like this:
sum = sum + float(array[i])
Try running it again and the code works. Here is the documentation for input()
Edit: now to fix the issues were were having with the sum.
Here is a version of your code I have revised with corrections to do the addition the way you want.
1 def receipt(sumvar, n):
2 sumvar = sumvar + float(n)
3 return sumvar
4
5 array = []
6 sumvar = 0.0
7
8 while True:
9 print("Calculating Price")
10 n = input("Enter a price: ")
11 if n == "":
12 print("Goodbye")
13 break
14 totalCost = receipt(sumvar, n)
15 sumvar = totalCost
16 print("The total cost is " + str(totalCost))
As mentioned by others, sum isn't a great variable name so I've renamed it sumvar. Notice the sumvar declaration that is outside the function. When you initialize sumvar inside receipt() like you did, you will always be adding n to 0.0. I doubt this is what you want. Instead, you want to keep a running total of the item count, which needs to be passed into the function. I've also eliminated the loop from your function. This loop was actually iterating over the characters in array, not the elements as you expected it to.
First of there are several things wrong. I will explain each and everything.
Here is your complete working code:
def receipt(array):
total = 0.0
for i in array:
total = total + i
return total
array = []
while True:
print("Calculating Price")
n = input("Enter a price: ")
if n=="":
print("Goodbye")
break
array.append(float(n))
totalCost = receipt(array)
print("The total cost is " + str(totalCost))
Your Mistakes:
1)array.append(n) - First one. Pretty common for beginner.
input() in python gets user input as string. So your n is a String.
See there are data types in all languages. And Python is a Strongly typed language while perl is not. How to say if a language is strongly typed or weakly typed ? Simple. Try this in your interpreter.
>>> a=5
>>> b='9'
>>> a+b
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
a+b
TypeError: unsupported operand type(s) for +: 'int' and 'str'
See the error now try this,
>>> a=5
>>> b='9'
>>> a+int(b)
14
Works perfectly fine right. Python doesn't allow just a+b while some languages do example perl. Read more about it. So you can't add them you have to typecast. So change that into
array.append(int(n))
or
array.append(float(n))
If you are going to work with float values.
2) totalCost = receipt(n) See you are passing n to the function. But your function definition has def receipt(array):. What actually happens here is
receipt(n) ----> (calls) ---->def receipt(array):
Where n ------> array So your array is nothing but n. What you should do intead is
totalCost = receipt(array)
3) sum = 0.0 NEVER I said never use built-in or keyword names (ex ample : sum,min,max,int,str etc) as variable names. Read more about naming in PEP 8
So maybe rename sum to sum_ (it's the convention to be followed) However why can't you just rename sum to total much simpler right?
4) And finally
for i in range(len(array)):
sum = sum + array[i]
Why range(len(array)) when you can simply do for i in array:
Can't understand this take a look at this example:
>>> a = [1,2,3]
>>> for i in a:
print(i)
1
2
3
See for item in something would just take each and every item from a group of something ( iterable (list,tuple,set etc..))
So just change those lines to
for i in array:
total = total + i
And voila you got what you wanted,
Output:
Calculating Price
Enter a price: 10
The total cost is 10.0
Calculating Price
Enter a price: 20
The total cost is 30.0
Calculating Price
Enter a price: 15
The total cost is 45.0
Calculating Price
Enter a price:
Goodbye
UPDATE:
As mentioned in comments you need to learn more about indentation. Check out the link in the comments.
You have some problems, I will comment one by one:
First, you had some indentation problems, be careful with that.
The rest are comments in the code
update
def receipt(array):
sum = 0.0
for i in range(len(array)):
sum = sum + array[i]
return sum
array = []
while True:
print("Calculating Price")
n = input("Enter a price: ") #If you convert the str into float here it will cause an error in the if
if n == "": #here, when you hit enter, it sends the "" (empty string)
print("Goodbye")
break
array.append(float(n)) #So an option is transform the string here
totalCost = receipt(array) #and here, you gave to receipt() function the wrong param, you gave "n" and it was waiting for an array
print("The total cost is " + str(totalCost))
You shouldn't use sum as a variable, since it's a built-in in Python, besides, convert your array[i] to a float type when adding it to another float, also notice you never use your initialized array, you are missing that when calculating totalCost:
def receipt(array):
summ = 0.0
for i in range(len(array)):
summ = summ + float(array[i])
return summ
array = []
while True:
print("Calculating Price")
n = input("Enter a price: ")
if n == "":
print("Goodbye")
break
array.append(n)
totalCost = receipt(array)
print("The total cost is " + str(totalCost))
I have corrected what is causing your issue, you are in fact passing in 'n' into receipt instead of 'array'.
def receipt(array):
sum = 0.0
for i in range(len(array)):
sum = sum + array[i]
return sum
array = []
while True:
print('Calculating Price')
n = input("Enter a price: ")
if n == "":
print("Goodbye")
break
array.append(n)
totalCost = receipt(array) #receipt takes a list as a parameter (what you call array)
print("The total cost is " + str(totalCost))
Additional issues are:
indentation (I suspect that was just copy paste)
input will also give you errors the way you are using it, take a look at this to solve that issue
Consider also making your loop based on the value of n as while true is generally unsafe
or at least changing your if statement to be 'not n' as point out here is more pythonic. Also in the future make sure to note the version of python you are using.
Dont use sum as a variable name, it is a Python built-in.
Fixed:
def receipt(array):
total = 0.00 # avoiding 'sum'
for price in array:
total += float(price) # equivalent to 'total = total + float(price)'
return total
array = []
print ("Calculating Price...") # outside 'while' to not reprint each time!
while True:
price = input("Enter a price: ")
if not price: # equivalent to 'if price is False, or 0 in CompSci speak
print ("Goodbye!")
break
array.append(price)
total = receipt(array)
print("The current total cost is", total) # no need to convert to str()
Some words of advice:
When writing a function, its better to be explicit rather than
implicit. So use variables that make sense!
We can use the same variable names because Python uses the LEBG
rule
for variable scope.
When calculating a price (which we know usually ends in 2 decimals)
its better to use integers rather than floats as you will run into
the [problem](
Limiting floats to two decimal points)
with floating point numbers.
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()
I am trying to get my function to take two arguments, and return their sum. Am I going about this the right way? This is what I have so far:
def my_sum(a, b):
sum = a + b
def main():
a = input(int("enter a number: ", a)
b = input(int("enter a number: ", b)
sum = a + b
return sum
print(" result: ", sum)
main()
So it looks good, but the main problem is that you aren't actually calling your function :) Once you get your two numbers, you can then make the call to your function (which you have properly set up):
def main():
# When you assign variables here, make sure you are putting the int outside
# You also don't need to reference the variable twice
a = int(input("enter a number: "))
b = int(input("enter a number: "))
# Here is where your call goes (try to avoid using variable names that
# are the same as Python keywords, such as sum)
s = my_sum(a, b)
print(" result: ", s)
Now, one other thing you'll have to do is modify your function to return a value. You're already almost there - just add a return (note that since you are just returning the sum of the two numbers, you don't have to assign it to a variable):
def my_sum(a, b):
return a + b
This now means that when you run s = my_sum(a, b), your function will return the sum of those two numbers and put them into s, which you can then print as you are doing.
One other minor thing - when you use the setup you are (with def main(), etc.), you usually want to call it like this:
if __name__ == '__main__':
main()
At this stage, don't worry too much about what it means, but it is a good habit to get into once you start getting into fun stuff like modules, etc. :)
You Have written Wrong coding Style
If you want to do some by using sum method than do this
def my_sum(a, b):
sum = a + b
return sum
def main():
a = int(raw_input("enter a number: "))
b = int(raw_input("enter a number: "))
sum = my_sum(a,b)
print" result: ", sum
main()
I hope this will work as per your requirement.
Regards,
Anil
I am not sure of the purpose of the first function you have defined there (my_sum). However, there are a few things wrong in main as well. The return function always exits the function it is in, and zooms out to a higher level scope. This is very similar to break, except that it returns a value as well. Also, your syntax when you ask for user input is incorrect. It should be:
def main():
a = int(raw_input("Enter a number: "))
b = int(raw_input("Enter a number: "))
return "Result" + (a+b)
main()
Also, if you wanted my_sum to automatically return the sum, you should use return or print:
def my_sum(a, b):
return a + b
doing a print function after return sum won't work because when returning a return value, the execution will exit the scope, the orders should be reversed.
your input function is not implemented correctly.
The correct code should be:
def main():
a = input("enter a number: ")
b = input("enter a number: ")
sum = a + b
print(" result: ", sum)
return sum