Skip to content

Commit 6104967

Browse files
authored
[Term Entry] Python Keywords: break
* First commit, set up and start * Add syntax example * Add output and explanation * Add metadata, link to loops, and change code insert type * Add Codebyte example and remove semicolon from initial example * Fix print statement syntax error * Add final summation statement * minor content fix * Update break.md ---------
1 parent b08a30d commit 6104967

File tree

1 file changed

+78
-0
lines changed
  • content/python/concepts/keywords/terms/break

1 file changed

+78
-0
lines changed
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
---
2+
Title: 'break'
3+
Description: 'Immediately exits the nearest enclosing `for` or `while` loop.'
4+
Subjects:
5+
- 'Computer Science'
6+
- 'Data Science'
7+
Tags:
8+
- 'Break'
9+
- 'For'
10+
- 'Loops'
11+
- 'Python'
12+
CatalogContent:
13+
- 'learn-python-3'
14+
- 'paths/computer-science'
15+
---
16+
17+
The **`break`** keyword in Python is used to exit a [loop](https://codecademy.com/resources/docs/python/loops) immediately. It’s commonly used to stop looping early based on a condition or to exit infinite loops.
18+
19+
## Syntax
20+
21+
Here is the syntax for using `break` in `while` loop:
22+
23+
```pseudo
24+
while condition:
25+
if some_condition:
26+
break # Exit the loop
27+
```
28+
29+
Here is the syntax for using `break` in `for` loop:
30+
31+
```pseudo
32+
for item in iterable:
33+
if some_condition:
34+
break # Exit the loop
35+
```
36+
37+
**Parameters:**
38+
39+
- The `break` statement does not take any parameters.
40+
41+
**Return value:**
42+
43+
The `break` statement does not return any value. It simply exits the nearest enclosing loop immediately.
44+
45+
## Example: Exiting a Loop Early Using `break`
46+
47+
This example iterates through a list of numbers and stops printing when the number 58 is reached, demonstrating how `break` exits the loop immediately:
48+
49+
```py
50+
numbers = [14, 25, 36, 47, 58, 69, 70]
51+
for number in numbers:
52+
print(number)
53+
54+
if number == 58:
55+
break
56+
```
57+
58+
The output of this code will be:
59+
60+
```shell
61+
14
62+
25
63+
36
64+
47
65+
58
66+
```
67+
68+
## Codebyte Example: Using `break` to Stop Loop on a Condition
69+
70+
This codebyte example loops through numbers and prints their doubles until it encounters a number divisible by 29, where it exits the loop using `break`:
71+
72+
```codebyte/python
73+
numbers = [14, 25, 36, 47, 58, 69, 70]
74+
for number in numbers:
75+
if number % 29 == 0:
76+
break
77+
print(number * 2)
78+
```

0 commit comments

Comments
 (0)