Thủ Thuật về How to end while loop python Mới Nhất
Bùi Đàm Mai Phương đang tìm kiếm từ khóa How to end while loop python được Cập Nhật vào lúc : 2022-09-30 17:36:25 . Với phương châm chia sẻ Bí quyết Hướng dẫn trong nội dung bài viết một cách Chi Tiết Mới Nhất. Nếu sau khi tham khảo tài liệu vẫn ko hiểu thì hoàn toàn có thể lại phản hồi ở cuối bài để Mình lý giải và hướng dẫn lại nha.Python provides three ways to stop a while loop:
Nội dung chính- Method 1: While Loop ConditionMethod 2: Keyword “break”Method 3: Keyword “continue”Python Keywords Cheat SheetProgrammer HumorHow do you end a while loop?How do you stop a while loop in a for loop?Do you have to end a while loop in Python?
You can see each of these three methods to terminate a while loop in the following graphic:
Figure: Terminate a while loop through (a) the loop condition, (b) the break keyword, or (c) the continue keyword.To exemplify these methods, you’ll learn how to use each of them to accomplish the same thing: remove the first character from a string until only 5 elements remain.
You can also watch my explainer video as you go through the article:
How to Stop a While Loop in Python?
- Method 1: While Loop ConditionMethod 2: Keyword “break”Method 3: Keyword “continue”Python Keywords Cheat SheetSummaryProgrammer Humor
Method 1: While Loop Condition
The most Pythonic way to end a
while loop is to use the while condition that follows immediately after the keyword while and before the colon such as while
Here’s an example that shows how the while loop ends as soon as a given string consists of 5 or fewer characters. In each iteration, you reduce the length of the string in variable s by one using string slicing, so the loop will eventually terminate, no matter the initial length of the string.
s="hello world" while len(s) > 5: s = s[1:] print(s) # worldMethod 2: Keyword “break”
If the program executes a statement with the keyword break, the loop terminates immediately. No other statement in the loop body toàn thân is executed and the program proceeds with the first statement after the loop construct. In most cases, you’d use the keyword break in an if construct to decide dynamically whether a loop should end, or not.
In the following example, we create a string with 11 characters and enter an indefinite while loop with a loop condition that is always fulfilled (while True). If you didn’t end the loop prematurely in the loop body toàn thân, Python would run this code forever.
s="hello world" while True: if len(s) > 5: s = s[1:] else: break print(s) # worldFortunately, you add an if construct that contains the break keyword in the else branch. As soon as the if condition evaluates to False, the else branch is executed and the break statement is executed—the loop ends.
Only a string with 5 or fewer characters causes the if condition to evaluate to False, so the loop ends as soon as s holds the string 'world'.
Method 3: Keyword “continue”
The keyword continue terminates only the current loop iteration, but not the whole loop. The program proceeds with the first statement in the loop body toàn thân. The most common use of continue is to avoid the execution of certain parts of the loop body toàn thân, constrained by a condition checked in an if construct.
Here’s an example:
s="hello world" while len(s) > 5: s = s[1:] if len(s) > 5: continue print(s) # worldYou start with the same string 'hello world'. Python checks if the string has more than 5 characters in the while loop condition—which is the case.
Then, it enters the loop body toàn thân and essentially reduces the length of the string by one. Now, it checks if len(s) > 5 which remains True as long as the string has more than 5 characters. In these cases, the continue statement is executed and Python immediately ends the current iteration and proceeds with the loop condition while len(s) >5.
However, as soon as the string s consists of only 5 characters 'world', the if branch is not executed and the continue statement is skipped. Instead, it prints the string to the shell and checks the loop condition which is not met—and it leaves the loop.
Although the loop body toàn thân has been run multiple times, the print() statement was executed only once.
👉 Recommended Tutorial: How to End a For Loop?
Python Keywords Cheat Sheet
You can learn about the most important Python keywords in this concise cheat sheet—if you’re like me, you love cheat sheets as well! ?
You can tải về it here:
Summary
You’ve learned three ways to terminate a while loop.
Method 1: The while loop condition is checked once per iteration. If it evaluates to False, the program ends the loop and proceeds with the first statement after the loop construct.
Method 2: The keyword break terminates a loop immediately. The program proceeds with the first statement after the loop construct.
Method 3: The keyword continue terminates only the current loop iteration, but not the whole loop. The program proceeds with the first statement in the loop body toàn thân.
Thanks for reading this tutorial—if you want to boost your Python skills further, I’d recommend you check out my không lấy phí email academy and tải về the không lấy phí Python lessons and cheat sheets here:
Join us, it’s fun! 🙂
Programmer Humor
❓ Question: How did the programmer die in the shower? ☠️
❗ Answer: They read the shampoo bottle instructions:
Lather. Rinse. Repeat.
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2022), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his không lấy phí email academy here.