how to get the average using for loop in python - python

In this exercise you will create a program that #computes the average of a collection of values #entered by the user. The user will enter 0 as a #sentinel value to indicate that no further values #will be provided. Your program should display an #appropriate error message if the first value entered #by the user is 0.
print("You first number should not be equal to 0.")
total=0
average_of_num=0
i=0
num=input("Enter a number:")
for i in num:
total=total+num
i=i+1
num=input("Enter a number(0 to quit):")
if i==0:
print("A friendly reminder, the first number should not be equal to zero")
else:
average_of_num=total/i
print("Counter",i)
print("The total is: ", total)
print("The average is: ",average_of_num)

See if this works for you.
entry_list = []
while True:
user_entry = int(input("Enter a non Zero number(0 to quit entering: "))
if user_entry == 0:
break
entry_list.append(user_entry)
total = 0
for i in entry_list:
total = total + i
avg = total/len(entry_list)
print("Counter",len(entry_list))
print("The total is: ", total)
print("The average is: ",avg)

If only for loop should be used try this..
num=[int(input("Enter a number:"))]
total=0
for i in num:
if i == 0:
break
total=total+i
x = int(input("Enter a number(0 to quit):"))
if x != 0:
num.append(x)
avg = total/len(num)
print("Counter: ",len(num))
print("The total is: ", total)
print("The average is: ",avg)

Related

Intro to Python: How to ask the user if they want to repeat the for loop?

I need help figuring out how to ask the user if they would like to repeat the program. Any help is much appreciated. I am relatively new to Python and it would be great to receive some advice!
X = int(input("How many numbers would you like to enter? "))
Sum = 0
sumNeg = 0
sumPos = 0
for i in range(0,X,1):
number = float(input("Please enter number %i : " %(i+1) ))
# add every number to Sum
Sum = Sum + number # Sum += number
#only add negative numbers to sumNeg
if number < 0:
sumNeg += number # sumNeg = sumNeg + number
#only add positive numbers to sumPos
if number > 0:
sumPos += number # sumPos = sumPos + number
print ("------")
print ("The sum of all numbers = ", Sum)
print ("The sum of negative numbers = ", sumNeg)
print ("The sum of positive numbers = ", sumPos)
I'm not sure if I need to use a while loop, but how would I enter a (y/n) into my code because I am asking for an integer from the user in the beginning.
Ask the user for input at the end of the loop to continue or not. If the user doesn't want to continue, use a break statement to break out of the loop.
https://www.simplilearn.com/tutorials/python-tutorial/break-in-python#:~:text='Break'%20in%20Python%20is%20a,condition%20triggers%20the%20loop's%20termination.
Have an outer loop that comprises your whole processing.
It's an infinite loop.
You exit from this loop thanks to the break statement once the user has answered no.
In fact once he has answered everything else than Y or y. The user string is converted to lower() before comparison for more convenience.
while True:
X = int(input("How many numbers would you like to enter? "))
Sum = 0
sumNeg = 0
sumPos = 0
for i in range(0, X, 1):
number = float(input("Please enter number %i : " % (i + 1)))
# add every number to Sum
Sum = Sum + number # Sum += number
# only add negative numbers to sumNeg
if number < 0:
sumNeg += number # sumNeg = sumNeg + number
# only add positive numbers to sumPos
if number > 0:
sumPos += number # sumPos = sumPos + number
print("------")
print("The sum of all numbers = ", Sum)
print("The sum of negative numbers = ", sumNeg)
print("The sum of positive numbers = ", sumPos)
resp = input("Would you like to repeat the program ? (y/n)")
if resp.lower() != "y":
break
As an alternative to the while True loop.
You could declare at the top of the script a variable user_wants_to_play = True.
The while statement becomes while user_wants_to_play.
And set the variable to False when the user answers no.
The following program will keep on executing until user enter 0 to break the loop.
while True:
X = int(input("How many numbers would you like to enter? "))
Sum, sumNeg, sumPos = 0
for i in range(X):
number = float(input("Please enter number %i : " %(i+1) ))
Sum += number
if number < 0:
sumNeg += number
if number > 0:
sumPos += number
print ("------")
print ("The sum of all numbers = ", Sum)
print ("The sum of negative numbers = ", sumNeg)
print ("The sum of positive numbers = ", sumPos)
print ("------")
trigger = int(input("The close the program enter 0: "))
if trigger == 0:
break

