Programming for Teens: Beginning Python Tutorial

Julian Meyer

Learn to code with Python!

Have you ever wondered how a computer works? While we can’t teach you everything in one blog post, you can get a pretty good start by learning how to write your own programs!

In this Python tutorial, you’ll learn the basics of programming a computer using one of the best languages for beginners.

What is Programming?

To put it as simply as possible, programming is the act of writing code that instructs a computer to perform a task.

A task can be as simple as adding two numbers together, or as complex as sending a spaceship into orbit!

The smallest element of a program is known as statement — this represents a single instruction to the computer.

All the things!

After you’ve written your program, a compiler converts the code you’ve written into machine code — the lowest-level language of a computer. Machine code instructs the central processing unit, or CPU, what steps to take such as loading a value, or performing some arithmetic.

If you’ve ever heard somebody say “I compiled my program”, it means they converted their code into machine code.

Why wouldn’t you just write machine code directly? The obvious reason is that program code is human readable. Compare the Python version of a program with its corresponding set of machine code below:

The Python Program

print "Hello, World!"
...
"Hello, World!"

The Machine Code Equivalent

c7 3c 2a 3c 2a 2b 2a 5c 3c 28 5c 2a 2b 2a 5c 3c
28 5c 2a 2b 2a 5c 3c 28 5c 2a 2b 2a 5c 3c 28 5c
2a 2b 2a 5c 3c 28 5c 2a 2b 2a 5c 3c 28 5c 2a 2b
2a 5c 3c 28 5c 2a 2b 2a 5c 3c 28 5c 2a 2b 2a 5c
3c 28 5c 2a 2b 2a 5c 3c 28 5c 2a 2b 2a 5c 3c 28
5c 2a 2b 2a 5c 3c 28 5c 2a 2b 2a 5c 3c 28 5c 2a
2b 2a 00 00 01 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 64 48 65 6c 6c 6f 2c 20 57
6f 72 6c 64 21 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
...
"Hello, World!"

It’s quite evident why you don’t want to program directly in machine code. However, there are a few people who do — there’s no accounting for taste! :]

There’s one minor detail we left out above. Python is an interpreted language; you don’t compile it directly into machine code as we alluded to above.

Instead, Python uses something called an Interpreter. An interpreter is yet another program that compiles code into something called Bytecode, which is then converted into machine code as the program runs. You’ll read more about interpreters later.

When you finally run the program, the machine code you recently compiled is loaded into memory and read by the CPU to execute the program.

However, you don’t need to really understand the inner workings of compilers to get started programming in Python, but you should first make sure that you have Python installed.

Getting Started

If you’re on a Mac, you’re in luck — Python comes preinstalled on a Mac.

To use the Python interpreter on a Mac, open Terminal.app; you can find it either in your Applications/Utilities folder, or by typing Terminal directly into Spotlight, like so:

terminalspotlight2

Once Terminal is open, type the following command and press Enter:

$ python

You should see something that looks like the following:

Screen Shot 2014-03-10 at 10.47.36 PM

Note: If you don’t get the output shown above, post the output from Terminal on the forum and we’ll do our best to help you out!

Windows

The process is a little more involved on Windows — but then again, most things are on Windows! :]

First, visit the official Python downloads page in your browser.

Scroll past the Python 3.x.x versions, all the way down to Python 2.7.x. Download the Windows installer, run it, and follow the instructions it presents, accepting the defaults along the way.

Once the installer has finished, you’ll need to launch the interpreter.

On Windows Vista or Windows 7, launch the interpreter like so:

  1. Click the Start button in the lower left hand corner
  2. Click on All Programs
  3. Open the folder named Python
  4. Double click the IDLE interpreter

If you’re on Windows 8, launch the interpreter this way:

  1. Click the Start button in the lower left hand corner
  2. Type IDLE into the search bar
  3. Click on IDLE (Python GUI)

Regardless of how you launched the interpreter, you’ll want to make sure that it works. Type the following command in Terminal, or Command Prompt in Windows, and press Enter:

print “Hello World!”

Although it doesn’t seem like much, you’ve just written your very first Python program! Printing Hello, World is often considered the de facto starting point when learning most languages.

The print command instructs the computer to print what follows on the screen — not print it out to your printer! Note the quotation marks around “Hello World”; anything contained inside the quotation marks is considered to be regular text and won’t be interpreted as an instruction.

Variables

Variables are a way of storing data in the memory on a computer; you’ll use them a LOT as you program. In some languages, variables have a specific type which indicates what kind of variable class they belong to.

In Python, you don’t have to declare your variable types. Don’t worry too much about that detail now; you’ll learn more about this a little later in the tutorial.

Type the following command into the interpreter and press Enter:

hello = "Hello World!"

