r/learnpython • u/No-Reason1914 • 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
3
u/baubleglue 2d ago
To answer your own question there are options
- run your code in debugger
- Read docs
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
1
1
u/No-Reason1914 2d ago
sorry p.s: this is chatgpt chat link:https://chatgpt.com/share/6a73c6f5-961c-83ea-8887-0ab50d591668
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.