Skip to 0 minutes and 1 secondOne of the reasons for Python's popularity is the truly amazing community that has formed around the language. You will rarely meet a more helpful, inclusive, or open community as those who consider themselves Pythonistas. Not only do they meet together at conferences all over the world, produce amazing and helpful resources for learners of all levels, and also occupy numerous forums just itching for the chance to help someone out with a programming problem, they also help improve the language itself. One way in which many programmers helped make Python an easier language to use is by producing modules that you can download and install on your computer to help perform a wide variety of tasks.

Skip to 0 minutes and 38 secondsIn this step, we're going to look at a few different modules to create a little script that will automatically download Pokemon images for you whenever you give it the name of a Pokemon. To begin with, you're going to need to install these modules. So if you are on Windows open a command prompt, and if you're on Mac or Linux open up your terminal. We use the programme pip to instal different modules. So first check that you've got pip installed by typing pip --version, or pip3 --version if you you're on Mac or Linux. If pip isn't installed then check in the text below the video for instructions on how to install it, or ask for help in the comments.

Skip to 1 minute and 24 secondsTo install a module on Mac/Linux type pip3 install, or on Windows just pip install, and then the name of the modules that you want to install. In this case requests, pokebase, and a module called pillow. Press Enter and you should see that the packages start to be downloaded and installed on your computer. To check whether the packages have been installed correctly we'll import them in the Python shell quickly. So close down your Command window or your terminal, and in the Python shell we're going to type import requests, import pokebase, and import PIL. To get started, let's create a new file, and we'll call it pokemon_simple.py.

Skip to 2 minutes and 25 secondsYour first four lines of code will be used to import the modules we need. The purpose of each module will be explained as we go along. So from pokebase import pokemon, from requests we're going to import get, from PIL we're going to import Image, and then lastly from io we're going to import BytesIO.

Skip to 2 minutes and 55 secondsNow you're going to write a function. A function is a named block of code that performs a task. Functions are useful for keeping code organised, and also for when code needs to be reused. You're going to reuse this function in the next step of this week's course, so it's useful to write it now. We create a function using the keyword def.

Skip to 3 minutes and 14 secondsSo def fetch_pokemon():.

Skip to 3 minutes and 20 secondsNow we can see that indentation there, underneath is automatically placed ready for our next bit of code. We'll keep the function simple to begin with, so indented within the function let's ask the user which Pokemon they want to fetch. So name = input(Which Pokemon do you want to fetch?) then finish it off by closing the brackets. Running this code at the moment wouldn't do anything. This is because we haven't yet called the function. You run the code inside a function by typing it's name followed by parentheses. So here I just type fetch_pokemon() and then I can write my code. Which Pokemon do you want to fetch? And I'm going to choose Charizard. Now let's get to the fun part.

Skip to 4 minutes and 12 secondsLet's use pokebase to get some information about the Pokemon. Pokebase is a library that provides access to the pokeapi. You can have a look at the website

Skip to 4 minutes and 22 secondsat HBS https://pokeapi.co. If you wanted to find out about Charizard, for instance, you can type pokemon/charizard into the search box and press Submit.

Skip to 4 minutes and 42 secondsThis will give you all the information that the database holds on the Charizard Pokemon. The pokebase module just gives us a method of doing exactly that, looking up different Pokemon and getting back information about them. Add in another line to your function to use the module. So here I'm going to write poke = pokemon and then in brackets the name that the user entered. Let's run this and see what happens. So I type Charizard again, hit Enter, and then what's going to happen is that request is going to be made to the pokeapi. Now this can take quite a long time, so be patient and just wait for the programme to eventually end.

Skip to 5 minutes and 32 secondsRunning the code will not actually produce any results yet, because although all the information has been fetched, we're not actually doing anything with it. Let's find out how much a Pokemon weighs. So I'm going to print and then name and then with the space around it I'm going to type weighs? And then I'm to concatenate that with the string of the Pokemon's weight. So, poke.weight. And close my brackets and close again. Running this again. It should be a little faster this time, because all the information has already been gathered. And we can see the Charizard weights 905. There are some other things you can find out about the Pokemon if you like.

Skip to 6 minutes and 16 secondsSo you can find out about their abilities, their height, their name, their species, their stats, their type, as well as their weight. If we do poke.stats and query Charizard, we get this data structure out. what we're interested in, though, is their sprites.

Skip to 6 minutes and 37 secondsTry querying Charizard sprites. When we type in Charizard, we'll be presented with some data that looks a little bit like this. What you are seeing here, are the links to different images of Charizard. You can try them out by copying and pasting the URLs into a browser.

