A Beginner's Python Tutorial/for Loop

Introduction

edit

Well, in the first lesson about loops, I said I would put off teaching you the for loop, until we had reached lists. Well, here it is!

The 'for' Loop

edit

Basically, the for loop does something for every value in a list. The way it is set out is a little confusing, but otherwise is very basic. Here is an example of it in code:

Code Example 1 - The for Loop
# Example 'for' loop
# First, create a list to loop through:
newList = [45, 'eat me', 90210, "The day has come, the walrus said, to speak of many things", -67]

# create the loop:
# Goes through newList, and sequentially puts each bit of information
# into the variable value, and runs the loop
for value in newList:
    print(value)

As you see, when the loop executes, it runs through all of the values in the list mentioned after 'in'. It then puts them into value, and executes through the loop, each time with value being worth something different. Let's see it a again, in a classic cheerleading call that we all know:

Code Example 2 - A for loop example
# cheerleading program
word = input("Who do you go for? ")

for letter in word:
    call = "Gimme a", letter + "!"
    print(call)
    print(letter + "!")
print("What does that spell?")
print(word + "!")

A couple of things you've just learnt:

As you see, strings (remember - strings are lines of text) are just lists with lots of characters. The program went through each of the letters (or values) in word, and it printed them onscreen.

Code Example 3 - Looping through a range

Sometimes, you may only need to loop a certain amount of times (say 10). If you're coming from another programming language, you might be looking for the usual for loop in a format somewhat like this:

for (var i = 1 ; i < 10 ; i++ ) {
}

Python doesn't have this type of loop. If you want to loop a certain number of times, simply use range().

# The below code will print numbers from 0 through 9
for integer in range(0,10):
  print(integer)

# The above code can further be simplified to:
# for integer in range(10):
#   print(integer)

A couple of things you must take note of:

  • The range starts with the starting number and ends up to the ending number. If you wanted to loop from 0 through 100, your range function will be range(0,101) as the function doesn't include the ending number.
  • The parameters for the range function are start (default of 0), end, and step (default is 1). A step is simply how much range() will increment by. If you wanted to loop from 100 to 0, simply use a step of -1. In other words: range(100,0,-1).

Making a Menu Function

edit

Now to the business end of the lesson. Lets start writing programs. So far we have learnt variables, lists, loops, and functions. That is pretty much all we need for quite a bit of programming. So let's set ourselves a task.

Code Example 4 - A menu function
# THE MENU FUNCTION
# The program asks for a string with all the menu options in it,
# and a text string asking a question.
# make sure every menu entry is unique.

def menu(list, question):
    for entry in list:
        print(1 + list.index(entry),)
        print(") " + entry)

    return input(question) - 1

# def menu(list, question): is telling the function to
# ask for two bits of information:
# A list of all the menu entries,
# and the question it will ask when all the options have been printed

# for entry in list: is pretty much saying;
#'for every entry in the list, do the following:'

# print list.index(entry) + 1 uses the .index() function to find
# where in the list the entry is in. print function then prints it
# it adds 1 to make the numbers more intelligible.

# print ") " + entry prints a bracket, and then the entry name

# after the for loop is finished, input(question) - 1 asks the question,
# and returns the value to the main program (minus 1, to turn it back to
# the number the computer will understand).

That wasn't very difficult, was it? the actual program only took up five lines - this is the wonder of how much we have learnt so far! All my comments take up sixteen lines - more than three times the program length. It is a good idea to comment your programs extensively. Remember that if you are going to be publishing your code open-source, there are going to be a lot of people checking out the code that you have written. We'll see the function we just wrote in our first example program.

Our First 'Game'

edit

What will our first example program be? How about a (very) simple text adventure game? Sounds like fun! It will only encompass one room of a house, and will be extremely simple. There will be five things, and a door. In one of the five things, is a key to the door. You need to find the key, then open the door. I will give a plain-english version first, then do it in python:

Code Example 5 - Plain-english version of code
#Plain-english version of our 'game'

Tell the computer about our menu function

Print a welcoming message, showing a description of the room.
We will give the player six things to look at: plant, painting,\
 vase, lampshade, shoe, and the door

Tell the computer that the door is locked
Tell the computer where the key is

