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).
Related
I'm working on a project for school and can't figure out how to get the average of the positive user entered inputs and the average of the negative user entered inputs and have it display. I think I'm on the right track and I feel that I'm only missing a step or two to get the program completed. This is what I have to start:
print("(enter '0' to stop)")
cout_pos=0
count_neg=0
sum= 0.0
num=1
while num != 0:
num = int(input("enter value: "))
if num > 0:
sum = sum + num
count_pos +=1
if num < 0:
sum = sum + num
count_neg -=1
if sum == 0:
print("no values were entered")
else:
print('positive average: ' ,sum/(count_pos-1))
print('negative average: ' ,sum/(count_neg))
Thanks for the help!
To have this working correctly you need to create separete variables for the sumation, like you are doing with the counts, otherwise you'll have overlapping:
print("(enter '0' to stop)")
count_pos=0
count_neg=0
sum_pos= 0
sum_neg= 0
num=1
while num != 0:
num = int(input("enter value: "))
if num > 0:
sum_pos = sum_pos + num
count_pos +=1
if num < 0:
sum_neg = sum_neg + num
count_neg -=1
if sum == 0:
print("no values were entered")
else:
print('positive average: ' ,sum_pos/(count_pos))
print('negative average: ' ,sum_neg/(count_neg))
Output:
enter value: 4
enter value: 4
enter value: 3
enter value: 3
enter value: -2
enter value: -4
enter value: 0
positive average: 3.5
negative average: 3.0
This is another version:
def average(lst):
""" Count average from the list of numbers """
return sum(lst) / len(lst)
positive = [] # list of positive numbers
negative = [] # list of negative numbers
num = None
print("(enter '0' to stop)")
while True:
try: # try to enter float values
num = float(input('enter value: '))
except ValueError: # non-number was entered
print('please, enter only numbers')
continue # start from beginning of while loop
if num > 0: # if positive, append number to positive list
positive.append(num)
elif num < 0: # if negative, append number to negative list
negative.append(num)
else: # if zero, exit from the while loop
break
# Use f-strings to print for Python 3.7 and higher
if len(positive):
print(f'positive average: {average(positive)}')
if len(negative):
print(f'negative average: {average(negative)}')
if len(positive) == 0 and len(negative) == 0:
print('no values were entered')
The output is:
(enter '0' to stop)
enter value: 1.5
enter value: 3.7
enter value: a
please, enter only numbers
enter value: 4.6
enter value: -2.78
enter value: -9.99
enter value: 0a
please, enter only numbers
enter value: 0.0
positive average: 3.266666666666667
negative average: -6.385
I'm attempting to write a program that lets the user input a list of numbers and tell them maximum and minimum numbers. The program should let the user choose the allowable minimum and maximum values, and should not let the user input something to the list that is outside of these bounds. I've managed to get the first bit done but I have no idea how to filter data outside of a range. Help would be greatly appreciated.
print ("Input done when finished")
print ("Input thresholds")
maximumnum = int(input("Input maximum number: "))
minimumnum = int(input("Input minimum number: "))
minimum = None
maximum = None
while True:
inp =input("Enter a number: ")
if inp == "done":
break
try:
num = float(inp)
except:
print ("Invalid input")
continue
if minimum is None or num < minimum:
minimum = num
if maximum is None or num > maximum:
maximum = num
print ("Maximum:", maximum)
print ("Minimum:", minimum)
You need to add this additional check below the try/except block:
# To check your number is not greater than maximum allowed value
if num > maximumnum:
print('Number greater the maximum allowed range')
break
# To check your number is not smaller than maximum allowed value
if num < minimumnum:
print('Number smaller the maximum allowed range')
break
Hence, your complete code will become:
print ("Input done when finished")
print ("Input thresholds")
maximumnum = int(input("Input maximum number: "))
minimumnum = int(input("Input minimum number: "))
minimum = None
maximum = None
while True:
inp =input("Enter a number: ")
if inp == "done":
break
try:
num = float(inp)
except:
print ("Invalid input")
continue
## ---- Additional Check ---- ##
if num > maximumnum:
print('Number greater the maximum allowed range')
break
if num < minimumnum:
print('Number smaller the maximum allowed range')
break
## -------------------------- ##
if minimum is None or num < minimum:
minimum = num
if maximum is None or num > maximum:
maximum = num
print ("Maximum:", maximum)
print ("Minimum:", minimum)
I'm trying to assign a value to the two starting variables in the following code, and change them if necessary (first if and elif), but the smallest gets changed to the string "done" while the largest stays untouched. what am I missing ?
Thank you very much
largest = 0
smallest = 999
while True:
num = raw_input("Enter a number: ")
if largest > num:
largest = num
elif smallest < num:
smallest = num
try:
num = int(num)
except ValueError:
print "Invalid input"
if num == "done" : break
print "Maximum is", largest
print "Minimum is", smallest
Edited the code as per suggestions as follow:
largest = None
smallest = None
while True:
num = raw_input("Enter a number: ")
try:
num = int(num)
if num > largest:
largest = num
elif smallest < num:
smallest = num
except ValueError:
print "Invalid input"
if num == "done" : break
print "Maximum is", largest
print "Minimum is", smallest
Now it runs correctly
I was tasked with creating a program that takes all the inputted numbers and adds them together except the highest integer out of that list. I am suppose to use while and if then logic but I cannot figure out how to exclude the highest number. I also had to make the program break when the string "end" was put into the console. So far I have,
total = 0
while 1 >= 1 :
value = input("Enter the next number: ")
if value != "end":
num = float(value)
total += num
if value == 'end':
print("The sum of all values except for the maximum value is: ",total)
return total
break
I just have no idea how to make it disregard the highest inputted number. Thanks in advance! I am using python 3 fyi.
Is this what you're trying to do?
total = 0
maxValue = None
while True:
value = input("Enter the next number: ")
if value != "end":
num = float(value)
maxValue = num if maxValue and num > maxValue else num
total += num
else:
print("The sum of all values except for the maximum value is: ",total-maxValue )
# return outside a function is SyntaxError
break
Here you go in regards to keeping it close to your original. Using lists is great in python for this sort of thing.
list = []
while True:
num = input("Please enter value")
if num == "end":
list.remove(max(list))
return sum(list)
else:
list.append(int(num))
if you input 1,2 and 3 this would output 3 - it adds the 1 and 2 and discards the original 3.
You've said it's an assignment so if lists aren't allowed then you could use
max = 0
total = 0
while True:
num = input("Please enter value")
if str(num) == "end":
return total - max
if max < int(num):
max = int(num)
total += int(num)
the easiest way to achieve the result you want is to use python's builtin max function (that is if you don't care about performance, because this way you are actually iterating over the list 2 times instead of one).
a = [1, 2, 3, 4]
sum(a) - max(a)
This not exactly the same as you want it to do, but the result is going to be the same (Since instead of not adding the largest item you can just subtract it in the end).
This should work for you.
total = 0
highest = None
while True:
value = input("Enter the next number: ")
if value != 'end':
num = float(value)
if highest is None or num > highest:
highest = num
total += num
else:
break
print("The sum of all values except for the maximum value is: ",total-highest )
print(total-highest)
I'm trying to write this program which asks for numbers and stores the smallest and largest in two variables which are both None at the beginning.
Somehow the largest number is stored as I want it but the smallest number never makes it.
Here's my code:
largest = None
smallest = None
while True:
inp = raw_input("Enter a number: ")
if inp == "done" : break
try :
num = int(inp)
except :
print "Invalid input"
continue
if num == None or num < smallest :
num = smallest
if num == None or num > largest :
num = largest
print "Maximum is", largest
print "Minimum is", smallest
As soon as I typed in some numbers and end the program with "done" the output looks like this:
Maximum is 56
Minimum is None
I checked the indentation a couple of times.
Don't you mean :
if smallest is None or num < smallest :
smallest = num
if largest is None or num > largest :
largest = num
instead of :
if num == None or num < smallest :
num = smallest
if num == None or num > largest :
num = largest
Because nothing is ever stored in smallest nor largest in the code you posted and as pointed by #MartijnPieters None is always smaller than numbers in python 2.
You can check this link : Is everything greater than None? for further information on that subject.
Also I'd prefer using explicit except such as except ValueError: in you case rather than something that catches everything.
Largest and smallest are never assigned to.
And in the spirit of writing pythonically, you can use min and max :)
largest = None
smallest = None
a=[]
while True:
inp = raw_input("Enter a number: ")
if inp == "done" : break
try :
num = int(inp)
a.append(num)
except :
print "Invalid input"
continue
smallest=a[0]
for x in a:
if x<smallest:
smallest=x
largest=max(a)
print "Maximum is", largest
print "Minimum is", smallest
You can replace the for loop with smallest=min(a)
#d6bels Answer is correct, but you need to add:
if smallest == None:
smallest = num
if largest == None:
largest = num
all code applied:
largest = None
smallest = None
a=[]
while True:
inp = raw_input("Enter a number: ")
if inp == "done": break
try:
num = int(inp)
a.append(num)
except:
print("Invalid input")#For the sake of 2.x-3.x compatability, format your
if smallest == None: #prints as a function
smallest = num
if largest == None:
largest = num
smallest=a[0]
for x in a:
if x<smallest:
smallest=x
largest=max(a)
print("Maximum is " + str(largest))
print("Minimum is " + str(smallest))