If you have a for loop in your Python code, and you want to exit it on a specific condition, then you can make use of the break statement.
This is just like other programming languages like C, C++, C# or Java.
Example:check_prime_numbers = [1, 2, 5, 6, 8, 9, 11, 12, 17]
for num in check_prime_numbers:
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
print(f"{num} is not a prime number")
break
else:
print(f"{num} is a prime number")
The above prime number example is a perfect one to understand how to make use of the break statement. We have a list of numbers and we want to know if they are prime or not. As soon as in the nested for loop we understand that the number is not prime we break the loop.
Facing issues? Have Questions? Post them here! I am happy to answer!
- Python List of Lists with Examples
- Fix: ERROR: Could not find a version that satisfies the requirement tkinter (from versions: none) ERROR: No matching distribution found for tkinter
- How to Convert Python Notebook .ipynb (JSON) to Executable .py Module
- ModuleNotFoundError: No module named qdarkstyle.colorsystem [Python]
- Python: Pandas Merge Indicator (Left, Right and Both) Example
- Fix: EOFError Exception in Python
- How to URL Decode a Query String in Python
- How to take user input from the console in a Python program
- Compare two lists in Python and return matches
- How to change the Python Default version
- Fix: KeyError: exception in Python
- How to get the Execution Time of A Python Program
- Fix: ModuleNotFoundError: No module named boto3 [Python]
- How to get unique values from a list in Python
- How to pip install Python Modules in VSCode
- Python: Fix - TypeError: NoneType object is not iterable
- How to delete a file using Python code example
- How to create a dictionary comprehension in Python
- Python: Get just the filename without extension using Path
- How to comment out a block of code in Python
- How to add two float numbers in Python
- Python: How to POST Json Data with HTTP Request
- Get MD5 Hash as Checksum of a String in Python
- Python - Convert float to String
- How to Parse XML String in Python
- Drag drop files here option missing for SharePoint document library - SharePoint
- New-SPLogFile PowerShell - create new SharePoint log file - SharePoint
- Portable Notepad++ for windows - NotepadPlusPlus
- Exception in thread main java.lang.NoClassDefFoundError: package javaClass - Java
- Fix Generics: error unexpected type required: class found: type parameter - Java
- [fix] java: incompatible types: double cannot be converted to java.lang.Integer Generics - Java
- SharePoint Server 2016 setup error - A system restart from a previous installation or update is pending. Restart your computer and run setup to continue. - SharePoint
- How to Mute All Sounds on Notepad++ on Windows - NotepadPlusPlus