-6

In python, return() and print() lead to different impacts on the following code. What's the difference? Why?

def count_wins(teamname):
    wins = 0
    for team in nfl:
        if team[2] == teamname:
            wins +=1
    return wins

def count_wins(teamname):
    wins = 0
    for team in nfl:
        if team[2] == teamname:
            wins +=1
    print wins

nfl = [['2009', '1', 'Pittsburgh Steelers', 'Tennessee Titans'], ['2009', '1', 'Minnesota Vikings', 'Cleveland Browns']]

Uioy
  • 25
  • 2
  • 5
    What's the difference? Everything. Maybe ask what is the similarity. The two are so unrelated it makes little sense to ask for "differences". Maybe read an introductory python book, where both should be explained. – juanchopanza Jul 17 '15 at 06:33

3 Answers3

6

print just prints stuff. It's not what you want if you need to do any extra processing on the result.

return returns a value from a function so you can add it to a list, store it in a database etc. Nothing is printed

What may confuse you is that the Python interpreter will print the returned value, so it might look like they do the same thing if that is all you are doing.

eg suppose you need to calculate the total wins:

def count_wins(teamname):
    wins = 0
    for team in nfl:
        if team[2] == teamname:
            wins +=1
    return wins

total_wins = 0
for teamname in teamnames:
    # doing stuff with result
    total_wins += count_wins(teamname) 

# now just print the total
print total_wins

def count_wins(teamname):
    wins = 0
    for team in nfl:
        if team[2] == teamname:
            wins +=1
    print wins

    for teamname in teamnames:
        # count_wins just returns None, so can't calculate total
        count_wins(teamname) 
John La Rooy
  • 281,034
  • 50
  • 354
  • 495
3

Print and return are very unrelated. Might be you are new to coding. In short "return" is used to return value(s)/control from a function being called. "Print" outputs the parameters passed to a specified logger, usually console screen.

You might want to look at: https://docs.python.org/2/tutorial/controlflow.html

Also: Why would you use the return statement in Python?

Community
  • 1
  • 1
1

My guess is that you are using IDLE.

print outputs anything it is given. Just that output, the result is not made available for further use by other functions or operations.

return returns the result of a function. Using this makes the result available for further use by other functions and operations. In IDLE, using return prints the value

Example:

def doso():
return 3+4

>>> doso()
7

Now 7 can be used in any operation or given to any function

See:

doso()+3
10
>>> 
BattleDrum
  • 426
  • 6
  • 13