present a menu, telling you what things you can 'operate':
    It will give you the six options
    It will ask the question "what will you look at?"

if the user wanted to look at:
    plant:
        If the key is here, give the player the key
        otherwise, tell them it isn't here
    painting:
        same as above
    etc.
    door:
        If the player has the key, let them open the door
        Otherwise, tell them to look harder

Give the player a well done message, for completing the game.

From this, we can write a real program. Ready? Here it is (skip typing the comments):

Code Example 6 - Text Adventure Game
#TEXT ADVENTURE GAME

#the menu function:
def menu(list, question):
    for entry in list:
        print(1 + list.index(entry),)
        print(") " + entry)

    return int(input(question)) - 1

#Give the computer some basic information about the room:
items = ["plant","painting","vase","lampshade","shoe","door"]

#The key is in the vase (or entry number 2 in the list above):
keylocation = 2

#You haven't found the key:
keyfound = 0

loop = 1

#Give some introductory text:
print("Last night you went to sleep in the comfort of your own home.")

print("Now, you find yourself locked in a room. You don't know how")
print("you got there, or what time it is. In the room you can see")
print(len(items), "things:")
for x in items:
    print(x)
print("")
print("The door is locked. Could there be a key somewhere?")
#Get your menu working, and the program running until you find the key:
while loop == 1:
    choice = menu(items,"What do you want to inspect? ")
    if choice == 0:
        if choice == keylocation:
            print("You found a small key in the plant.")
            print("")
            keyfound = 1
        else:
            print("You found nothing in the plant.")
            print("")
    elif choice == 1:
        if choice == keylocation:
            print("You found a small key behind the painting.")
            print("")
            keyfound = 1
        else:
            print("You found nothing behind the painting.")
            print("")
    elif choice == 2:
        if choice == keylocation:
            print("You found a small key in the vase.")
            print("")
            keyfound = 1
        else:
            print("You found nothing in the vase.")
            print("")
    elif choice == 3:
        if choice == keylocation:
            print("You found a small key in the lampshade.")
            print("")
            keyfound = 1
        else:
            print("You found nothing in the lampshade.")
            print("")
    elif choice == 4:
        if choice == keylocation:
            print("You found a small key in the shoe.")
            print("")
            keyfound = 1
        else:
            print("You found nothing in the shoe.")
            print("")
    elif choice == 5:
        if keyfound == 1:
            loop = 0
            print("You put in the key, turn it, and hear a click")
            print("")
        else:
            print("The door is locked, you need to find a key.")
            print("")

print("Light floods into the room as you open the door to your freedom.")

Well, a very simple, but fun, game. Don't get daunted by the amount of code there, 53 of the lines are just the 'if' statements, which is the easiest thing to read there. (Once you comprehend all the indentation, you'll be able to make your own game, and you can make it as simple [or as complex] as you like.)

Making the Game Better

edit

The first question you should ask is "does this program work?". The answer here is yes. Then you should ask "does this program work well?" - not quite. The menu() function is great - it reduces a lot of typing. The 'while' loop that we have, however, is a little messy - four levels of indents, for a simple program. We can do better!

Now, this will become much MUCH more straightforward when we introduce classes. But that will have to wait. Until then, let's make a function that reduces our mess. We will pass two things to it - the menu choice we made, and the location of the key. It will return one thing - whether or not the key has been found. Lets see it:

Code Example 7 - Creating an inspect function
def inspect(choice,location):
    if choice == location:
        print("")
        print("You found a key!")
        print("")
        return 1
    else:
        print("")
        print("Nothing of interest here.")
        print("")
        return 0

Now the main program can be a little simpler. Let's take it from the while loop, and change things around:

Code Example 8 - The new game
while loop == 1:
    keyfound = inspect(menu(items,"What do you want to inspect? "), keylocation)
    if keyfound == 1:
        print("You put the key in the lock of the door, and turn it. It opens!")
        loop = 0

print("Light floods into the room, as you open the door to your freedom.")

Now the program becomes massively shorter - from a cumbersome 83 lines, to a very shapely 50 lines! Of course, you lose quite a bit of versatility - all the items in the room do the same thing. You automatically open the door when you find the key. The game becomes a little less interesting. It also becomes a little harder to change.