return value - python - getting 'none' at the end of printing a list -
this question has answer here:
newbie here. can please explain me why 'none' printed @ end of code, when called inside function?
background: have variable (share_data) contains lists:
share_data = [['date', 'ticker', 'company', 'mkt cap', 'vm rank', 'value rank', 'momentum rank'], ['2016-08-27', 'bez', 'beazley', '2,063', '89', '72', '76'], ['2016-08-30', 'bez', 'beazley', '2,063', '89', '72', '76'], ['2016-08-31', 'bez', 'beazley', '2,050', '89', '72', '75'], ['2016-09-01', 'bez', 'beazley', '2,039', '96', '73', '93'], ['2016-09-02', 'bez', 'beazley', '2,069', '90', '72', '77'], ['2016-09-03', 'bez', 'beazley', '2,120', '96', '70', '94'], ['2016-09-06', 'bez', 'beazley', '2,106', '90', '71', '77'], ['2016-09-07', 'bez', 'beazley', '2,085', '89', '71', '76'], ['2016-09-08', 'bez', 'beazley', '2,091', '89', '72', '77'], ['2016-09-09', 'bez', 'beazley', '2,114', '89', '71', '77'], ['2016-09-10', 'bez', 'beazley', '2,084', '94', '71', '89'], ['2016-09-12', 'bez', 'beazley', '2,084', '94', '71', '89']]
i interested in printing last 5 lines.
if use in main program:
for row in share_data[-5:]: print(row)
i correct data:
['2016-09-07', 'bez', 'beazley', '2,085', '89', '71', '76'] ['2016-09-08', 'bez', 'beazley', '2,091', '89', '72', '77'] ['2016-09-09', 'bez', 'beazley', '2,114', '89', '71', '77'] ['2016-09-10', 'bez', 'beazley', '2,084', '94', '71', '89'] ['2016-09-12', 'bez', 'beazley', '2,084', '94', '71', '89']
...however when created function this:
def share_details(share_data, n=5): ''' prints last n rows of share's records''' row in share_data[-n:]: print(row) return
and called function way:
print(share_details(share_data))
...what (note 'none' @ end):
['2016-09-07', 'bez', 'beazley', '2,085', '89', '71', '76'] ['2016-09-08', 'bez', 'beazley', '2,091', '89', '72', '77'] ['2016-09-09', 'bez', 'beazley', '2,114', '89', '71', '77'] ['2016-09-10', 'bez', 'beazley', '2,084', '94', '71', '89'] ['2016-09-12', 'bez', 'beazley', '2,084', '94', '71', '89'] none
i think it's 'return' statement @ end of function triggers it, don't know how/why.
edit - that's it's clear error (ie. printing inside function, , return value outside) can follow additional question? is practice delegate printing function? maybe function called, readability:
print_share_details(share_data)
or there better way more readable/pythonic?
when write print(share_details(share_data))
- means print value returned share_details
function. function returns none
after printing values.
if function doesn't return needs printed, better omit print
, call function like:
share_details(share_data)
Comments
Post a Comment