Figuring out Sum, Product, and Average from User Inputs - python

I'm working on some homework which requires me to do the following:
Write a program that receives a series of numbers from the user and allows the user to press the enter key to indicate that he or she is finished providing input. After the user presses the enter key, the program should print the sum of the numbers, the product of the numbers, and the average of the numbers.
Run your program with the following inputs:
1, 2, 3, 4, 5, 6, 7, 8
2, 24, 11, 1, 4, 10
Enter no number
Here is what I have so far, but my numbers are not coming out correctly. Can someone tell me what I'm doing wrong. I'm a beginner so, if you could speak in the simplest terms possible, that would be great.
Take numbers from user until the user presses "Enter"
calculate the sum, product, and average of the numbers entered
display the results
#main program start
def main():
#initialize variables
count = 0
sum = 0.0
product = 1.0
data = input("Enter a number or press Enter to quit: ")
while True:
#request input from user
data = input("Enter a number or press Enter to quit: ")
#set up the termination condition
if data == "":
break
#convert inputs into floats
number = float(data)
#calculate sum, product, and average
sum += number
product *= number
average = sum / number
#display results
print("The sum is", sum)
print("The product is", product)
print("The average is", average)
#main program end
main()

Not sure what you mean the values are wrong. Nothing seems off except the average.
If you want the average, you need a list to collect the values. Try writing your algorithm by hand, and you'll see what I mean.
data = input("Enter a number or press Enter to quit: ")
numbers = []
while True:
#request input from user
data = input("Enter a number or press Enter to quit: ")
#set up the termination condition
if data == "":
break
#convert inputs into floats
numbers.append(float(data))
# these can all be done outside and after the while loop
count = len(numbers)
if count > 0:
_sum = sum(numbers)
product = 1.0
for n in numbers:
product *= n
average = _sum / float(count)
#display results
print("The sum is", _sum)
print("The product is", product)
print("The average is", average)
else:
print("Nothing was entered")

You don't have all the numbers since you are entering the numbers one at a time. It would be best to have the user enter a list like this:
def main():
average = 0
sum_nums = 0
product = 1
nums = []
while True:
data = input("Enter a number or press Enter to quit: ")
if data == ""
sum_nums = sum(nums)
for num in nums:
num *= product
average = sum_nums/len(nums)
print("The sum is {},".format(sum_nums))
print("The product is {}.".format(product))
print("The average is {}.".format(average))
else:
nums.append(data)
continue
It works by entering all the inputs into a list. The only way to exit an input is by using enter so if the input is nothing then it can only be the Enter key. Once the enter key was hit, I got all the values and printed them.

numbers = []
print("enter key to stop")
while(True):
num = input("enter a number :")
if num:
numbers.append(int(num))
elif(num == ''):
break
sum_num =0
for num in numbers:
sum_num += num
avg = sum_num / len(numbers)
print(sum_num)
print(avg)

Related

how to sort a list in a while loop

I want to write a program which reads numbers continuously from the user (one at a time), until the user enters "0"
and then the program returns the smallest number in that inputs. I am having trouble sorting out.
This is my code so far:
while True:
number = []
number = input("Please enter a number ")
if number == "0":
break
number.sort()
x = number[0]
return x
You overwrite your number at each step, this cannot work. You should keep track of the min value instead:
min_value = None
while True:
number = int(input("Please enter a number ")) # no type check here
if number == 0:
break
if number is None or number < min_value:
min_value = number
print(min_value)
You can make a list of your entered numbers appending them and then finding the minimum value using the numpy module. For example:
import numpy as np
while True:
number_list = []
number = input("Please enter a number ")
number_list.append(number)
if number == "0":
break
number_array = np.array(number_list)
minval = np.min(number_array[np.nonzero(number_array)])
So that you can find the minimum value of the array, excluding the "0" you entered at the end.

Mathmatical Average Calculation

