<jupyter_start><jupyter_text>SWAPI (Star Wars)Answer the following questions using the [Star Wars](https://swapi.co/). I've added three cells for each question but you're free to use more or less! Hold `Shift` and hit `Enter` to run a cell, and use the `+` on the top left to add a new cell to a notebook.If you spend some time reading the documentation your life will probably be a little bit easier! 0) Import any libraries you might need- *Tip: We're going to be downloading things from the internet, so we probably need `requests`.*<jupyter_code>import requests<jupyter_output><empty_output><jupyter_text>1) Make a request to the Star Wars APII've heard there's a new Star Wars film called **Solo**, but it isn't in SWAPI!The most recent film it contains has an ID of 7. Make a request for that film and look at the data.<jupyter_code>response = requests.get('https://swapi.co/api/films/7/')
film7 = response.json()
#film7<jupyter_output><empty_output><jupyter_text>2) What is that film's name, and when was it released?Please print **only** the title and the release date. You can guess at the keys, but I recommend checking the documentation.<jupyter_code>print(f"{film7['title']}, {film7['release_date']}")<jupyter_output>The Force Awakens, 2015-12-11<jupyter_text>3) But I want Han Solo! Use the API to search for people named "Solo".<jupyter_code>response = requests.get("https://swapi.co/api/people/schema")
schema_people = response.json()
# schema_people
# response = requests.get("https://swapi.co/api/people/?search=r2")
# search_r2 = response.json()
# search_r2
# response = requests.get("https://swapi.co/api/people/?search=skywalker")
# search_skywalker = response.json()
# search_skywalker
response = requests.get("https://swapi.co/api/people/?search=solo")
search_solo = response.json()
search_solo
response = requests.get("https://swapi.co/api/people/14/")
solo = response.json()
solo<jupyter_output><empty_output><jupyter_text>4) How many results did you get?Show **two different ways** of displaying this number.- *Tip: One uses the API, and one uses a Python function*<jupyter_code>print(search_solo['count'])
print(len(search_solo['results']))
s=0
for result in search_solo['results']:
    s = s + 1
print(s)
hs = len([result for result in search_solo['results']])
print(hs)<jupyter_output>1<jupyter_text>5) Write me a sentence about Han SoloYour sentence should be say `"____ has _____ hair, is _____cm tall and weighs ____kg."` - make sure you have **no spaces** between the numbers and `cm`/`kg`.<jupyter_code>solo = search_solo['results'][0]
solo
print(f"{solo['name']} has {solo['hair_color']} hair, is {solo['height']}cm tall and weighs {solo['mass']}kg.")<jupyter_output>Han Solo has brown hair, is 180cm tall and weighs 80kg.<jupyter_text>5) Search for C-3PO<jupyter_code>response = requests.get("https://swapi.co/api/people/?search=3po")
search_3po = response.json()
# search_3po<jupyter_output><empty_output><jupyter_text>6) What URL can tell me more about his species? Make a request to the corrent endpoint.Spoiler: he's a **droid**. Are robots a species? I guess so, maybe.<jupyter_code>droid_url = search_3po['results'][0]['species'][0]
print(droid_url)
response = requests.get(f'{droid_url}')
spec_droid = response.json()
print(f"This endpoint points to the species page for '{spec_droid['name']}.'")<jupyter_output>This endpoint points to the species page for 'Droid.'<jupyter_text>7) Print out the URL of every droid* *Tip: life will be easier if you don't say `for droid in...` or `for person in` because you aren't looping through droids or people. What are you looping through?*<jupyter_code># loop through list of people on https://swapi.co/api/species/2/
for droid_url in spec_droid['people']:
    print(droid_url)<jupyter_output>https://swapi.co/api/people/2/
