LJ350
LJ350

Reputation: 21

How can i end a loop by myself?

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)

Upvotes: 1

Views: 77

Answers (3)

Leandro A.G.
Leandro A.G.

Reputation: 51

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

Upvotes: 0

nathancy
nathancy

Reputation: 46600

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']

Upvotes: 1

Henry Woody
Henry Woody

Reputation: 15662

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.

Upvotes: 2

Related Questions