Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
How to Define and Call a Function in Python
Next article icon

How to Break a Function in Python?

Last Updated : 16 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, breaking a function allows us to exit from loops within the function. With the help of the return statement and the break keyword, we can control the flow of the loop.

Using return keyword

This statement immediately terminates a function and optionally returns a value. Once return is executed, any code after it is ignored and the function exits at that point.

Example:

Python
def fun(a):     if a < 18:         return "Underage"  # Terminate     return "Eligible"  # Continue print(fun(15)) 

Output
Underage 

Explanation:

  • This function checks if the input a is less than 18. If true, it returns "Underage" and terminates the function.
  • As a is 18 or more, it returns "Eligible", indicating the function continues normally.

Common Methods to break a Function

In Python, we use the "break" and "return" statements to exit a function. However, there are other ways to manage flow control or exit from a function, depending on the situation.

Let's explore these methods in detail, one by one.

Table of Content

  • Using return keyword
  • Using break keyword
  • using raise keyword
  • using sys.exit()

Using break keyword

break statement exits a loop early but allows the function to continue after the loop. It is generally used in for and while loops.

Example:

Python
def fun(no):     for i in no:         if i % 2 == 0:             print(i)  # Found             break     else:         print("Not Found")  # Not found  # input fun([1, 3, 5, 8, 7]) 

Output
8 

Explanation:

  • This function finds the first even number in the list, prints it and exits the loop.
  • If no even number is found, it prints "Not Found".

using raise keyword

raise statement exits the function by raising an exception, stopping the normal flow and passing the error.

Example:

Python
def fun(a, b):     if b == 0:         raise ValueError("Error")  # Error     return a / b  # Output  # Input try:     print(fun(10, 0))  # Will raise an exception except ValueError as e:     print(e)  # Error 

Output
Error 

Explanation:

  • This function raises a ValueError with the message "Error" if b is 0.
  • This try block calls the function and the except block prints the error message when caught.

using sys.exit()

sys.exit() function terminates the entire program, not just the function and is typically used to end a script under specific conditions.

Example:

Python
import sys def fun(a):     if a < 18:         print("Exiting")  # Exit         sys.exit()     return "Valid."  # Valid # Input fun(15) 

Output
Exiting 

Explanation:

  • This function exits the program if a is less than 18, printing "Exiting."
  • Otherwise, it returns "Valid.".

Next Article
How to Define and Call a Function in Python

V

vishakshx339
Improve
Article Tags :
  • Python
  • python
Practice Tags :
  • python
  • python

Similar Reads

  • How to call a function in Python
    Python is an object-oriented language and it uses functions to reduce the repetition of the code. In this article, we will get to know what are parts, How to Create processes, and how to call them. In Python, there is a reserved keyword "def" which we use to define a function in Python, and after "d
    5 min read
  • How to Recall a Function in Python
    In Python, functions are reusable blocks of code that we can call multiple times throughout a program. Sometimes, we might need to call a function again either within itself or after it has been previously executed. In this article, we'll explore different scenarios where we can "recall" a function
    4 min read
  • How to Add Function in Python Dictionary
    Dictionaries in Python are strong, adaptable data structures that support key-value pair storage. Because of this property, dictionaries are a necessary tool for many kinds of programming jobs. Adding functions as values to dictionaries is an intriguing and sophisticated use case. This article looks
    5 min read
  • How to use Function Decorators in Python ?
    In Python, a function can be passed as a parameter to another function (a function can also return another function). we can define a function inside another function. In this article, you will learn How to use Function Decorators in Python. Passing Function as ParametersIn Python, you can pass a fu
    3 min read
  • How to Define and Call a Function in Python
    In Python, defining and calling functions is simple and may greatly improve the readability and reusability of our code. In this article, we will explore How we can define and call a function. Example: [GFGTABS] Python # Defining a function def fun(): print("Welcome to GFG") # calling a fu
    3 min read
  • Python | How to get function name ?
    One of the most prominent styles of coding is following the OOP paradigm. For this, nowadays, stress has been to write code with modularity, increase debugging, and create a more robust, reusable code. This all encouraged the use of different functions for different tasks, and hence we are bound to
    3 min read
  • How to Call Multiple Functions in Python
    In Python, calling multiple functions is a common practice, especially when building modular, organized and maintainable code. In this article, we’ll explore various ways we can call multiple functions in Python. The most straightforward way to call multiple functions is by executing them one after
    3 min read
  • set() Function in python
    set() function in Python is used to create a set, which is an unordered collection of unique elements. Sets are mutable, meaning elements can be added or removed after creation. However, all elements inside a set must be immutable, such as numbers, strings or tuples. The set() function can take an i
    3 min read
  • Function aliasing in Python
    In Python, we can give another name of the function. For the existing function, we can give another name, which is nothing but function aliasing. Function aliasing in Python In function aliasing, we create a new variable and assign the function reference to one existing function to the variable. We
    2 min read
  • round() function in Python
    Python round() function is a built-in function available with Python. It will return you a float number that will be rounded to the decimal places which are given as input. If the decimal places to be rounded are not specified, it is considered as 0, and it will round to the nearest integer. In this
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences