1

I am learning Python. I am trying to create a program that will calculate my final score in college. My question is if I can end an if loop by myself? E.g. I want my program to repeat the question "Do you want to add a grade?" as long as the question is "yes", and as soon as the answer is no, I want my program to leave this part of my code.

What is the easiest way to do this?

noten = [] #list for grades
lp = []    #list for the weight of my different grades
p_antwort = ['y', 'yes'] #p_antwort = positive answer
n_antwort = ['n', 'no']  #n_antwort = negative answer

txt = input("Do you want to add a grade? y/n ")
if txt in p_antwort:
   i = input("What grade did you get? ")
   noten.extend(i)
   txt_2 = input("Do you want to add another one? y/n")
   if txt_2 in p_antwort:
        i = input("What grade did you get? ")
        noten.extend(i)
SuperKogito
  • 2,998
  • 3
  • 16
  • 37
LJ350
  • 21
  • 2
  • Generally this is achieved by the `while` operator in lots of languages. Check here: https://realpython.com/python-while-loop/ – Brian Kung Apr 10 '19 at 22:41
  • Possible duplicate of [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – G. Anderson Apr 10 '19 at 22:53

3 Answers3

2

You can use a while loop, with a done variable, then update done on each iteration of the loop, by checking if the user is interested in adding another entry.

For example:

done = False

while not done:
    # do stuff
    done = input("Want to add another? (y/n)") == "n"

Or you can use a keep_going variable and do basically the opposite of the above code.

Henry Woody
  • 14,024
  • 7
  • 39
  • 56
1

You can use a while loop to keep grabbing grades until the user types in a key to exit the loop such as quit.

grades = [] 

txt = input("What grade did you get? Enter 'quit' to exit: ")
while txt != 'quit':
    grades.append(txt)
    txt = input("What grade did you get? Enter 'quit' to exit: ")

print(grades)

Example interaction

What grade did you get? Enter 'quit' to exit: A

What grade did you get? Enter 'quit' to exit: B

What grade did you get? Enter 'quit' to exit: C

What grade did you get? Enter 'quit' to exit: D

What grade did you get? Enter 'quit' to exit: quit

['A', 'B', 'C', 'D']

Community
  • 1
  • 1
nathancy
  • 42,661
  • 14
  • 115
  • 137
0

The way you could do it is with the while loop.

First you need to instanciate the variable text for the while loop

text = ""
text = input("Do you want to add a grade? y/n ")
while text != "n":
   if txt in p_antwort:
      # do some stuff
   text = input("Do you want to add a grade? y/n ")

I think this should work