DragonG Wrote:that is the difference between return and print, explained so that a beginner can understand it?In example under gone look at some basic usage of function and return,this can make it clearer what return is good for.
In
read_file()
we don't want to print the result,but return it out for further progressing.Same with
check_gender(read_file)
it take in read_file do work and return result.In
result(gender)
when all is finish then print out result.If look at code you see small task function(like black box isolated for outside world),
that take in a argument and return out the result.
This make code easier to read and test,than writing this same code within functions.
def read_file(): try: with open("names.txt", encoding='utf-8') as f: return [i.strip() for i in f] except (OSError, IOError) as error: return f'Error reading file: {error}' def check_gender(read_file): '''Make male and female list output''' male = [] female = [] for name in read_file: if name.lower().startswith('male'): male.append(name.split(' ', 1)[1]) else: female.append(name.split(' ', 1)[1]) return male, female def result(gender): '''Show table of Male Female''' male, female = gender titles = ['Male', 'Female'] print('{:>8}{:>15}'.format(*titles)) print('-'*27) for item in zip(male, female): print('{:15}{:^10}'.format(*item)) if __name__ == '__main__': if 'Error' in read_file(): print(read_file()) else: gender = check_gender(read_file()) result(gender)
Output: Male Female
---------------------------
Kent Hollow Emily Hunt
Hans Klein Olivia Stock
Input names.txt:Male Kent Hollow Female Emily Hunt Male Hans Klein Female Olivia StockYou need Python 3.6 --> to run this code,so do not use Python 2 as you use in first post