(Jul-16-2019, 09:12 AM)SB_J Wrote: Why do I have to use a return statement(1) when I can get the output by calling the function directly(2)?
Functions is a first step to structure code better,one function can do a task and return data out.
Then other functions can take that data in as argument and do other task.
This make code easier to read and test(functions should be isolate from data outside) than writing all code in global namespace.
A working example of what mention over.
from bs4 import BeautifulSoup
import json
import requests
def data_from_web():
'''Read title from web-site'''
url = 'http://CNN.com'
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
return soup.find('title').text
def process_data(data):
'''Make dicionary'''
modified_data = {'title': data}
return modified_data
def write_data(data):
'''Serializing data to disk'''
with open('title.json', 'w') as f_out:
json.dump(data, f_out)
def result():
data = data_from_web()
modified_data = process_data(data)
write_data(modified_data)
if __name__ == "__main__":
result()