Skip to 6 minutes and 59 secondsSo when I copy this in here, and hit Enter, we're taken to a picture of Charizard which I would just magnify a little bit. Now we want your programme to go and fetch that image from the web site. This is why you've imported the requests module. The get method will go and fetch data from a web page, in this case, the image that we're after. Adding a line will go and fetch the image. So let's change this line from print poke.sprites, to pic= get, and then we're going to get poke.sprites that the specific sprite we want is the .front_default.

Skip to 7 minutes and 48 secondsAnd then, rather getting the whole page and all the information with it, I just want the content.

Skip to 7 minutes and 58 secondsNow that you have the image, it's time to save it. The PIL module is used to do all types of image manipulation in Python. Here we're just going to use it to save the image. At the moment, the image is actually a large collection of ones and zeros, so it needs to be converted using the io and PIL modules.

Skip to 8 minutes and 18 secondsSo I'm adding the line here image=image.open BytesIO pic. The last step is to save the file. We're going to use the GIF file type for this, so I type image.save and then in brackets after that I can put the name of my image which I'm going to call poke.gif. And that should be the code all complete. Now I'm going to save my Python file again, but this time I'm going to save it in a different directory. So I'm going to go to my pictures directory, and I'm going to save my file there. Now I'm going to run my code again, and look for Charizard.

Skip to 9 minutes and 5 secondsYou should be able to see, in that Pictures directory, is the image of Charizard which I can open up.

Skip to 9 minutes and 13 secondsNow if I reorganise my desktop a little bit, so that we can see my image directory, and my shell, and my file. And then I'm going to run my code again. This time I'm going to fetch Spearow. Now because Spearow hasn't been fetched before, this will take a little bit of time again. But once it's fetched all the information and then grabbed the image, we should see that image of Charizard change in my directory to that of Spearow. As an optional challenge, why didn't you see if you can save each Pokemon image with the Pokemon's name. Or how about working through a list of Pokemon and fetching all their images. It's really up to you.

Poke-fun

One of the reasons that Python is so popular is the amazing community that has formed around this language. You will rarely meet a more helpful, inclusive, and open group of people! These self-styled Pythonistas share their knowledge at conferences around the world, produce amazing and helpful resources for learners of all levels, and gather in numerous online forums, just waiting for the chance to help someone with a programming problem. Their activities also help to improve the language itself.

One way programmers make Python an easier language to use is by producing a wide variety of modules that you can download — for free! — and install on your computer to help you perform any number of tasks.

In this step, we are going to look at a few different modules and use them to create a short script that will automatically download an image of a Pokemon for you whenever you enter a Pokemon name.

Installing external modules

Unlike modules such as random or time, these modules do not come bundled with Python. In other words, they are not part of what is called the standard library. Instead, you need to install them one by one on your system.

To do this, you first need to install the Pip tool.

Windows

pip should come with your Python 3 installation. You can test this by opening a cmd command prompt window from your Start menu and typing in the following:

pip --version

If this tells you that pip can’t be found, the easiest way to install it is by following our handy installation guide.

macOS

On macOS, assuming you installed Python 3 using Homebrew, you will already have pip installed.

Linux

On most Linux systems, pip will be packaged along with Python 3, but if it’s not there, you can install it using your package manager.

sudo apt install python3-pip

Installing requests, pokebase and pillow

  • On a machine running Linux/macOS, open a terminal/cmd prompt window and enter:
pip3 install requests pokebase pillow
  • On Windows, open a cmd prompt window and type in:
pip install requests pokebase pillow

Testing the installation

  • Open IDLE, and then in the shell, type in the following (PIL is how you’re referencing pillow):
>>> import requests
>>> import pokebase
>>> import PIL

If there are no errors, you are good to go. If you get errors, then review the messages, and ask for help in the comments of this section if you’re still stuck.

Writing a function to fetch Pokemon

  • Create a new file and call in pokemon_simple.py.

  • Your first four lines of code will import the modules you need. We’ll explain the purpose of each module as we go along.

from pokebase import pokemon
from requests import get
from PIL import Image
from io import BytesIO
  • Now you are going to write a function. A function is a named block of code that performs a task. Functions are useful for keeping code organised, and because you can reuse them. In fact, you’re going to reuse this function in the next step of this week’s course!

  • You can write a function using the keyword def, and this function will be named fetch_pokemon. You could name it whatever you want, but it’s useful to give it a descriptive name.

from pokebase import pokemon
from requests import get
from PIL import Image
from io import BytesIO

def fetch_pokemon():
  • We’ll keep the function simple to begin with: indented within the function (to tell Python that these lines of code are inside the function), let’s ask the user which Pokemon they want to fetch.
from pokebase import pokemon
from requests import get
from PIL import Image
from io import BytesIO