Write an application that allows a user to enter any number of student test scores until the user enters 999

Write a python application that allows a user to enter any number of student test scores until the user enters 999. If the score entered is less than 0 or more than 100, display an appropriate message and do not use the score. After all the scores have been entered, display the number of scores entered and the arithmetic average.
I am having trouble breaking the loop when the score entered is less than 0 or more than 100.
The code I have is
total_sum = 0
count = 0
avg = 0
numbers = 0
while True:
num = input("Enter student test score: ")
if num == "999":
break
if num < "0":
break
print("Number is incorrect")
if num > "100":
break
print ("Number is incorrect")
total_sum += float(num)
count += 1
numbers = num
avg = total_sum / count
print("The average is:", avg)
print("There were " +str(count) + " numbers entered")
There are multiple issues with your code.
You want to compare numbers, not strings. Try using float(input(...))
break will break out of the loop in exactly the same way for numbers under 0, above 100, or for the "finished" token 999. That's not what you described that you want. Rather, for "incorrect numbers" just print the message, and don't add the numbers and counter...But no need to break the loop, amirite?
You've got an indentation problem for the < 100 case. Your print is missing an indentation.
No need to have avg = 0
numbers isn't used
Try something like -
total_sum = 0
count = 0
while True:
num = float(input("Enter student test score: "))
if num == 999:
break
elif num < 0 or num > 100:
print("Number is incorrect")
else:
total_sum += num
count += 1
avg = total_sum / count
print("The average is:", avg)
print("There were " +str(count) + " numbers entered")

Calculate Maximun, Minimun, Average of n numbers

The question is to write a program that asks the user to enter a series of numbers and output, the maximum number in the series, the minimum number in the series, and the average of all the POSITIVE numbers.
The current code I have calculates for the minimum and maximum, but I don't know how to write a code to make it calculate the average.
maximum = None
minimum = None
num = None
while True:
inp = input("PLease enter a number: ")
if inp == "#" :
break
try:
num=float(inp)
except:
print ("Error with this input")
continue
if maximum is None:
maximum = num
minimum = num
if num>maximum:
maximum=num
if num<minimum:
minimum=num
print ("The Maximum is ", maximum)
print ("The Minimum is ", minimum)
You store all inputted numbers in a list and calculate from there:
def avg_pos(d):
if len(d) == 0: # avoid div by 0
return 0
return sum(d)/len(d)
data = []
while True:
try:
n = input("Number: ")
if n == "#":
break
n = int(n)
data.append(n)
except ValueError:
print("Not a number")
print( f"Min: {min(data)} Max: {max(data)} AvgP: {avg_pos([d for d in data if d>0])}" )
Output:
Number: 4
Number: 5
Number: 6
Number: -2
Number: -99
Number: 73
Number: #
Min: -99 Max: 73 AvgP: 22.0
Find the sum each time a positive number is accepted and count each number. At the end you can determine the average
maximum = None
minimum = None
sum_of_positive = 0
count_of_positive = 0
num = None
while True:
inp = input("PLease enter a number: ")
if inp == "#" :
break
try:
num=float(inp)
except:
print ("Error with this input")
continue
if maximum is None:
maximum = num
minimum = num
if num>maximum:
maximum=num
if num<minimum:
minimum=num
if num > 0:
sum_of_positive = sum_of_positive + num
count_of_positive = count_of_positive + 1
if count_of_positive > 0:
average_of_positive = sum_of_positive / count_of_positive
else:
average_of_positive = 0
print ("The Maximum is ", maximum)
print ("The Minimum is ", minimum)
print ("The Average of Positive Numbers is ", average_of_positive)
You need to add a counter variable to know how many rounds you got in the loop.
And also you need a total variable to sum all the num
Then you just need to print total/counter
Use library functions like max, min and sum.
For example max([1,2,3,5,11,8]) gives you 11, min([1,2,3,5,11,8]) gives you 1 and sum([1,2,3,5,11,8]) gives you 30.
So lets say you read the numbers in to a list named numbers, then getting the maximal number is max(numbers), the minimal is min(numbers) and the average is sum(numbers)/len(numbers).
Please notice that if you use python 2 then you need to convert to float before dividing, like this float(sum(numbers))/len(numbers).

