= Learn Python with this Ebook

:Author: Seth Kenlon 
:Email: <seth@opensource.com>
:Revision: 1.0

Python is one of the most popular programming languages out there.
Whether you want to learn it for work or for fun, it's a powerful and useful language for any purpose.
You can create applications to help you with daily tasks, you can create fun games you and your friends can play, you can create scripts to process data, applications to generate or parse information, and much more.
Our philosophy is that no matter what you intend to do with a programming language, it's more fun to learn by creating a game than just by crunching numbers or transforming strings.
And if you're completely new to programming, then it's a lot easier to understand why you have to do something in code when you can see the code working in a familiar setting like a video game.

Python isn't necessarily the best programming language available (everyone has their own answer for that), but it is a relatively non-intimidating one.
Python can use a lot of words (such as `is` and `is not`) instead of symbols (such as `=` and `!=`).
It also manages many low-level tasks so you usually don't have to worry about things like data types and garbage collection.
This generally means you can get started coding without the upfront frustration that a complex language, such as a https://opensource.com/article/20/8/c-programming-cheat-sheet[C] or https://opensource.com/resources/java[Java].

To help people learn Python, we wrote an ebook teaching you how to create a platformer video game.
Step through the lessons to learn Python while building a video game.
As an additional benefit, you'll also learn about programming logic, syntax, operators, and more.
You can see immediate results as you learn, so everything you learn is promptly reinforced.

== Python in 1 minute

Python is a general purpose language, meaning it, like most languages, provides functions to do simple "tricks" with numbers and letters.
Linux users already have Linux installed.
Mac users have an old version of Python installed, but you can https://www.python.org/downloads/mac-osx[install the latest version from Python.org website].
Windows users can learn to install Python from this https://opensource.com/article/19/8/how-install-python-windows[Install Python on Windows] article.

Once installed, you can start an interactive Python shell and do math:

----[source,python]
$ python3
>>> 5+6
11
>>> 11/2
5.5
>>> 11//2
5
>>> 11%2
1
----

As you can see from this sample session, there's some special notation required, but it's mostly familiar to anyone comfortable with math.
Maybe you're not a maths person, and prefer letters:

----[source,python]
$ python3
>>> string = "hello world"
>>> print(string)
hello world
>>> print(string.upper())
HELLO WORLD
>>> print(string[0])
h
>>> print(string[1])
e
>>> print(string[2])
l
>>> print(string[3])
l
>>> print(string[4])
o
----

Again, there's special notation for relatively basic tasks, but even without explanation, you have probably already detected that the `[0]` and `[1]` notation enables you to "slice" data, and that `print` presents data to you on your screen.

== Pygame in 5 minutes

If you had to create a video game, or anything beyond a basic calculator, with just Python, it would take a lot of study, work, and time.
Luckily, Python's been around for a couple of decades, and so people have developed libraries of code to help you perform typical programming feats with (comparatively) very little effort.
Pygame is a set of code modules designed for video game creation.
It's https://opensource.com/article/18/4/easy-2d-game-creation-python-and-arcade[not the only one], but it's the oldest (for better and for worse) and so there's a lot of documentation and examples online.

Start by learning LINK TO MY VENV ARTICLE[the recommended Python virtual environment workflow]:

----[source,bash]
$ python3 -m venv mycode/venv
$ cd mycode
$ source ./venv/bin/activate
(venv)$ 
----

Once in a virtual environment, you can safely install Pygame into your project folder.

----[source,bash]
(venv)$ echo "pygame" >> requirements.txt
(venv)$ python -m pip install -r requirements.txt
[...] Installing collected packages: pygame
Successfully installed pygame-x.y.z
----

Now that you have Pygame installed, you can create a simple demo application.
It's easier than you think.
Python can do what's called _object-oriented programming_ (OOP), which is a fancy computer science term to describe when code is structured as if you were creating physical objects with code.
Programmers aren't deluded, though.
They know they're not really making physical objects when they code, but it can help to imagine it that way, because then you understand the limits of your programmed world.

For instance, if you were stranded on a desert island and wanted a coffee cup to appear, you'd have to harvest some clay, fashion a cup, and bake it.
If you were very clever, you'd create a mold first so that whenever you wanted an additional cup in the future, you could quickly create a new one from your template.
Even though each cup came from the same template, they would be physically independent: should one break, you still have others.
And you could make each coffee cup appear unique by adding colour or etchings.

In Pygame, and in many programming tasks, you use similar logic.
A thing can't appear in your programmed world until you define it.
Here's how to make a coffee cup appear in a Python and Pygame program.

=== Object-oriented programming with Pygame

Create a new file called `main.py` and enter this code to initiate the Pygame module, and to use a Pygame template to create a window:

----[source,python]
import pygame

pygame.init()

screen = pygame.display.set_mode((960,720))
----

Just as you might use a template to create an object in real life, you use a template provided by Pygame to create a _sprite_ (which is Pygame's term for a visual game object).
In object-oriented programming, a _class_ represents a template for an object.
Type this code into your document:

----[source,python]
class Cup(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)

	# image
        img = pygame.image.load('coffeecup.png').convert()
        self.image = img

	# volume
        self.rect = self.image.get_rect()
        self.rect.x = 10
        self.rect.y = 10
----

In this code block, you use the Pygame `sprite` template to design a coffee cup sprite.
Your coffee cup sprite has an image because of `self.image`, while `self.rect` gives it volume (width and height).
These are attributes Pygame expects a sprite to possess, but were you creating a playable video game, you could also give it any attribute you wanted, such as health points and a score.

All you've done so far is create a window and the _template_ for a cofee cup.
Your game doesn't actually _make_ a cup yet.

The last part of your code must use your template to generate a cup, and then add it to your game world.
As you may know, computers are very fast, so technically the code you've created so far would only run for a millisecond or so.
When writing a graphical computer application, you must force the computer to remain open whether or not it thinks it has completed the proscribed tasks.
Programmers do this with an _infinite loop_, which in Python is represented by the instruction `while True` (True is always true, so the loop never ends).

An infinite loop ensures that your application stays open long enough for the computer user to see and use the application.

----[source,python]
cup = Cup()

while True:
    pygame.display.update()
    screen.blit(cup.image, cup.rect)
----

In this code sample, you create a cup from your template `Cup`, and then you update the display using a Pygame function.
Finally, you draw the cup's image within its bounding box using the Pygame `blit` function.


=== Get a graphic

Before you can run the code successfully, though, you need a graphic for your coffee cup.
You can find lots of https://opensource.com/article/20/1/what-creative-commons[Creative Commons] coffee cup graphics on http://freesvg.org[FreeSVG.org].
I use https://freesvg.org/1548870028[this one].
Save the graphic in your project directory, and call it `coffeecup.png`.

=== Run the game

Launch your application.

----[source,bash]
(venv)$ python ./main.py
----

image:coffeecup.png[Coffee cup in Pygame]

== Download the ebook

Pygame's a powerful framework, and there's a lot more you can do with it than just draw coffee cups on screen.
Download our free ebook to get to know Pygame, and Python itself, better.

[LINK TO EBOOK]
