![]() |
|
[Tut] What’s the Difference Between return and break in Python? - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] What’s the Difference Between return and break in Python? (/thread-100130.html) |
[Tut] What’s the Difference Between return and break in Python? - xSicKxBot - 10-23-2022 What’s the Difference Between return and break in Python? 5/5 – (1 vote) Question: What is the difference between Code: returnCode: breakLet’s first look at a short answer before we dive into a simple example to understand the differences and similarities between Code: returnCode: breakComparison ![]() Both Code: returnCode: break
Code: returnCode: breakUsed to end a function | Used to end a Code: forCode: whilePasses an optional value to the caller of the function (e.g., Code: return 'hello'Doesn’t pass anything to the “outside” While they serve a different purpose, i.e., ending a function vs ending a loop, there are some cases where they can be used interchangeably. Similar Use Cases The following use case shows why you may have confused both keywords Code: returnCode: breakHere’s the variant using Code: returnCode: def f(): for i in range(10): print(i) if i>3: return f()And here’s the variant using Code: breakCode: def f(): for i in range(10): print(i) if i>3: break f()Both code snippets do exactly the same—printing out the first 5 values 0, 1, 2, 3, and 4. Output: Code: 0
1
2
3
4However, this is where the similarity between those two keywords ends. Let’s dive into a more common use case where they both perform different tasks in the code. Different Use Cases The following example uses both keywords Code: breakCode: returnCode: breakCode: iSo the line Code: print(i)Code: iBut the function doesn’t end because Code: breakCode: print('hi')Code: 42Code: def f(): for i in range(10): if i>3: break print(i) print('hi') return 42 print(f())Output: Code: 0
1
2
3
hi
42The keyword Code: returnCode: break
Rule: Only if you want to exit a loop inside a function and this would also exit the whole function, you can use both keywords. In that case, I’d recommend using the keyword Code: returnCode: breakThanks for reading over the whole tutorial—if you want to keep learning, feel free to join my email academy. It’s fun! ![]() Recommended Video |