For my intro to Python class we are required to make a simplistic program which utilizes the while loop. The program is supposed to take grades, then once the user is done inputting grades it will print the average, highest, and lowest grades. My professor also advised us to just have any negative number be the trigger for the end of inputs.
I've tried using various types of loops to get the program to stop taking inputs but it does not seem to stop when inputting a negative number.
grades = []
print('When done inputting grades input any negative number.')
grade = int(input('Input grades here: '))
while (grade >= 0):
grades.append(grade)
else:
avg_grade = sum(grades) / len(grades)
print('Average grade: ' , avg_grade)
print('Lowest grade: ' , min(grades))
print('Highest grade: ', max(grades))
So basically the only issue with this here is that I can't figure out how to get it to stop taking inputs, it seems to work when I put a . negative number as the first input but I cannot understand why it won't end the loop.
The while loop never modifies grade, so the loop never ends. You need to ask for the input inside the loop.
Rather than duplicating the code that asks for input, just do it once, inside the loop. Use break to stop the loop when you get the terminating value.
There's no need to use else:. That's used when you have a loop that can either run to completion when the condition fails, or terminate early with break, and you want to do something special if it runs to completion. But your loop always ends on the same condition.
while True:
grade = int(input('Input grades here: '))
if grade == 0:
break
avg_grade = sum(grades) / len(grades)
print('Average grade: ' , avg_grade)
print('Lowest grade: ' , min(grades))
print('Highest grade: ', max(grades))
What you are doing is getting the input only once. You need to get the input every single time the loop iterates. The best way of doing this is to add grade = int(input('Input grades here: ')) inside the while loop. This way when you enter into the loop the first time, it checks if the first number you input is a positive, and then every time it iterates, it checks again if your new input is a positive. If it is not, then it will just exit out of the while loop and not iterate again. Also, else statements are normally only used for if and try statements so you do not need it here. Instead just un-indent the lines.
grades = []
print('When done inputting grades input any negative number.')
grade = int(input('Input grades here: '))
while (grade >= 0):
grades.append(grade)
grade = int(input('Input grades here: '))
avg_grade = sum(grades) / len(grades)
print('Average grade: ' , avg_grade)
print('Lowest grade: ' , min(grades))
print('Highest grade: ', max(grades))
Related
I am doing an assignment where I need to calculate an average grade, in one part I have a for loop where it takes the input of 5 quiz grades, I can't figure how to drop the lowest grade out of the ones entered during calculation.
print("Please enter 5 quiz grades.")
print("\t")
for i in range(5):
quizgrade = float(input("Quiz grade: "))
quizgradetotal += quizgrade
print("\t")
here is the code so far.
I have tried changing the loop, but I can't figure it out.
One of the ways you can approach this is to store each entered quiz grade in a list. Then you can drop the lowest grade once you know all of the grades:
quizgrades = [] # Initialize an empty list
print("Please enter 5 quiz grades.")
print("\t")
# Grab all 5 quiz grades
for i in range(5):
quizgrades.append(float(input("Quiz grade: ")))
# Now remove the lowest number from the list
quizgrades.remove(min(quizgrades))
# Now that you have a list with the lowest grade dropped, you can easily calculate the average
average = sum(quizgrades) / len(quizgrades)
print(average)
one solution is to store all your inputs in one array
gards = []
for i in range(5):
gards.append(float(input("Quiz grade: ")))
then remove the lowest grade :
gards.remove(min(gards))
finally you calculate the average of the array :
average = sum(gards) / 4
your solution is good you can overwrite the sum on every input by adding the new value then calculate the average. but the problem is that you will never know which one is the lowest once the loop is over.
I am trying to get into coding and this is kinda part of the assignments that i need to do to get into the classes.
"Write a program that always asks the user to enter a number. When the user enters the negative number -1, the program should stop requesting the user to enter a number. The program must then calculate the average of the numbers entered excluding the -1."
The while loop i can do... The calculation is what im stuck on.
negative = "-1"
passable = "0"
while not passable <= negative:
passable = input("Write a number: ")
I just want to get this to work and a explanation if possible
As pointed out by some of the other answers here, you have to sum up all your answers and divide it by how many numbers you have entered.
However, remember that an input() will be a string. Meaning that our while loop has to break when it finds the string '-1' , and you have to add the float() of the number to be able to add the numbers together.
numbers=[]
while True:
ans=input("Number: ")
if ans=="-1":
break
else:
numbers.append(float(ans))
print(sum(numbers)/len(numbers))
I would initialize a list before asking the user for a number, using a do-while. Then, you add every number to that list unless the number == -1. If it does, then you sum every element in the list and output the average.
Here's pseudocode to help:
my_list = []
do
input_nb = input("Please enter a number: ")
if(input_nb != -1)
my_list.add(input_nb)
while (input_nb != -1)
average = sum(my_list) / len(my_list)
print('My average is ' + average)
You are assigning strings to your variables, which I don't think is your intention.
This will work:
next_input = 0
inputs = []
while True:
next_input = int(input('Please enter a number:'))
if next_input == -1:
break
else:
inputs.append(next_input)
return sum(inputs) / len(inputs)
First, you need to create a container to store all the entered values in. That's inputs, a list.
Next, you do need a while loop. This is another way of structuring it: a loop that will run indefinitely and a check within it that compares the current input to -1, and terminates the loop with break if it does. Otherwise, it appends that input to the list of already entered inputs.
After exiting the loop, the average is calculated by taking the sum of all the values in the entered inputs divided by the length of the list containing them (i.e. the number of elements in it).
I am trying to create a simple program that initializes a list for the grades to be entered by the user and adds grades to the grade list. Also I want my user to be able to repeatedly prompt grades to the list until the user enters a blank grade. My problem is my code does not stop when a blank input is placed by the user.
Here is my initial code:
grade_list=[]
valid_input=True
while valid_input:
grade= input ("Enter your grade:")
grade_list.append(grade)
else:
valid_input= false
print(grade_list)
grade_list = []
while True:
grade = input('Enter your grade: ')
if not grade:
break
grade_list.append(grade)
print(grade_list)
Two problems:
(1) You never change the value of valid_input: you cannot get to the "else" branch.
(2) You don't do anything in the "true" branch to check the input.
You can get rid of the variable and simplify the loop: just grab the first input before the loop, and then control the loop by directly checking the input. This is the "old-school" way to run a top-checking loop.
grade_list = []
grade = input ("Enter your grade:")
while grade:
grade = input ("Enter your grade:")
grade_list.append(grade)
I have a question about input loops and keeping track of it.
I need to make a program that will keep track of all the grades of a class. The thing is that the class size varies every semester, so there is no fixed number assigned to the number of students.
The program will stop taking input when a student enters a grade of -1.
while True:
grade = int(input("Test: "))
if grade < 0:
break
How can I make it so that it keeps track of every single input?
You could use a list comp with iter and get the user to enter -1 to end the loop:
grades = [int(grade) for grade in iter(lambda:input("Enter grade or -1 to exit: "), "-1")]
iter takes a sentinel that will break the loop when entered, so as soon as the user enters -1 the loop will end.
When taking input and casting you should really use a try/except to validate what the users inputs:
grades = []
while True:
try:
grade = int(input(""Enter grade or -1 to exit: ""))
except ValueError:
# user entered bad input
# so print message and ask again
print("Not a valid grade")
continue
if grade == -1:
break
grades.append(grade) # input was valid and not -1 so append it
grades = [] # initialize an empty list
while True:
grade = int(input("Test: "))
if grade < 0:
break
else:
grades.append(grade) # add valid values to the list
Just started working with an older python book, learning about loops and trying to make a loop that accumulates the user input and then displays the total. The problem is the book only shows how to do this with a range, I want to have the user input as many numbers as they want and then display the total, so for example if the user entered 1,2,3,4 I would need python to output 10, but I don't want to have python tied down to a range of numbers.
here is the code I have WITH a range, as I stated above, I need to do this user input without being tied down to a range. Also do I need to apply a sentinel for the kind of program I want to make?
def main():
total = 0.0
print ' this is the accumulator test run '
for counter in range(5): #I want the user to be able to enter as many numbers
number = input('enter a number: ') #as they want.
total = total + number
print ' the total is', total
main()
You'll want a while-loop here:
def main():
total = 0.0
print ' this is the accumulator test run '
# Loop continuously.
while True:
# Get the input using raw_input because you are on Python 2.7.
number = raw_input('enter a number: ')
# If the user typed in "done"...
if number == 'done':
# ...break the loop.
break
# Else, try to add the number to the total.
try:
# This is the same as total = total + float(number)
total += float(number)
# But if it can't (meaning input was not valid)...
except ValueError:
# ...continue the loop.
# You can actually do anything in here. I just chose to continue.
continue
print ' the total is', total
main()
Using your same logic, only replace it with a while loop. The loop exits when the user types 0
def main():
total = 0
print 'this is the accumulator test run '
while True:
number = input('enter a number: ')
if number == 0:
break
total += number
print 'the total is', total
main()
Just for fun, here is a one line solution:
total = sum(iter(lambda: input('Enter number (or 0 to finish): '), 0))
If you want it to display right away:
print sum(iter(lambda: input('Enter number (or 0 to finish): '), 0))
Use a while-loop to loop an indeterminate number of times:
total = 0.0
print 'this is the accumulator test run '
while True:
try:
# get a string, attempt to cast to float, and add to total
total += float(raw_input('enter a number: '))
except ValueError:
# raw_input() could not be converted to float, so break out of loop
break
print 'the total is', total
A test run:
this is the accumulator test run
enter a number: 12
enter a number: 18.5
enter a number: 3.3333333333333
enter a number:
the total is 33.8333333333