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:
Python Runtimeerror: Super() No Arguments
Next article icon

SyntaxError: ‘return’ outside function in Python

Last Updated : 03 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

We are given a problem of how to solve the 'Return Outside Function' Error in Python. So in this article, we will explore the 'Return Outside Function' error in Python. We will first understand what this error means and why it occurs. Then, we will go through various methods to resolve it with examples.

What is SyntaxError: ‘return’ outside function in Python?

The 'Return Outside Function' error is raised by the Python interpreter when it encounters a return statement outside the scope of a function. The return statement is used to exit a function and return a value to the caller. If this statement is mistakenly placed outside a function, Python will throw this error.

Syntax:

SyntaxError: 'return' outside function 

Below are the reasons by which SyntaxError: ‘return’ outside function in Python occurs:

  • Syntax Error in Script
  • Common Mistake Alert

Syntax Error in Script

In this example, code attempts to iterate through a list of strings named "l" and use a return statement within a for loop, but it will result in a 'Return Outside Function' error because the return statement is not inside a function.

Python
l = [ "The first line", "The second line", "The third line"]  for s in lines:     return s 

Output

Hangup (SIGHUP)
File "Solution.py", line
return s
SyntaxError: 'return' outside function

Common Mistake Alert

In below code, the return sum statement is placed outside the scope of the function add_nums, resulting in the 'Return Outside Function' error.

Python
def add_nums(a, b):     sum = a + b  # Return statement outside the function return sum 

Output

Hangup (SIGHUP)
File "Solution.py", line 6
return sum
^
SyntaxError: 'return' outside function

Solution for SyntaxError: ‘return’ outside function in Python

Below are some of the approaches to solve SyntaxError: ‘return’ outside function in Python:

  • Move 'return' inside a function
  • Use 'print()' instead of return
  • Use a 'Generator' (yield instead of return)

Move return inside a function

Since return must always be inside a function, we can define a function and place return within it to solve the error. Let's consider the example of the above code.

Python
def get_first_line():     l = ["The first line", "The second line","The third line"]     for s in l:         return s  # Now it's inside a function  print(get_first_line()) 

Output
The first line 

Explanation: We defined a function get_first_line(), and now the return statement is valid.

Use print() instead of return

If we just need to display values instead of returning them, we can use print() instead of return to avoid getting this error.

Python
l = ["The first line", "The second line", "The third line"]  for s in l:     print(s)  # Prints each line without error 

Output
The first line The second line The third line 

Use a Generator (yield instead of return)

Instead of using return, which immediately exits a function, we can use yield to turn the function into a generator. This allows us to produce values one by one without breaking the loop. It's generally used when we need to return multiple values from a function, but it can also replace 'return' to return a single value.

Python
def get_lines():     lines = ["The first line", "The second line", "The third line"]     for s in lines:         yield s   gen = get_lines()  for line in gen:     print(line) 

Output
The first line The second line The third line 

Explanation: since yield returns a generator instead of a final value, we must iterate over the generator (for line in gen) to retrieve values.


Output
The first line The second line The third line 

Next Article
Python Runtimeerror: Super() No Arguments

S

ssoniyaster
Improve
Article Tags :
  • Python
  • Python Programs
  • Python-Functions
  • Python How-to-fix
  • Python Errors
Practice Tags :
  • python
  • python-functions

Similar Reads

  • How to return null in Python ?
    In Python, we don't have a keyword called null. Instead, Python uses None to represent the absence of a value or a null value. We can simply return None when you want to indicate that a function does not return any value or to represent a null-like state. [GFGTABS] Python def my_function(): return N
    1 min read
  • Accessing Python Function Variable Outside the Function
    In Python, function variables have local scope and cannot be accessed directly from outside. However, their values can still be retrieved indirectly. For example, if a function defines var = 42, it remains inaccessible externally unless retrieved indirectly. Returning the VariableThe most efficient
    4 min read
  • How to fix "SyntaxError: invalid character" in Python
    This error happens when the Python interpreter encounters characters that are not valid in Python syntax. Common examples include: Non-ASCII characters, such as invisible Unicode characters or non-breaking spaces.Special characters like curly quotes (“, ”) or other unexpected symbols.How to Resolve:
    2 min read
  • Runtimeerror: Maximum Recursion Limit Reached in Python
    In this article, we will elucidate the Runtimeerror: Maximum Recursion Limit Reached In Python through examples, and we will also explore potential approaches to resolve this issue. What is Runtimeerror: Maximum Recursion Limit Reached?When you run a Python program you may see Runtimeerror: Maximum
    5 min read
  • Python Runtimeerror: Super() No Arguments
    Python, a versatile programming language, provides developers with a powerful toolset for creating complex applications. However, like any programming language, it comes with its share of challenges. One such issue that developers might encounter is the "RuntimeError: super(): no arguments." This er
    4 min read
  • Print Output from Os.System in Python
    In Python, the os.system() function is often used to execute shell commands from within a script. However, capturing and printing the output of these commands can be a bit tricky. This article will guide you through the process of executing a command using os.system() and printing the resulting valu
    3 min read
  • How To Return 0 With Divide By Zero In Python
    Dividing a number by zero is a big problem in math, and it can cause errors that suddenly stop your Python program. However, what if you could smoothly deal with this issue and make your program return a specific value, such as 0, instead of crashing? This article looks into different methods to acc
    3 min read
  • Python | Handling recursion limit
    When you execute a recursive function in Python on a large input ( > 10^4), you might encounter a "maximum recursion depth exceeded error". This is a common error when executing algorithms such as DFS, factorial, etc. on large inputs. This is also common in competitive programming on multiple pla
    4 min read
  • Can I call a function in Python from a print statement?
    Calling a function from a print statement is quite an easy task in Python Programming. It can be done when there is a simple function call, which also reduces the lines of code. In this article, we will learn how we can call a function from a print statement. Calling a Function Inside print()In this
    2 min read
  • Provide Multiple Statements on a Single Line in Python
    Python is known for its readability and simplicity, allowing developers to express concepts concisely. While it generally encourages clear and straightforward code, there are scenarios where you might want to execute multiple statements on a single line. In this article, we'll explore the logic, and
    3 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