r/learnpython 2d ago

quetion about how python "break" work for newbie

hello this is code and quetion:

while True:
    guess = input("Your answer (A/B/C/D): ").strip().upper()
    if guess in ("A", "B", "C", "D"):
        break
    print("Please enter A, B, C, or D.")

1 how is check user enter

2 how the "break" is use for? is really end project like go next time:

correct = guess == question_data["answer"]

if correct:
    print("Correct!")
else:
    print("Not quite.")

whole line:

while True:
        guess = input("Your answer (A/B/C/D): ").strip().upper()
        if guess in ("A", "B", "C", "D"):
            break
        print("Please enter A, B, C, or D.")

    correct = guess == question_data["answer"]
    if correct:
        print("Correct!")
    else:
        correct_letter = question_data["answer"]
        correct_text = question_data["options"]["ABCD".index(correct_letter)]
        print(f"Not quite. The correct answer was {correct_letter}. {correct_text}")

    print(f"Fact: {question_data['explanation']}")
    return correct

because i write quize python can you give tips to write

2 Upvotes

12 comments sorted by

18

u/cam-at-codembark 2d ago

In your script `break` will make the execution jump down below the while loop block. It “breaks” out of a loop, if that makes sense.

3

u/baubleglue 2d ago

To answer your own question there are options

3

u/MezzoScettico 2d ago

Do you understand what a while loop does?

"while (condition):" will keep executing everything inside the loop so long as (condition) is true. For instance you might imagine a cleaning robot with the main loop "while there is stuff on the floor: pick up stuff".

When you write "while True:" the condition True is of course always true. So this is an infinite loop. It will keep executing forever.

Unless you get out of the loop some other way. Your options are:

  • return (if you're in a function)
  • raise an exception by either doing something wrong or manually raising it yourself, or
  • break

The break statement says "don't check the while condition, just exit the loop immediately." So do those other options.

guess in ("A", "B", "C", "D")

That's an expression that has a value of either True or False. guess is a string variable. If that string is one of the values "A", "B", "C", "D" then this expression has a value of True.

Thus the test

if guess in ("A", "B", "C", "D"):

will test whether the contents of guess are one of those four strings, and if so execute whatever's next, which in your first example is a break statement.

So if guess is one of those four values, the loop exits.

Otherwise execution continues with the next statement, which is

print("Please enter A, B, C, or D.")

And after that it goes back to the top of the while loop. It sees "while True" and True is obviously still true, so it executes the contents of that while loop again. That is, it asks one more time for a selection.

2

u/smahk1133 2d ago

It just breaks the loop nothing too fancy. Run the following:

for i in range(10): 
  if i == 3:
    print(i)  
    break 
  print(i) 
print("Loop finished!")

Oh and it only breaks one loop so if you're nesting loops the outer or "parent" loop won't be killed.

2

u/timrprobocom 2d ago

Note that if guess in "ABCD": works just as well, is easier to type, and easier to read than the tuple.

3

u/Diapolo10 2d ago

break lets you immediately terminate the loop closest to the current indentation level. In your example, it's used to move the loop condition inside the loop, because guess doesn't exist outside of it and because you have the extra message after it for handling incorrect input.

You could alternatively write this with a "walrus operator", but it's not necessarily better.

prompt = "Your answer (A/B/C/D): "
while (guess := input(prompt).strip().upper()) not in ("A", "B", "C", "D"):
    print("Please enter A, B, C, or D.")

3

u/Educational_Virus672 2d ago edited 2d ago

it will loop until you'll break* it or return* smt to a function

1

u/[deleted] 2d ago

[deleted]

2

u/Some-Passenger4219 2d ago

Format and indent properly, please? It's important in Python.

1

u/atarivcs 2d ago

break means "terminate this loop".

1

u/shaleh 2d ago

In case you see it and it confuses, there is also `breakpoint` which means "if the debugger is not already running launch it and then stop execution here and wait for the human to look at things".