This declares and sets the hello variable to the value Hello World. Now, instead of typing “Hello World” everywhere you need that string in your program, you can just use the hello variable.

Type the following command into the interpreter and press Enter:

print hello

This prints out the same thing as your Hello World example, but instead it’s printing out the value of the hello variable.

Variables can also be used to store numbers. Type the following commands into your interpreter:

x = 5
print x
y = 10
z = x + y
print z

Note: From now on, there may be multi-line statements of code for you to type in. Simply hit Enter after each line.

Try to guess what the code above does before reading the spoiler below:

Solution Inside SelectShow

Variables are core to most of the programming you’ll do in your life. You’ll become intimately familiar with them as you work your way through this tutorial!

Variable Types

You encountered variable types a little earlier in this tutorial, but we didn’t cover them in any detail. Each variable type stores a different kind of value.

Note: For a complete list of built-in types in Python, check the official Python documentation.

So far, you’ve only dealt with two basic types in Python: integers and strings. You’ll also encounter boolean types which you can use to store True and False values.

Here’s a bit of detail on each of these variable types:

Integers

An integer is a whole number. Integers range from -2147483648 to 2147483647 on 32-bit machines, and from -9223372036854775808 to 9223372036854775807 on 64-bit machines.

You create an integer variable by simply typing the number without any quotation marks, as shown below:

foo = 5

Strings

A string is a sequence of characters; you can use a string to represent anything from text on a screen to entire web requests.

You create a string variable by surrounding the sequence of characters with quotation marks as shown below:

bar = "foo-bar"

Booleans

Booleans represent either True or False values.

You create a boolean variable by typing a capitalized True or False without quotation marks as shown below:

isFoo = True

There aren’t any quotation marks around the variable; if you did surround True with quotation marks, you’d be declaring it as a string variable instead!

Adding Strings and Integers

Python makes it really easy to hook strings together, also known as concatenation. You can convert values from integer types to string types using the str() command. Likewise, you can convert a value from a string to an integer by using int().

Enter the following commands into your interpreter:

"1" + "1"
1 + 1
1 + int("1")

Here’s what’s going on in your code above:

  • The first statement concatenates the two strings; the quotation marks ensure the numbers are treated as strings. The result is simply "11".
  • The second statement adds the two numbers together as integers with 2 as the result.
  • The final statement adds an integer to a string that has been converted to an integer, so it also returns 2.

If Statements

If statements check whether a conditional is true, and if so, they execute a block of code. Conditionals are usually in the form of valueoperatorvalue and usually compare two values.

For example, you could evaluate whether a variable is equal to zero with the expression x == 0, where == is the equality operator.

Here are some common comparisons in Python:

a == b: #Checks if a and b are equal
a != b: #Checks if a and b are not equal
a > b:  #Checks if a is greater than b
a < b:  #Checks if a is less than b
a >= b: #Checks if a is greater than or equal to b
a <= b: #Checks if a is less than or equal to b

If statements take the following form:

if conditional:
    do_statements_here

Note how the do_statements_here line is indented. This is how you declare code blocks in Python. It's imperative that every line in a code block is indented by the same number of tabs or spaces as all other lines in the code block; this is a rule enforced by the language itself. In other words, don't mix tabs and spaces!

To create an if statement, type the following into your interpreter:

pyblock

You'll be greeted by the cryptic prompt ...; this indicates the interpreter is waiting for your code block.

Press Tab, and type the second line as follows:

pyblocktab

Press Enter one more time and your cursor returns to the left side of your console. To add another line to the conditional block, just hit Tab.

If you're done entering lines, press Enter to tell the interpreter that your code block is complete.

pyblockcomplete

Take a look at the example below:

x = 10
y = 10
if x == 10:
    print "x equals 10!"
if x == y:
    print "x equals y!"

The first if statement checks whether x is equal to 10; if so, it prints out x equals 10!. The other if statement checks whether x and y; if so, it prints "x equals y!".

For Loops

For loops in Python loop through items in a list and set a variable to the current item in the list. A list is a collection of just about anything!

Type in the following code, indenting as shown below:

for x in range(10):
    print x

In this example, range(10) generates a list of numbers from 0 to 9. The for loop, in turn, sets x to each number in the range.

Just like an if statement, a for loop executes everything indented beneath it. In the above example, the indented code block only contains a single statement.

Since print is called ten times, once for each item in the list, the program prints the numbers from 0 to 9.

Functions

Functions are reusable blocks of code that perform specific tasks. For example, you could write a function to add two numbers together, or print out a string.

You define and call a function as shown in the example below:

def hello():
    print "Hi"
for x in range(3):
    hello()

Can you guess what the output of this program is before you run it? Check your answer below:

Solution Inside SelectShow

The indented code defines the statements which run when you call the function. Since print "Hi" is the only indented line under the function declaration, it's the only line that executes when the function is called — not the other lines below.

