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)
Related
we have been tasked with writing a program in python asking a user to enter multiple numbers.
the subject is while loops,so we can only make use of while loops and if statements.
when the user wants to stop the entry of numbers,the user then needs to type '-1'.
once that has been done,the program must return the average of the numbers entered by the user.
this is what i have so far:
#task 13-while.py
#first the program will explain to the user that the user can keep
#entering numbers until -1 occurs.
num = int(input('''please enter any number of your choice\n
please enter -1 to stop entry and run program'''))
num_count = 0
while num > -1:
num_count = num_count + 1
average = sum(num)/num_count
if num == -1:
print("the average of the numbers you have entered is"+ average)
extremely inexperienced with python,all help will be greatly appreciated.
You need to put the input into the while and then only when the loop is over calculate the averageLike this:
num = int(input("enter numbers and then -1 to stop: "))
num_count = 1
sum = num
while num!=-1:
num = int(input("another number: "))
num_count+=1
sum+=num
print(sum/num_count)
In order for it to work you need to add an input() call inside the while loop like in the code bellow :
count = 0
sum = 0
num = int(input('''please enter any number of your choice\n
please enter -1 to stop entry and run program\n'''))
while num != -1:
sum += num
count +=1
num = int(input('''Give another integer\n'''))
print("the average of the numbers you have entered is", sum/count)
Personal advice : I would suggest for you to read more tutorials or ask your peofessor for more work
how_many_number = int(input("How many number do you want to print? "))
for take_number in how_many_number:
take_number = int(input("Enter number: "))
sum = 0
sum = sum + take_number
print(sum)
Here you go. To take user input we can use a for loop and for each iteration we can add it to our sum using += operator. You can read through the following code to understand it well enough.
number_of_inputs = int(input("How many number to sum: ")
sum = 0 # Initialize the sum variable
for x in range(number_of_inputs): # Repeat the number of inputs times
sum += int(input("Enter Value: ")) # Take a input and add it to the sum
print("Sum is", sum) # print out the sum after completing
You can also compress it into a List Comprehension, like this...
how_many_number = int(input("How many number do you want to print? "))
print(sum([int(input("Enter number: ")) for i in range(how_many_number)]))
i would use the following, note: error handle is not yet incorporated.
num_list = []
### create a function that adds all the numbers entered by a user
### and returns the total sum, max 3 numbers
### return functions returns the entered variables
def add_nums():
while len(num_list) < 3:
user_num = int(input('please enter a number to add:'))
num_list.append(user_num)
print('You have entered the following numbers: ',num_list)
total_num_sum = 0
for x in num_list:
total_num_sum += x
print('total sum of numbers = ',total_num_sum)
add_nums()
Also, please follow the StackOverFlow post guidelines; have your post title as a problem question, it has to be interesting for other devs, and add more emphasis on why you want to add numbers entered by user vs running calc on a existing or new data-frame, need more meat.
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)
I am trying to write a program that will add together a series of numbers that the user inputs until the user types 0 which will then display the total of all the inputted numbers. this is what i have got and im struggling to fix it
print ("Keep inputting numbers above 0 and each one will be added together consecutively. enter a and the total will be displayed on the screen. have fun")
number = input("Input a number")
sum1 = 0
while number >= 1:
sum1 = sum1 + number
if number <= 0:
print (sum1)
Here is a more robust way to input the number. It check if it can be added. Moreover I added the positive and negative number.
# -*-coding:Utf-8 -*
print ("Keep inputting numbers different than 0 and each one will be added together consecutively.")
print ("Enter a and the total will be displayed on the screen. Have fun.")
sum = 0
x = ""
while type(x) == str:
try:
x = int(input("Value : "))
if x == 0:
break
sum += x
x = ""
except:
x = ""
print ("Please enter a number !")
print ("Result : ", sum)
If you're using Python 3, you will need to say number = int(input("Input a number")) since input returns a string. If you're using Python 2, input will work for numbers but has other problems, and the best practice is to say int(raw_input(...)). See How can I read inputs as integers? for details.
Since you want the user to repeatedly enter a number, you also need an input inside the while loop. Right now it only runs once.
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.