![]() |
Function Improvement - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Function Improvement (/thread-27031.html) |
Function Improvement - Santino - May-23-2020 Hey I am looking to improve my working function below; The objective is to get back a list of countries from the free api. The argument parsed is the number of countries the user wants back , the default is ALL the countries . Two ways i want to improve is ; a)i want the len(z) , the maximum value to be defined within the loop instead of explicitly defining it as 250 this would be in case countries are added b) I want an object list 'country_list' , which is appended to in this code, to be created by this function , and not only just as output displayed when running the function --------start of function ----------------------- def list_of_countries(number_to_return=250): allurl='https://restcountries.eu/rest/v2/all' uh=urllib.request.urlopen(allurl) data = uh.read().decode() z=json.loads(data) lim=number_to_return country_list=list() i=0 while i < lim : y=z[i] country_list.append(y['name']) i+=1 return country_list-------------------------end of function--------------------- test case 1 : list_of_countries(4) test case 2 : list_of_countries() #without explicitly using 250 in default test case 3 : print(country_list) RE: Function Improvement - jefsummers - May-23-2020 This should help. I simplified the code some, set your country limit to an arbitrarily high number (one would hope there will never be 100,000 countries), limit works, I am not sure what you want for the second part. The function returns a list object. You can assign that list to another name, copy the list, do whatever you like. Can you clarify what you wanted for the second part? import urllib import json def list_of_countries(number_to_return=100000): allurl='https://restcountries.eu/rest/v2/all' uh=urllib.request.urlopen(allurl) data = uh.read().decode() z=json.loads(data) lim=number_to_return country_list=list() for country in z : country_list.append(country['name']) lim -= 1 if lim == 0: break return country_list print(list_of_countries()) |