-2

Here is my code I've tried:

import csv
f = open("nfl.csv", "r")
nfl = list(csv.reader(f))
patriots_wins = 0
for each in nfl:
    if each[2] == "New England Patriots":
        patriots_wins = patriots_wins + 1
        return patriots_wins
print(patriots_wins)

It gives the below error:

SyntaxError: 'return' outside function
Vikas Periyadath
  • 3,088
  • 1
  • 21
  • 33
The One
  • 2,261
  • 6
  • 22
  • 38
  • what is unclear? You cannot `return` if you are not in a function. Did you mean to put `break` instead? – UnholySheep Feb 15 '18 at 08:03
  • Here I can't see any function ,then why are you returning some value ? – Vikas Periyadath Feb 15 '18 at 08:03
  • 1
    When you say _"Here is my code I've tried"_ it would help to explain *why did you try it*, that is, what is the purpose of this code. – AGN Gazer Feb 15 '18 at 08:04
  • Possible duplicate of [Return outside function error in Python](https://stackoverflow.com/questions/14924820/return-outside-function-error-in-python) – AGN Gazer Feb 15 '18 at 08:04
  • Why can't if i'm not in function? Vikas edited that for me. I didn't write that. – The One Feb 15 '18 at 08:05
  • 1
    Ask yourself: to where is `return patriots_wins` supposed to return the value of `patriots_wins`? Usually a function is called either from another function of from the "main" program/script. A `return` inside a function instructs that function to pass a return value back to the caller. Without a function there cannot be a caller to whom you could pass anything. – AGN Gazer Feb 15 '18 at 08:08
  • _"Vikas edited that for me. I didn't write that."_ Ha-ha-ha! That's a good one! – AGN Gazer Feb 15 '18 at 08:09
  • 1
    What are you trying to achieve with the `return`? – cdarke Feb 15 '18 at 08:09
  • Why would you need return in that situation? – Psytho Feb 15 '18 at 08:20
  • @AGNGazer with out try that code how he will get that error dude ? – Vikas Periyadath Feb 15 '18 at 09:13

2 Answers2

4

return is used to return a value from a function and you have not defined a function.

For instance, you might have created the following function:

def f(x):
    """Adds 5 to any integer x"""

    y = x + 5

    return y

and put this function in some larger context, such as:

def main():

    for i in range(10):
        print(f(i))

Here, when main is called, we will call the function f() 10 times and everytime we do so f() will return the answer to "What is i + 5?".

GLaDER
  • 345
  • 2
  • 17
1

You get a return from a function.

check out this link

The return statement

return may only occur syntactically nested in a function definition, not within a nested class definition.

If an expression list is present, it is evaluated, else None is substituted.

return leaves the current function call with the expression list (or None) as return value.

When return passes control out of a try statement with a finally clause, that finally clause is executed before really leaving the function.

Swarn Singh
  • 134
  • 7