You call a function by typing the function name followed by open and closed parentheses. As shown earlier, hello() calls the function you declared above.

Functions are a little like walled gardens: they can't see anything outside of their own little area. This is known as variable scope. If you want a function to work with any outside data, you'll need to pass that data to the function.

This is accomplished using arguments — and no, functions don't argue with each other! :]

An argument is a variable that you pass to a function; the function can then access the value of that variable inside its walls.

You declare a function with arguments as follows:

def add(a, b):
    print a + b

The above function defines two arguments, a and b, separated by commas between the parentheses. When you call the function, the interpreter sets the value of a and b to the value of the variables you pass in.

Take a look at the example below:

def add(a, b):
    print a + b
add(1,2) # prints 3!

In the example above, the statement add(1,2) sets a and b to 1 and 2, respectively. The function then prints out the sum of the two numbers you passed in.

The above example prints out the result of the calculation — but what if you wanted to do something with the result of that calculation? What if you wanted to add other values to the result of the function?

To do this, you'll need to add a return statement to your function.

Consider the code below:

def add(a,b):
    return a + b
print add(2, 2) + 1

In the above example, your function adds the two numbers as before, but the return statement then passes the sum of the two numbers back to the calling statement.

That means the print statement above takes the value returned by add(2,2) and adds it to 1, which will give the final value of 5.

While Loops

While loops are similar to for loops. For loops continue until you reach the end of a list, but while loops will repeat indefinitely until a given condition evaluates to False.

The general structure of a while loop is shown below:

while (conditional):
    run_statement

Generally, the conditional variable in a while loop is updated as the loop runs.

To see this in action, type the following into your interpreter:

x = 0
while x < 10:
    print x
    x += 1

This behaves the same as the for loop example above, but uses a while loop instead.

Here's what the code above does:

  1. Sets x = 0
  2. Checks if x < 10
  3. If x < 10 evaluates to True, then execute the block below. If it evaluates to False then exit the loop
  4. Print x
  5. Increment x by 1

One thing to watch out for with while loops is creating an infinite loop.

To see how an infinite loop functions, type the following code into your interpreter:

x = 0
while True:
    print x
    x += 1

All the things!

Whoa — Terminal is going pretty crazy, isn't it? Terminate your program by pressing Control+C on your keyboard.

What the heck happened there? If you look closely, you'll see that it was impossible for the while loop conditional: True, to ever evaluate to False, so the block executed as fast as the CPU could crunch numbers.

The moral of this story: always be careful when writing while loops, because infinite loops in your code are rarely considered a good thing out in the real world!

It is possible to use True as your while loop conditional, especially when you might not know how many times your loop should execute. However, you need to use a little trick to exit out of the loop.

Type the following code into your interpreter:

x = 0
while True:
    print x
    x += 1
    if x > 10:
        break

That's better! The above code prints the numbers from 0 to 10 and exits. The trick here is to use the break statement which immediately exits out of any loop. You can also use this technique if you're in the middle of a for loop and need to exit prematurely for whatever reason.

Capturing User Input

One cool thing about Python is that it's very easy to receive input in the form of text from the user. Input is any external data provided to a program, such as text or other directions which affect the behavior of a program.

Type the following code into your Python interpreter:

name = raw_input("What is your name? ")
print "Hello, " + name

The above code first asks the user for input; once the user types in their answer to the question the program assigns it to the variable name. Once that's done, the program then concatenates the string "Hello, " with the contents of the variable name.

The raw_input() function is built right into Python; it does the work of printing out the provided string to the console, captures the text input from the user, then returns the captured text as the return value of the function.

You can make a simple calculator using the above technique of capturing user input.

Type the following code into your interpreter:

a = raw_input("Number 1: ")
b = raw_input("Number 2: ")
print int(a) + int(b)

First, you capture two values input by the user and assign them to the a and b variables respectively. Then you convert the input values into integers and add them together.

Why the conversion step? Simply because raw_input() interprets all input as strings, and you want to add the integer values together.

If you didn't convert the strings to integers, what do you think would happen? That's right — the program would print out the concatenation of the two strings, which is not what you want!

Imports

Before you dig into imports, it's worthwhile introducing the Python module.

A module is a group of Python functions which you can reuse in your programs. Importing a module is the equivalent of taking the all the code from the module and putting it right into your program so you can use all of the functions whenever you want, but without cutting and pasting a single line of code!

There are lots of modules available in the Python community, but right now you'll just touch on the random module.

To import a module, type the following into your interpreter:

import random

Once the random module has been imported, you can use it like this:

print random.randint(0, 100)

This prints out a random integer between 0 and 100; pretty straightforward stuff.

You've gained a lot of knowledge by this point, enough to put together a small program that exercises everything you've learned so far!

