User input repeatedly error - python

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)

Related

Python input validation: is there a way to ensure the user only inputs numbers (i.e. floats) that are GREATER than their previous input?

Beginner here, looking for info on input validation.
I need the user to input a set of times that is occurring "during a race" (i.e. we assume that as the user keeps inputting times, the values keep getting bigger and bigger) which will then be stored into a list.
For example: times = [3.2, 3.45, 3.98, 4.32] and so on.
I need to make a way to error-proof this so it tells the user that it had made an "invalid input" by putting down a time that is lower than the previous time user had inputted.
Here is how my code looks thus far which isn't "error-proofed":
cont = "Y"
runners = []
times = []
while(cont != "N"):
if cont == "Y":
#get the name and time of the next runner
runner_name = input("Please enter name of next runner: ")
runner_time = float(input("Please enter runner time: "))
#add the name and time to their respective lists
runners.append(runner_name)
times.append(runner_time)
cont = input("Any more runners to add? (Y/N) ")
#ask if the user is done
if cont != "Y":
if cont == "N":
break
print("Invalid input. Please try again...")
cont = input("Any more runners to add? (Y/N) ")
times[-1] will retrieve the last runner's time. You can compare that to the next input time and throw an error if it breaks your condition. You'll need to create a special case for the first runner, as they do not have a previous runner to compare to so you can't access times[-1].
...
runner_name = input("Please enter name of next runner: ")
while True:
runner_time = float(input("Please enter runner time: "))
if len(times) == 0 or runner_time > times[-1]:
break
else:
print("New time must be greater than last!")
...
This will do the job. The while loop will ask for a valid number over and over again, and since your values in times are increasing, you can compare to the last added element which is given by times[-1]. Note that len(times) deals with the special case of the first runner, where your times list is empty.

Else loop doesn't seem to be triggering when meeting its' parameters?

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))

Python gives me the index numbers instead of the input in the list.

Python gives me the index numbers instead of the input in the list. I'm trying to get the user to give input and then have it store that into a printed list. How do I fix it?
number_of_grades = int(input('How many quizzes have you had?'))
grade_list = []
for grades in range(number_of_grades):
input('Please input a grade from the quiz.')
grade_list.insert(0, grades)
print(grade_list)
It works just fine up until it needs to be printed.
It's because you are not assigning your second input to a variable!, then you are just inserting the index used in the for loop.
number_of_grades = int(input('How many quizzes have you had?'))
grade_list = []
for grades in range(number_of_grades):
value = input('Please input a grade from the quiz.')
grade_list.insert(0, value)
print(grade_list)

Break a for loop that is prompting input to list?

I'm trying to make a simple program that accepts input of 'sales amounts' individually for each day of the week then totals the values and displays them.
I have a loop that accepts 7 inputs, but I would like the user to be able to enter 'q' to break the loop if they have less than 7 inputs.
Here's what I have:
sales = []
for i in range(0, 7):
sales.append(input("> "))
if 'q':
break
It is giving me a NameError, but I've tried a variety of things.
I've done if sales/input/raw_input == "q":.
I've also set q equal to a variable, but that terminated my loop after one iteration.
store the input in a variable so you can reuse it without requiring the user to re-enter the value
user_input = input("> ")
if user_input == "q":
break
sales.append(user_input)

How to repeat getting user's input and keep track of it?

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

Categories