https://swapi.co/api/people/3/
https://swapi.co/api/people/8/
https://swapi.co/api/people/23/
https://swapi.co/api/people/87/<jupyter_text>8) Print out the name of every droid* *Tip: You should start from the last answer, but add more stuff in!** *Tip: You'll need to make a request every time you're in the loop** *Tip: Be careful - f you re-use the variable name `data` you'll erase your old `data` variable*<jupyter_code>for droid_url in spec_droid['people']:
    response = requests.get(droid_url)
    droid_page = response.json()
    print(droid_page['name'])<jupyter_output>C-3PO
R2-D2
R5-D4
IG-88
BB8<jupyter_text>9) Print out more about the droidCount the number of films for each droid, printing `"___ was in ___ films"` for each of them* *Tip: You might want to look at a single droid result, or print the data in the for loop, so you know how to get the films. Or read the documentation!*<jupyter_code>for droid_url in spec_droid['people']:
    response = requests.get(droid_url)
    droid_page = response.json()
    print(f"{droid_page['name']} was in {len(droid_page['films'])} films.")<jupyter_output>C-3PO was in 6 films.
R2-D2 was in 7 films.
R5-D4 was in 1 films.
IG-88 was in 1 films.
BB8 was in 1 films.<jupyter_text>10) Let's be smart and cache the results *[DIFFICULT, maybe!]*So far we've been using a for loop to go through each droid. Every droid, one more request. Every time we want more data, we run the loops again. I don't want that guy to get angry that we're asking for so much data!We want to our list of **droid urls** and turn it into a **list of dictionaries about those droids**. Save it as a variable called `droids`. If you get it correct, the following code should work if you cut and paste it.```pythonfor droid in droids:    print(droid['name'])```* *Tip: Use a list comprehension** *Tip: So far we've done `response = requests.get..` and `response.json()` on separate lines. You'll need to combine them!*<jupyter_code>droids = [requests.get(droid_url).json() for droid_url in spec_droid['people']]
# droids
for droid in droids:
    print(droid['name'])<jupyter_output>C-3PO
R2-D2
R5-D4
IG-88
BB8<jupyter_text>11) Get a list of every single planet in the Star Wars universe* *Tip: You'll want to use the API documentation for this, I think*<jupyter_code>planet_list = []
base_url = "https://swapi.co/api/planets/"
for i in range(1,100):
    if response.status_code == 200:
        page_no = i
        response = requests.get(base_url+str(page_no))
        planet_list.append(response.json())
    else:
        del planet_list[-1]
        break
for planet in planet_list:
    print(planet['name'])
# WHILE LOOP THAT TIMED OUT
# planet_list = []
# base_url = "https://swapi.co/api/planets/"
# runwhile = True
# while (runwhile):
#     page_no = 1
#     response = requests.get(base_url+str(page_no))
#     planet_list.append(response.json())
#     page_no += 1
#     if response.status_code == 404:
#         runwhile = False
#         break
# planet_list<jupyter_output><empty_output><jupyter_text>12) How many planets are there? Show me two different ways of displaying the answer.* *Tip: They won't match*<jupyter_code>print(len(planet_list))
pc = len([planet for planet in planet_list])
print(pc)<jupyter_output>61<jupyter_text>These questions are all list comprehension questions, if you'd like 13) Get the population of each of the planets* *Tip: Only use the 10 results for now** *Tip: Use a list comprehension*<jupyter_code>#planet_list[0]
for planet in planet_list [:10]:
    print(f"{planet['name']}:\t{int(planet['population']):,.0f}")<jupyter_output>Tatooine:	200,000
