Average not calculating right in python3 - python

This is a work in progress code. As you can tell, I am a complete beginner and been trying new things. I usually get an error and I try and fix that but here this one is not giving me any error. It's just that the answer to the average is a wrong number. Without any error, its hard for me to know what's wrong with the code. Any suggestion?
sum = 0.0
count = 0
ids = [ ]
scores = [ ]
ids = eval(input("Enter an id number:"))
if ids <= 0.0:
print("Can't be 0 or a negative number, please enter a number greater than 0")
exit(1)
scores = eval(input("Enter a score:"))
while ids >= 0.0:
ids = eval(input("Enter another id number (or 0 to quit):"))
if ids <= 0.0:
break
scores = eval(input("Enter another score:"))
sum = sum + scores
count = count + 1
avg = sum / count
for i in range(ids):
print(i)
print("The average of the scores is", avg)

There are several mistakes in your code.
First of all in python you must use right indentation.
Next you have declared ids = [ ] and scores = [ ] without any reason
Why do you use ids?
Instead of eval(input()), use int(input())
A simple code to calculate average:
scores = list(map(int, input('Enter Space Separated Elements : ').split()))
print('Average is ' + str(sum(scores) / len(scores)))
Explanation:
Learn about input here
Learn about input().split() here
Learn about map() here
As map returns a map object, we must convert it to a list
Learn about sum, len and other built-in functions here
Hope this helps!

Related

Finding the mean from input

