Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Def - Return Question
#1
Hi Everyone,

I'm trying to understand the below code. My question is why is it returning salary_bins?

So from what I understand it first defines the table columns, creates the bins and then draws the histograms.

But the return part I'm not sure I fully understand. I tried to run it with return salary_bins and it created the histograms as well.

Thanks in advance.

def histograms(t):
    ages = t.column('Age')
    salaries = t.column('Salary')
    age_bins = np.arange(min(ages),max(ages)+1,1)
    salary_bins = np.arange(min(salaries), max(salaries)+1000000,1000000)
    t.hist('Age', bins=age_bins, unit='year')
    t.hist('Salary', bins=salary_bins, unit='$')
    return age_bins # Keep this statement so that your work can be checked
    
histograms(full_data)
print('Two histograms should be displayed below')
Reply
#2
The return statement does just that - returns selected the result of the processing within a function.

So, if you don't need any of the data produced in a function, you are not obligated to use it at at all - by default, functions return None in Python

You also don't have to use the returned value in the calling code - you may have a function that returns result, and sometimes this result is discarded.
Test everything in a Python shell (iPython, Azure Notebook, etc.)
  • Someone gave you an advice you liked? Test it - maybe the advice was actually bad.
  • Someone gave you an advice you think is bad? Test it before arguing - maybe it was good.
  • You posted a claim that something you did not test works? Be prepared to eat your hat.
Reply
#3
Hi volcano63,

Thanks for the explanation, can I please clarify. So when I call the function histograms(full_data), in addition to the histograms it will give me the value of age_bins? I actually don't need to return anything here and still get the histograms drawn?
Reply
#4
(Jul-01-2018, 11:04 AM)tryingtolearnpython Wrote: I actually don't need to return anything here and still get the histograms drawn?
If it worked when you return value - it should work even without it.
Test everything in a Python shell (iPython, Azure Notebook, etc.)
  • Someone gave you an advice you liked? Test it - maybe the advice was actually bad.
  • Someone gave you an advice you think is bad? Test it before arguing - maybe it was good.
  • You posted a claim that something you did not test works? Be prepared to eat your hat.
Reply
#5
thank you very much volcano63
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020