How do i find the biggest number that are not in a list?

I am trying to make a program that gives you the average, total, and biggest number entered. I am stuck at the biggest number part. My numbers are not in a list, so I don't know how to find the biggest one.
num=0
total=0
average=0
count=0
while True:
num=input("enter a number:")
num=int(num)
if num==-999:
break
total=total + num
count=count+1
biggest = max(total)
average=total/count
#print the results
print("the total is:", total)
print("the biggest number is:", biggest)
print("the average is:", average)
I would like it to print the biggest number at the end.
Thanks
num=0
total=0
average=0
count=0
biggest=0
while True:
num=input("enter a number:")
num=int(num)
if num==-999:
break
total=total + num
count=count+1
if num > biggest:
biggest = num
average=total/count
#print the results
print("the total is:", total)
print("the biggest number is:", biggest)
print("the average is:", average)
you can just:
if num > biggest:
biggest = num
Let me share you a solution for your problem. (Take a look at the if clause after the check of the number being "-999"). Feel free to ask if you have any questions! Hope it helps you
num=0
total=0
average=0
count=0
biggest=0
while True:
num=input("enter a number:")
num=int(num)
if num==-999:
break
if num > biggest:
biggest = num
total=total + num
count=count+1
average=total/count
#print the results
print("the total is:", total)
print("the biggest number is:", biggest)
print("the average is:", average)
initialize biggest with a value which can not be bigger than any input:
import numpy
biggest = -np.inf
replace
biggest = max(total)
by
biggest = max(biggest, num)
Here idited your code to be right
num=0
total=0
average=0
count=0
biggest = None ### added
while True:
num=input("enter a number:")
num=int(num)
if num==-999:
break
total=total + num
count=count+1
#biggest = max(total) Here where was you wrong
if num > biggest : #### added
biggest = num #### added
average=total/count
#print the results
print("the total is:", total)
print("the biggest number is:", biggest)
print("the average is:", average)
If you look into some other methods you can get a lot more functionality and do even more with your program, take a look at this code and try to take some ideas it could make your task and future tasks easier for you
numbers = []
print("Enter any non-number to perform calculations.\n")
while True:
try:
num = int(input("Enter a number: "))
numbers.append(num)
except ValueError:
break
total = sum(numbers)
average = total/len(numbers)
biggest = max(numbers)
print(f"\nThe total is: {total}")
print(f"The biggest number is: {biggest}")
print(f"The average is: {average}")
(xenial)vash#localhost:~/python$ python3.7 biggest.py
Enter any non-number to perform calculations.
Enter a number: 1
Enter a number: 2
Enter a number: 3
Enter a number: 4
Enter a number: -1
Enter a number: 2
Enter a number: 3
Enter a number: q
The total is: 14
The biggest number is: 4
The average is: 2.0
Initialize a variable biggest before the loop:
biggest = -9999
This should be initialized to something smaller than any of the numbers that the program is going to encounter. The above assumes that -9999 is such a number which is a bad assumption in general; there are better ways to accomplish that, e.g. one of the comments suggests
import sys
biggest = -sys.maxint
That's the negative of the maximum integer value that this implementation can represent.
Then in the body of the loop, update the variable biggest:
biggest = max(biggest, num)
If num is bigger than biggest then max(biggest, num) will return the value of num so that biggest will get the value of num. If it is smaller, biggest will stay unchanged. In other words, biggest remembers the largest value seen so far. At the end of the loop, it will then hold the largest value seen, period.

Python: Write a program that counts positive and negative numbers and computers the average of numbers

