Programming for Teens: Beginning Python Tutorial

In this Python tutorial you’ll be introduced to computer programming using one of the most beginner-friendly languages available. By .

Leave a rating/review
Save for later
Share
You are currently viewing page 3 of 4 of this article. Click here to view the first page.

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.