Alderaan:	2,000,000,000
Yavin IV:	1,000<jupyter_text>14) Get the population of each of the planets, EXCEPT the ones that have a population of `'unknown'`* *Tip: Use a list comprehension with a filter (that's the `..if..` part at the end)*<jupyter_code>print(f"The population of various planets:")
for planet in planet_list:
    if planet['population'] != 'unknown':
        print(f"\t{planet['name']}:  \t{int(planet['population']):,.0f}")<jupyter_output>The population of various planets:
	Tatooine:  	200,000
	Alderaan:  	2,000,000,000
	Yavin IV:  	1,000
	Bespin:  	6,000,000
	Endor:  	30,000,000
	Naboo:  	4,500,000,000
	Coruscant:  	1,000,000,000,000
	Kamino:  	1,000,000,000
	Geonosis:  	100,000,000,000
	Utapau:  	95,000,000
	Mustafar:  	20,000
	Kashyyyk:  	45,000,000
	Polis Massa:  	1,000,000
	Mygeeto:  	19,000,000
	Felucia:  	8,500,000
	Cato Neimoidia:  	10,000,000
	Saleucami:  	1,400,000,000
	Eriadu:  	22,000,000,000
	Corellia:  	3,000,000,000
	Rodia:  	1,300,000,000
	Nal Hutta:  	7,000,000,000
	Dantooine:  	1,000
	Bestine IV:  	62,000,000
	Ord Mantell:  	4,000,000,000
	Trandosha:  	42,000,000
	Socorro:  	300,000,000
	Mon Cala:  	27,000,000,000
	Chandrila:  	1,200,000,000
	Sullust:  	18,500,000,000
	Toydaria:  	11,000,000
	Malastare:  	2,000,000,000
	Dathomir:  	5,200
	Ryloth:  	1,500,000,000
	Vulpter:  	421,000,000
	Tund:  	0
	Haruun Kal:  	705,300
	Cerea:  	450,000,000
	Glee Anselm:  	500,000,000
	Champala:  	3,500,000,000
	Ojom: [...]<jupyter_text>14) Add up the populations* *Tip: They're strings right now, so it isn't going to work unless you change something about them*<jupyter_code>intergal_pop = [int(planet['population']) for planet in planet_list if planet['population'] != 'unknown']
print(f"The intergalactic population totals: {sum(intergal_pop):,.0f}")<jupyter_output>The intergalactic population totals: 1,711,401,432,500<jupyter_text>15) Print what percentage of the total population each planet hasI would like the sentences to be `"The planet ____ has a population of _____, which is ___% of the total population"`. If we don't know the planet's population, say `"We don't know the population of _____"`.* *Tip: This finally uses a for loop, but also the result of the last question*<jupyter_code>for planet in planet_list:
    if planet['population'] != 'unknown':
        print(f"The planet {planet['name']} has a population of {int(planet['population']):,.0f}, which is {(int(planet['population'])/sum(intergal_pop))*100:,.1f}% of the total galactic population.")
    elif planet['population'] == 'unknown':
        print(f"We don't know the population of {planet['name']}.")<jupyter_output>The planet Tatooine has a population of 200,000, which is 0.0% of the total galactic population.
The planet Alderaan has a population of 2,000,000,000, which is 0.1% of the total galactic population.
The planet Yavin IV has a population of 1,000, which is 0.0% of the total galactic population.
We don't know the population of Hoth.
We don't know the population of Dagobah.
The planet Bespin has a population of 6,000,000, which is 0.0% of the total galactic population.
The planet Endor has a population of 30,000,000, which is 0.0% of the total galactic population.
The planet Naboo has a population of 4,500,000,000, which is 0.3% of the total galactic population.
The planet Coruscant has a population of 1,000,000,000,000, which is 58.4% of the total galactic population.
The planet Kamino has a population of 1,000,000,000, which is 0.1% of the total galactic population.
The planet Geonosis has a population of 100,000,000,000, which is 5.8% of the total galactic population.
The planet Utapau[...]
{'fraction_non_alphanumeric': 0.12071925544411313, 'fraction_numerical': 0.052950212343001714, 'mean_word_length': 4.937768240343348, 'pattern_counts': {'":': 0, '<': 60, '<?xml version=': 0, '>': 60, 'https://': 16, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '18', 'dir': 'jupyter-structured-clean-dedup', 'id': '658109', 'license': 'MIT', 'n_tokens_mistral': 4249, 'n_tokens_neox': 3811, 'n_words': 1259, 'path': '01 - SWAPI API (Star Wars).ipynb', 'repo_name': 'domhnallog/04-homework', 'size': '11067'}