def fetch_pokemon():
    name = input('Which Pokemon do you want to fetch? ')
  • Running this code wouldn’t do anything yet. This is because you haven’t yet called the function. You can call the function, i.e. execute the code inside it, by typing its name followed by parentheses:
from pokebase import pokemon
from requests import get
from PIL import Image
from io import BytesIO

def fetch_pokemon():
    name = input('Which Pokemon do you want to fetch? ')

fetch_pokemon()
  • Run your script. You should see that you are prompted for the name of a Pokemon. You can try any Pokemon you like. If you don’t know any, type in charizard.

Using pokebase

Now for the fun part! Let’s use pokebase to get some information about the Pokemon. pokebase is a library that provides access to Pokéapi, a Pokemon API. API stands for application programming interface, which is a set of tools for building software applications — in this case, apps to do with Pokemon. You can have a look at the website pokeapi.co to find out more about this particular API and try out its online version. If you want to find out about Charizard for instance, you could type pokemon/charizard into the website’s search box and press Submit.

  • The pokebase library gives us tools to write a script that does exactly the same thing: looking up different Pokemon and getting back information about them. Add another line to your function:
from pokebase import pokemon
from requests import get
from PIL import Image
from io import BytesIO

def fetch_pokemon():
    name = input('Which Pokemon do you want to fetch? ')
    poke = pokemon(name)

fetch_pokemon()
  • Running this code will not produce any results yet, because although all the information has been fetched, the script is not actually doing anything with it. Let’s change that by adding code to find out how much a Pokemon weighs.
from pokebase import pokemon
from requests import get
from PIL import Image
from io import BytesIO

def fetch_pokemon():
    name = input('Which Pokemon do you want to fetch? ')
    poke = pokemon(name)
    print(name + ' weighs ' + str(poke.weight))

fetch_pokemon()
  • Here are some other things you can find out about your Pokemon:
poke.abilities
poke.height
poke.name
poke.species
poke.stats
poke.type
poke.weight
  • At the moment, we’re interested in the pokemon.sprites. Try this code out:
from pokebase import pokemon
from requests import get
from PIL import Image
from io import BytesIO

def fetch_pokemon():
    name = input('Which Pokemon do you want to fetch? ')
    poke = pokemon(name)
    print(poke.sprites)

fetch_pokemon()
  • If you enter charizard, the data that is printed looks like this:
{'back_female': None, 'back_shiny_female': None, 'back_default': 'https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/back/6.png', 'front_female': None, 'front_shiny_female': None, 'back_shiny': 'https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/back/shiny/6.png', 'front_default': 'https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/6.png', 'front_shiny': 'https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/shiny/6.png'}

What you are seeing here are the links to different images of Charizard that the API gives you access to. To check out the images, you can copy and paste the links into a browser.

Charizard

Using requests

Now you want your program to go and fetch the image called ‘front_default’ from the website. This is why you have imported the requests module: its get method will fetch data from a web page, in this case the image that we are after.

  • Add a line of code to have your function fetch the image.
from pokebase import pokemon
from requests import get
from PIL import Image
from io import BytesIO

def fetch_pokemon():
    name = input('Which Pokemon do you want to fetch? ')
    poke = pokemon(name)
    pic = get(poke.sprites.front_default).content

fetch_pokemon()

Using PIL

Now that you have the image, it’s time to save it. With the PIL module, you can do all types of image manipulation in Python. Here, you’re just going to use PIL to save the image.

  • At the moment the image is just a bunch of 1s and 0s on your computer, so it needs to be converted into something humans can look at using the io and PIL modules.
from pokebase import pokemon
from requests import get
from PIL import Image
from io import BytesIO

def fetch():
    name = input('Which Pokemon do you want to fetch? ')
    poke = pokemon(name)
    pic = get(poke.sprites.front_default).content
    image = Image.open(BytesIO(pic))

fetch()
  • Now you can add in a line to save the image — use the gif file type.
from pokebase import pokemon
from requests import get
from PIL import Image
from io import BytesIO

def fetch():
    name = input('Which Pokemon do you want to fetch? ')
    poke = pokemon(name)
    pic = get(poke.sprites.front_default).content
    image = Image.open(BytesIO(pic))
    image.save('poke.gif')

fetch()
  • Save and run your code. Once you type in the name of a Pokemon, your script will fetch the ‘front_default’ image from the website — look in the directory where you saved your Python file, and you should see the image file there. Each time you type in a different Pokemon name, you’ll see that the image file gets overwritten.

Share this video:

This video is from the free online course:

Scratch to Python: Moving from Block- to Text-based Programming

Raspberry Pi Foundation