my 6th grade teacher asked me to code a program in python that input any amount of a number and it outputs the mean so i tried and theirs a problem with the print statement here's the code.i even tried to replace the float(b) statements to float(1) statements but that didn't work either
n = int(input("Enter number of elements :"))
b = input("\nEnter the numbers :")
sum = (float(b)+float(b)+float(b) / float(n)
print("\nThe mean is -",sum())
Please give space separated input here :
input = list(map(float ,input('Enter number of elements : ').split(' ')))
mean = sum(input)/len(input)
print(mean)
: Output :
Enter number of elements : 10 20 30
20.0
i would do something like this.
I assumed you wanted the arithmetic mean and not the geometric one, so the first thing to do is to get the number of values the user wants to input and store it in the variable n. The you iterate over a range n and you sum the inputs to k.
The you divide k by n.
n, k = int(input("Enter number of elements:")), 0
for i in range(n):
k += float(input("Enter value number {}".format(i+1)))
k /= n
print(k)
if you want to use the "cool" way you can do something like this:
n = int(input("Enter number of elements:"))
k = sum([float(input("Enter value number {}".format(i+1))) for i in range(n)]) / n
print(k)
There is an syntax error and logical error in this code.
You haven't closed the opening bracket, It should be like this
sum = (float(b)+float(b)+float(b)) / float(n)
If you want to calculate the mean of 3 values why are you adding the same value for three times here
(float(b)+float(b)+float(b))
Insted of using same values you can get each values from for loop like this
for i in range(3):
num = float(input())
total += num

"Variable not defined" error in total and average computation

I wrote this program to find sum and average, and got "Variable not defined" error. Can anyone solve it?
a=int(input("Total Numbers you will input for calculation: "))
Sum = 0 # Running Totalis b
for x in range (a-1):
c=int(input("Enter your input number {0}.".format(x+1)) # c is for next number
Sum = Sum + c
Total=b/10 # For Total
print("Total sum of the number you entered is {0} and their average is {1},".format(b,d))
In your code that prints out the sum and average, you refer to the variables b and d, neither of which actually exist. That is the cause of your immediate problem, the "Variable not defined" issue.
The sum of the numbers is stored in the Sum variable which you should use rather than b. The average is not calculated anywhere unless your calculation for Total is meant to do this but, if that's the case, you should choose a more appropriate name and calculate it correctly (dividing by a rather than by ten).
On top of that, your use of range is incorrect. You should be using a rather than a-1, since range(n) already gives you the values 0 .. n-1, a toal of n different items.
So, with all that in mind, and using some better (self-documenting) variable names (and catching the problem of entering a non-positive count), you could opt for something like:
count = int(input("Total Numbers you will input for calculation: "))
if count > 0:
sumOfNums = 0
for x in range(count):
num = int(input("Enter your input number {0}.".format(x+1))
sumOfNums += num
avgOfNums = sumOfNums / count
print("Total sum of the number you entered is {0} and their average is {1},".format(sumOfNums, avgOfNums))
Have a look at below:
a=int(input("Total Numbers you will input for calculation: "))
sum = 0 # Running Totalis b
for x in range (a):
c=int(input("Enter your input number {0}.".format(x+1)))
sum +=c
avg=sum / a # For Total
print("Total sum of the number you entered is {0} and their average is {1},".format(sum,avg))

Generate a list of random numbers

So, the assignment is to ask the user for how many randomly generated numbers they want in a list, and then from that list find the: total(sum), the average, the smallest and the largest number. SOFAR, I am getting an error on line 14 "object of type 'int' has no len()". I get the same responce when using < too.
import random
def main():
randomList = 0
smallest = 0
largest = 0
average = int(input("How may numbers (between 1-100) would you like to generate?: "))
total = 0
if average >= 101 or average <= 0:
print("Invalid input:How may numbers (between 1-100) would you like to generate?: ")
else:
while randomList != len(int(average)):
randomList.append(random.randint(1,101))
randomList=sorted(randomList)
print(randomList)
total = sum(randomList)
average = float(sum(randomList)) / max(len(randomList))
largest = randomList.pop(average)
smallest = randomList.pop(0)
print('The total of all the numbers are ',str(total))
print('The average of all the numbers are ',str(average))
print('The largest of all the numbers are ',str(largest))
print('The smallest of all the numbers are ',str(smallest))
main()
Here is a working version of your code.
import random
def main():
smallest = 0
largest = 0
n = int(input("How may numbers (between 1-100) would you like to generate?: "))
total = 0
if n >= 101 or n <= 0:
print("Invalid input:How may numbers (between 1-100) would you like to generate?: ")
else:
randomList = random.choices(range(1, 101), k=n)
print(randomList)
total = sum(randomList)
average = sum(randomList) / len(randomList)
largest = max(randomList)
smallest = min(randomList)
print('The total of all the numbers are ',str(total))
print('The average of all the numbers are ',str(average))
print('The largest of all the numbers are ',str(largest))
print('The smallest of all the numbers are ',str(smallest))
main()
Explanation
Many errors have been fixed:
Use random.choices for a random list of values of specified length.
You use average in the context of a list of numbers and average value. Make sure you name and use variables appropriately.
Sorting is not required for your algorithm.
I have corrected calculations for average, largest, smallest.
In addition, I advise you get in the habit of returning values via the return statement and leave formatting as a step separate from your calculation function.
how about this:
randomList = [random.integer() for i in range(userinput)]

Simple arithmetic average in Python

I'm a total newbie on Python and I would like to calculate the arithmetic average.
a = [int(i) for i in input().split()]
average=sum(a)/len(a)
print('The average is:' ,average)
I'm aware that such code do solve my problems but that is not exactly what I'm looking for.
I want the user to be able to type the number of terms of the arithmetic average and I would like him to be able of typing them separatley on different lines. So I thought the right thing to use was For Loop. I came out with something like this:
n = input('Number of terms')
for i in range (1,int(n)+1):
a=input('Term number '+str(int(i))+': ')
I know that all I need to do know is to find a way to sum all values of a typed on each loop and divide this number by int(n) but I have no idea how to do that.
Can you guys help me with that?
Thanks everyone!
n = input('Number of terms')
acc = 0
for i in range(1,int(n)+1):
a=input('Term number '+str(int(i))+': ')
acc += float(a)
print('The average is ',acc/int(n))
The idea is to create an accumulator variable acc to which the entered numbers are added. After the loop acc is equal to the sum of all numbers entered. Divide it by the number of terms and you get the arithmetic average.
Try:
n = int(input('Number of terms'))
sum = 0
for i in range (1,n+1):
a=int(input('Term number '+str(i)+': '))
sum += a
avg = sum/n

Printing an average in python, using a list

This code needs to calculate an average to retrieve an integer between 0-100. Any suggestions would be great.
Prompt the user for the number of points they expect to receive
for engagement at the end of class. This number should not be
adjusted by the program (engagement is a total of 302).
Calculate the final based on an average of the quiz scores to
date.
Prompt the user for the various scores. -1 = no more scores, 0 -
zero for that assignment. Keep looping for the grade until the user
enters a -1.
Here is my code, I definitely do not understand lists very well. Probably clearly.
list1 = []
g=1
totalnum = 0
total=0
tot = int(input("Total Points? :"))
list1.append(tot)
eng = int(input("How many points do you expect to get in engangement, out of 302?: "))
list1.append(eng)
while g !=0:
num = int(input("Please enter a grade"))
if num == -1:
break
totalnum+=1
total= total+num
list1.append(num)
average= tot/eng+num
counter=0
while counter<totalnum:
print(list1[counter])
counter+=1
print("your average is",average)
If you can use built ins you can just use sum(your_list) / len(your_list) for the average.
If len(your_list) is zero, you will get a ZeroDivisionError, because you just broke math.
It's not clear to me that this is what you're trying to accomplish, but if you just want an average of all the values in the list, you can just do:
average = sum(list)/len(list)
This would return an integer, if you don't want it rounded you could do:
average = sum(list)/float(len(list))
As an aside, you have this:
counter=0
while counter<totalnum:
print(list1[counter])
counter+=1
Which could be made simpler, like:
for e in list1:
print e
Python will do the counting for you. :)
list1 = []
g=1
totalnum = 0
total=0
tot = int(input("Total Points? :"))
eng = int(input("How many points do you expect to get in engangement, out of 302?: "))
list1.append(eng)
while g !=0:
num = int(input("Please enter a grade"))
if num == -1:
break
else:
list1.append(num)
totalnum+=1
total= (num+eng)/tot
print(len(list1))
average = (sum(list1)/tot)*100
counter=0
for e in list1:
print (e)
print("your average is",average)
This is more what I was looking for. Thanks to #Tommy, #SQLnoob, and #Slayer for the tips that I have implemented into the code.

Categories