I saw a similar post, but it included functions, which mine does not.
Objective: Write a program that reads an unspecific number of integers, determines how many positive and negative values have read, and computes the total and average of the input values (not counting 0's) while the program will halt at 0.
ISSUE I AM HAVING: When using the following test values
1,
2,
-1,
3
I get the following:
The number of positives: 1
The number of negatives: 2
The total amount of numbers used: 3
The average is 1.33 which is 4 / 3
It should be:
The number of positives: 1
The number of negatives: 3
The total amount of numbers used: 4
The average is 1.25 which is 5 / 4
My Attempt below:
positive_number = 0
negative_number = 0
average = 0
count = 0
new_number = 0
user_input = eval(input("Enter enter as many integers as you want, 0 will halt: "))
if user_input == 0:
print("You didn't enter any number, code ended")
else:
while user_input != 0:
user_input = eval(input("Enter enter as many intergers as you want, 0 will halt: "))
if user_input == 0:
print("You didn't enter any number, code ended")
elif user_input != 0 and user_input > 0:
new_number += user_input
positive_number += 1
count += 1
else:
user_input != 0 and user_input < 0
new_number += user_input
negative_number += 1
count += 1
average = (new_number / count)
print("\nThe number of positives:", positive_number)
print("The number of negatives:", negative_number)
print("The total amount of numbers used:", count)
print("The average is", format(average,".2f"), "which is", str(new_number), "/", str(count))
What is causing such error? I can only assume that this is a minor fix?
I've fixed the problems in your code and refactored to trap error conditions and removed unnecessary complications:
positive_number = 0
negative_number = 0
average = 0
count = 0
total = 0
user_input = None
while user_input != 0:
try:
user_input = int(input("Enter enter as many intergers as you want, 0 will halt: "))
except ValueError:
user_input=0
if user_input > 0:
total += user_input
positive_number += 1
count += 1
elif user_input<0:
total += user_input
negative_number += 1
count += 1
if count==0:
print("You didn't enter any number, code ended")
else:
average = total / count
print("\nThe number of positives:", positive_number)
print("The number of negatives:", negative_number)
print("The total amount of numbers used:", count)
print("The average is", format(average,".2f"), "which is", str(total), "/", str(count))
First, the first if statement is redundant as you test for user_input != 0 as the loop condition. Second, the reason it was going wrong was because on your first input you immediately overwrote the value of user_input, so I put the reprompt code at the end of the loop. Finally, I cleaned up the if elif else statement as this does the exact same with fewer characters. The print statement for the closing line is also executed once we pull out of the loop - sinc eby definition that means user_input == 0
positive_number = 0
negative_number = 0
average = 0
count = 0
new_number = 0
user_input = eval(input("Enter enter as many integers as you want, 0 will halt: "))
while user_input != 0:
if user_input > 0:
new_number += user_input
positive_number += 1
count += 1
else:
new_number += user_input
negative_number += 1
count += 1
average = (new_number / count)
print("\nThe number of positives:", positive_number)
print("The number of negatives:", negative_number)
print("The total amount of numbers used:", count)
print("The average is", format(average,".2f"), "which is", str(new_number), "/", str(count))
user_input = eval(input("Enter enter as many intergers as you want, 0 will halt: "))
print("You didn't enter any number, code ended")
Like it was said in the comments, your first input is getting ignored. Here is an alternative that should work. I excluded a few redundant check statements.
positive_number = 0
negative_number = 0
average = 0
count = 0
new_number = 0
user_input = 1
while user_input != 0:
user_input = eval(input("Enter enter as many integers as you want, 0 will halt: "))
if user_input == 0:
print("You didn't enter any number, code ended")
elif user_input > 0:
new_number += user_input
positive_number += 1
count += 1
else:
new_number += user_input
negative_number += 1
count += 1
average = (new_number / count)
print("\nThe number of positives:", positive_number)
print("The number of negatives:", negative_number)
print("The total amount of numbers used:", count)
print("The average is", format(average,".2f"), "which is", str(new_number), "/", str(count))
There are a number of issues with your code. First of all, the first number that the user prompts is not being evaluated by the code; it's being overwritten once you get to the while loop. There are multiple ways to fix this, but the best would be along the lines:
cont = True
while cont is True:
user_input = int(input("Prompt user"))
if user_input == 0:
cont = False
You could do a break statement too, it doesn't matter.
So that takes care of why the first number isn't being read, and why the code thinks there were only 3 inputs (as well as your count being off). Now what about the two negatives? I don't know why you got that. When I inputted the numbers you listed, I got one negative and two positives. Try it again and see if it works now, I suspect you must've mistyped.

Categories

Resources