Using range function to display a message - python

I am writing a program for a course that takes user input exam scores and averages them. I have a functioning program, however I need to add a function that uses a range to identify scores entered outside of the 1-100 range and display a message "score out of range. please re enter".
Here is what I have so far:
SENTINEL = float(9999)
scores = []
while True:
number = float(input("Enter exam score (9999 to quit): "))
if number == SENTINEL:
break
scores.append(number)
if not scores:
print("No scores entered")
else:
avg = sum(scores)/len(scores)
print("average of ", len(scores), " test scores is :", avg)

Try this:
SENTINEL = float(9999)
scores = []
while True:
number = float(input("Enter exam score (9999 to quit): "))
while number != SENTINEL and (number < 1 or number > 100):
number = float(input("score out of range. please re enter: "))
if number == SENTINEL:
break
scores.append(number)
if not scores:
print("No scores entered")
else:
avg = sum(scores)/len(scores)
print("average of ", len(scores), " test scores is :", avg)

Related

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)

Two while loops that run simultaneously

I am trying to get the first while True loop to ask a question. If answered with a 'y' for yes, it continues to the second while test_score != 999: loop. If anything other than a y is entered, it should stop.
Once the second while loop runs, the user enters their test scores and enters 'end' when they are finished and the code executes, the first "while True" loop should ask if the user would like to enter another set of test scores. If 'y' is entered, then it completes the process all over again. I know the second one is a nested while loop. However, I have indented it, in PyCharm, per python indentation rules and it still tells me I have indentation errors and would not run the program. That is the reason they are both lined up underneath each other, below. With that said, when I run it as it is listed below, it gives the following answer:
Enter test scores
Enter end to end the input
==========================
Get entries for another set of scores? y
Enter your information below
Get entries for another set of scores? n
((When I type in 'n' for no, it shows the following:))
Thank you for using the Test Scores application. Goodbye!
Enter test score: 80 (I entered this as the input)
Enter test score: 80 (I entered this as the input)
Enter test score: end (I entered this to stop the program)
==========================
Total score: 160
Average score: 80
When I answered 'y', it started a continual loop. When I answered 'n', it did give the print statement. However, it also allowed me to enter in my test scores, input end and execute the program. But, it also did not ask the user if they wanted to enter a new set of test scores. Any suggestions on where I am going wrong?
print("The Test Scores application")
print()
print("Enter test scores")
print("Enter end to end input")
print("======================")
# initialize variables
counter = 0
score_total = 0
test_score = 0
while True:
get_entries = input("Get entries for another set of scores? ")
if get_entries == 'n':
print("Thank you for using the Test Scores application. Goodbye!")
break
else:
print("Enter your information below")
continue
counter = 0
score_total = 0
test_score = 0
while test_score != 999:
test_score = input("Enter test score: ")
if test_score == 'end':
break
elif (int(test_score) >= 0) and (int(test_score) <= 100):
score_total += int(test_score)
counter += 1
elif test_score == 999:
break
else:
print("Test score must be from 0 through 100. Score discarded. Try again.")
# calculate average score
average_score = round(score_total / counter)
# format and display the result
print("======================")
print("Total Score:", score_total,
"\nAverage Score:", average_score)
The while loops should be nested to have recurring entries
print("The Test Scores application")
print()
print("Enter test scores")
print("Enter end to end input")
print("======================")
# initialize variables
counter = 0
score_total = 0
test_score = 0
while True:
get_entries = input("Get entries for another set of scores? ")
if get_entries == 'n':
print("Thank you for using the Test Scores application. Goodbye!")
break
else:
print("Enter your information below")
counter = 0
score_total = 0
test_score = 0
while test_score != 999:
test_score = input("Enter test a score: ")
if test_score == 'end':
break
elif (int(test_score) >= 0) and (int(test_score) <= 100):
score_total += int(test_score)
counter += 1
elif test_score == 999:
break
else:
print("Test score must be from 0 through 100. Score discarded. Try again.")
# calculate average score
average_score = round(score_total / counter)
# format and display the result
print("======================")
print("Total Score:", score_total,
"\nAverage Score:", average_score)
Output:
The Test Scores application
Enter test scores
Enter end to end input
======================
Get entries for another set of scores? y
Enter your information below
Enter test a score: 60
Enter test a score: 80
Enter test a score: 90
Enter test a score: 70
Enter test a score: end
======================
Total Score: 300
Average Score: 75
Get entries for another set of scores? y
Enter your information below
Enter test a score: 80
Enter test a score: 80
Enter test a score: end
======================
Total Score: 160
Average Score: 80
Get entries for another set of scores? n
Thank you for using the Test Scores application. Goodbye!

Figuring out Sum, Product, and Average from User Inputs

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)

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.

Python max and min

I'm pretty new to Python, and what makes me mad about my problem is that I feel like it's really simple.I keep getting an error in line 8. I just want this program to take the numbers the user entered and print the largest and smallest, and I want it to cancel the loop if they enter negative 1.
'int' object is not iterable is the error.
print "Welcome to The Number Input Program."
number = int(raw_input("Please enter a number: "))
while (number != int(-1)):
number = int(raw_input("Please enter a number: "))
high = max(number)
low = min(number)
print "The highest number entered was ", high, ".\n"
print "The lowest number entered was ", low, ".\n"
raw_input("\n\nPress the enter key to exit.")
The problem is that number is an int. max and min both require lists (or other iterable things) - so instead, you have to add number to a list like so:
number = int(raw_input("Please enter a number: "))
num_list = []
while (number != int(-1)):
num_list.append(number)
number = int(raw_input("Please enter a number: "))
high = max(num_list)
low = min(num_list)
Just as a note after reading dr jimbob's answer - my answer assumes that you don't want to account for -1 when finding high and low.
That's cause each time you pass one integer argument to max and min and python doesn't know what to do with it.
Ether pass at least two arguments:
least_number = min(number1, number2,...,numbern)
or an iterable:
least_number = min([number1, number2, ...,numbern])
Here's the doc
You need to change number to an list of numbers. E.g.,
print "Welcome to The Number Input Program."
numbers = []
number = int(raw_input("Please enter a number: "))
while (number != -1):
numbers.append(number)
number = int(raw_input("Please enter a number: "))
high = max(numbers)
low = min(numbers)
print "The highest number entered was ", high, ".\n"
print "The lowest number entered was ", low, ".\n"
raw_input("\n\nPress the enter key to exit.")
As mentioned by another answer, min and max can also take multiple arguments. To omit the list, you can
print "Welcome to The Number Input Program."
number = int(raw_input("Please enter a number: "))
high = low = number
while (number != int(-1)):
number = int(raw_input("Please enter a number: "))
high = max(high, number)
low = min(low, number)
print "The highest number entered was ", high, ".\n"
print "The lowest number entered was ", low, ".\n"
raw_input("\n\nPress the enter key to exit.")
num = ''
active = True
largest = 0
smallest = 0
while active:
num = input("Please enter a number")
if num == 'done':
active = False
break
else:
try:
num = int(num)
if largest < num:
largest = num
if smallest == 0 or smallest > num:
smallest = num
except ValueError:
print("Please enter a valid number")
print("Largest no. is " + str(largest))
print("Smallest no. is " + str(smallest))

Categories