Edit the program provided so that it receives a series of numbers from the user and allows the user to press the enter key to indicate that he or she is finished providing inputs. After the user presses the enter key, the program should print:
The Average and The Sum
I've been able to get it to print the sum of the numbers put in but I think it is messing up when trying to calculate the average. I really need some help with this. try inputting 100 59 37 21 and you will see what I mean
data = input("Enter a number: ")
number = float(data)
while data != "":
number = float(data)
theSum += number
data = input("Enter the next number: ")
print("The sum is", theSum)
average = theSum // number
print("The average is", average)```
As Mat and Nagyl have pointed out in the comments you need to keep track of how many numbers were given and divide the sum by that to get the average
data = input("Enter a number: ")
number = float(data)
numbersGiven = 0
theSum = 0
while data != "":
number = float(data)
theSum += number
numbersGiven += 1
data = input("Enter the next number: ")
print("The sum is", theSum)
average = theSum / numbersGiven
print("The average is", average)
Notice that the first input isn't counted (I start with numbersGiven = 0) but the empty input at the end is counted so it gives the correct count.
you can use these code too!
instead of writing the formula for average you can use statistics module
import statistics
the code below asks you the numbers how many times you wrote in the number of datas
number_of_datas=int(input("number of inputs asking: "))
datas=[]
The following code takes the number from the number of times you wrote in the number of inputs
also you can write a Specified number instead of getting an input
for i in range(number_of_datas):
data = float(input("Enter a number: "))
datas.append(data)
fmean is float average
average=statistics.fmean(datas)
print(average)

Add numbers and exit with a sentinel

My assignment is to add up a series of numbers using a loop, and that loop requires the sentinel value of 0 for it to stop. It should then display the total numbers added. So far, my code is:
total = 0
print("Enter a number or 0 to quit: ")
while True:
number = int(input("Enter a number or 0 to quit: "))
print("Enter a number or 0 to quit: ")
if number == 0:
break
total = total + number
print ("The total number is", total)
Yet when I run it, it doesn't print the total number after I enter 0. It just prints "Enter a number or 0 to quit", though it's not an infinite loop.
The main reason your code is not working is because break ends the innermost loop (in this case your while loop) immediately, and thus your lines of code after the break will not be executed.
This can easily be fixed using the methods others have pointed out, but I'd like to suggest changing your while loop's structure a little.
Currently you are using:
while True:
if <condition>:
break
Rather than:
while <opposite condition>:
You might have a reason for this, but it's not visible from the code you've provided us.
If we change your code to use the latter structure, that alone will simplify the program and fix the main problem.
You also print "Enter a number or 0 to quit:" multiple times, which is unnecessary. You can just pass it to the input and that's enough.
total = 0
number = None
while number != 0:
number = int(input("Enter a number or 0 to quit: "))
total += number # Same as: total = total + number
print("The total number is", total)
The only "downside" (just cosmetics) is that we need to define number before the loop.
Also notice that we want to print the total number after the whole loop is finished, thus the print at the end is unindented and will not be executed on every cycle of the while loop.
You should sum the numbers inside the loop even if they aren't zeros, but print the total after the loop is over, not inside it:
total = 0
while True:
number = int(input("Enter a number or 0 to quit: "))
total = total + number
if number == 0:
break
print ("The total number is", total)
If the number is 0, the first thing you are doing is break, which will end the loop.
You're also not adding the number to the total unless it's 0, which is not what you're after.
while True:
number = int(input("Enter a number or 0 to quit: "))
total = total + number
if number == 0:
break
print ("The total number is", total)
You were very near, but you had some indentation problem.
Firstly, why all these print statements? I guess you are trying to print it before taking input. For this, the below line will be enough.
number = int(input("Enter a number or 0 to quit: "))
Secondly, differentiate between what you want to do, when only the number==0 and what to do in every iteration.
You want to use the below instruction in every iteration as you want every number to be added with total. So, keep it outside if block.
total = total + number
And when number==0, you first want to print something and then break the loop.
if number == 0:
print ("The total number is", total)
break
Make sure you are adding with total first and then checking the if condition, because once you break the loop, you just can't add the number to total later.
So, the solution could be like that,
total = 0
while True:
number = int(input("Enter a number or 0 to quit: "))
total = total + number
if number == 0:
print ("The total number is", total)
break
total = 0
while True:
number = int(input("Enter a number or 0 to quit: "))
if number == 0:
break
total = total + number
print("The total number is", total)
If you put break before your other code, then the loop will be ended and your code after that break will not run.
And by the way, you can use try...except to catch the error if user didn't enter a number:
total = 0
while True:
try:
number = int(input("Enter a number or 0 to quit: "))
except ValueError:
print('Please enter a number')
continue
if number == 0:
break
total = total + number
print("The total number is", total)

Python Help, Max Number of Entries

Created a program for an assignment that requests we make a program that has the user input 20 numbers, and gives the highest, lowest etc. I have the main portion of the program working. I feel like an idiot asking this but I've tried everything setting the max number of entries and everything I've tried still lets the user submit more than 20. any help would be great! I tried max_numbers = 20 and then doing for _ in range(max_numbers) etc, but still no dice.
Code:
numbers = []
while True:
user_input = input("Enter a number: ")
if user_input == "":
break
try:
number = float(user_input)
except:
print('You have inputted a bad number')
else:
numbers.append(number)
for i in numbers:
print(i, end=" ")
total = sum(numbers)
print ("\n")
print("The total amount is {0}".format(str(total)))
print("The lowest number is {0}".format(min(numbers)))
print("The highest number is {0}".format(max(numbers)))
mean = total / len(numbers)
print("The mean number is {0}".format(str(mean)))
Your question could be presented better, but from what you've said it looks like you need to modify the while condition.
while len(numbers) < 20:
user_input = input("Enter a number:" )
....
Now once you've appending 20 items to the numbers list, the script will break out of the while loop and you can print the max, min, mean etc.
Each time the user enters input, add 1 to a variable, as such:
numbers = []
entered = 0
while entered < 20:
user_input = input("Enter a number: ")
if user_input == "":
break
else:
numbers.append(number)
try:
number = float(user_input)
except:
print('You have inputted a bad number')
continue
for i in numbers:
print(i, end=" ")
total = sum(numbers)
print ("\n")
print("The total amount is {0}".format(str(total)))
print("The lowest number is {0}".format(min(numbers)))
print("The highest number is {0}".format(max(numbers)))
mean = total / len(numbers)
print("The mean number is {0}".format(str(mean)))
entered+=1
Every time the while loop completes, 1 is added to the variable entered. Once entered = 20, the while loop breaks, and you can carry on with your program. Another way to do this is to check the length of the list numbers, since each time the loop completes you add a value to the list. You can call the length with the built-in function len(), which returns the length of a list or string:
>>> numbers = [1, 3, 5, 1, 23, 1, 532, 64, 84, 8]
>>> len(numbers)
10
NOTE: My observations were conducted from what I ascertained of your indenting, so there might be some misunderstandings. Next time, please try to indent appropriately.

How do I count the number of entries in a python code using while loops?

I'm working on a homework assignment for my introductory python programming class and I am stuck on a problem. The instructions are to:
Modify the find_sum() function so that it prints the average of the values entered. Unlike the average() function from before, we can’t use the len() function to find the length of the sequence; instead, you’ll have to introduce another variable to “count” the values as they are entered.
I am unsure on how to count the number of inputs and if anyone can give me a good starting point, that would be great!
# Finds the total of a sequence of numbers entered by user
def find_sum():
total = 0
entry = raw_input("Enter a value, or q to quit: ")
while entry != "q":
total += int(entry)
entry = raw_input("Enter a value, or q to quit: ")
print "The total is", total
Every time you read an input total += int(entry), immediately afterward you should increment a variable.
num += 1 is all it would take, after you've initialized it to 0 elsewhere.
Make sure your indentation level is the same for all statements in the while loop. Your post (as originally written) did not reflect any indentation.
You could always use an iteration counter as #BlackVegetable said:
# Finds the total of a sequence of numbers entered by user
def find_sum():
total, iterationCount = 0, 0 # multiple assignment
entry = raw_input("Enter a value, or q to quit: ")
while entry != "q":
iterationCount += 1
total += int(entry)
entry = raw_input("Enter a value, or q to quit: ")
print "The total is", total
print "Total numbers:", iterationCount
Or, you could add each number to a list and then print the sum AND the length:
# Finds the total of a sequence of numbers entered by user
def find_sum():
total = []
entry = raw_input("Enter a value, or q to quit: ")
while entry != "q":
iterationCount += 1
total.append(int(entry))
entry = raw_input("Enter a value, or q to quit: ")
print "The total is", sum(total)
print "Total numbers:", len(total)

Categories