Guessing Game Time!

Guessing Game

This is where all of your hard work learning to code Python pays off. You're going to create your very own guessing game!

First off, you'll need a better way to run programs than typing them directly into the Python interpreter, statement by statement.

To do that, you'll create a Python file.

Mac

To create a simple Python file on a Mac, type the following commands into Terminal:

$ touch guess.py
$ open -t guess.py

This creates an empty file called guess.py using the touch command, then opens that file in your default text editor using the open -t command.

Once you have some code in your Python file, you can execute your program by typing python guess.py in Terminal.

Windows

On Windows, click on the File menu in IDLE and scroll down to New File. You'll see a text editor appear where you can type in your new program.

Click the File menu again, and choose Save. Name the file guess.py and save it to whatever location you like.

To run your program, select Run\Run Module from the menu bar, like so:

IDLE will then open up the interpreter and show you the output of your program.

Game Time!

The guessing game will generate a random number, then use a loop to ask the player repeatedly for their guess. If the user guesses the number, it'll exit the loop; otherwise the program will notify the user if their guess was too high or too low and continue to ask the player for guesses until they get it right.

You'll begin by generating a random number that will be used for the player to guess.

Add the following code to the Python file you just created:

import random

number = random.randint(0, 100)

The above code imports the random module, then generates a random number between 0 and 100 and stores it in the variable number.

Next, you need to ask the player for their guess. Add the following code to the bottom of your program:

guess = raw_input("Guess the Number: ")

This code, as you can probably guess, asks for user input and assigns it to the variable guess. Remember, that variable is now set to a string — you'll need to convert that string to an integer.

Add the following code to your program, right after the guess statement you added above:

guess_int = int(guess)

This code sets the variable guess_int to the integer value of the string you received from the user.

Next you need to compare the user's guess to the randomly selected number.

Add the following code to the end of your program:

if number > guess_int:
    print "Too low!"
if number < guess_int:
    print "Too high!"
if number == guess_int:
    print "You got it!"

Run your program by clicking Run\Run Module in the menu bar or entering python guess.py in Terminal; enter a number when your program prompts you. What happens?

The program stops as soon as you enter a number and it outputs the result to the screen. Whoops!

You want the program to continue looping until the person guesses correctly. You'll add this functionality by using a variable named running.

Add the following code just after the import statement:

running = True

running will be used with a while loop to control the looping of your program. When the user guesses the correct number, the program will set running to False and the while loop will stop.

Add the following code right before the statement where you ask the user for a number:

while running:
    guess = raw_input("Guess the Number: ")
    ...etc

Next, indent the remainder of the program by one level so the while loop recognizes this as the code block for the loop.

Finally, you need to add the logic that sets running to False once the user wins.

Add the following code directly after the third print statement:

if number == guess_int:
    print "You got it!"
    running = False

Make sure that the two lines below the if statement are indented by two levels.

Run your program, and try it out now. How many guesses will it take you to guess the right number?

Guess the number: 50
Too Low!
Guess the number: 75
Too Low!
Guess the number: 87
Too High!
Guess the number: 80
Too Low!
Guess the number: 82
Too Low!
Guess the number: 84
Too High!
Guess the number: 83
You Got It!

Your completed program should now look like the following:

import random
running = True
number = random.randint(0, 100)

while running:
    guess = raw_input("Guess the Number: ")

    guess_int = int(guess)

    if number > guess_int:
        print "Too low!"
    if number < guess_int:
        print "Too high!"
    if number == guess_int:
        print "You got it!"
	running = False

Congratulations — you've just written your first Python program. That wasn't so hard, was it? :]

Where to Go From Here?

Now that you've successfully completed this Python tutorial for beginners, I bet you're itching for a challenge. Try adding the following features to your program:

  • A running count of guesses
  • A bigger range of numbers to pick from
  • A computer opponent to compete against

If you are looking to make a slightly more complicated game, check out one of my other tutorials: Beginning Game Programming for Teens with Python.

If you have any comments or feedback, feel free to share them in the forum!

Julian Meyer is a 13-year-old python programmer from Northern California. He has programmed PixelBuild, a simple block-building game and has his own blog about programming, arduino, and music here.

Other Items of Interest

Save time.
Learn more with our video courses.

raywenderlich.com Weekly

Sign up to receive the latest tutorials from raywenderlich.com each week, and receive a free epic-length tutorial as a bonus!

Advertise with Us!

PragmaConf 2016 Come check out Alt U

Our Books

Our Team

Video Team

... 20 total!

iOS Team

... 78 total!

Android Team

... 26 total!

Unity Team

... 11 total!

Articles Team

... 15 total!

Resident Authors Team

... 18 total!

Podcast Team

... 7 total!

Recruitment Team

... 9 total!