dreamsys software

Python Scripting Tutorial

Looping


While Loop

The while statement is used when you want to loop while a statement is true. This is the same in many other programming and scripting languages. The body of the loop is the indented, same as in the if/else condition. Suppose that we want to write a script to have the user guess what number we are thinking of. The best way to use this would be to use a while loop.

#!/usr/bin/env python
#guess the number game
import random

answer = random.randint(1, 10)
num = 0

while num != answer:
    num = int(raw_input('What number am I thinking of? '))

    if num != answer:
        print 'Wrong!'

print 'Correct!'

This code will repeatedly ask you 'What number am I thinking of?' until you get it right. The first thing it does is import the random package to make use of the randint function. This will give you a number between (and including) the two parameters given.

If the number entered is not equal to the answer generated at startup, it will print the text "Wrong!" and continue the loop, otherwise if you guess correcly, the loop terminates and you see the printed text "Correct!".

To loop forever in your script, you can put the number 1 in your while statement condition. Let's write a simple program that will print out how long it has been running until the user presses Ctrl+C to terminate the program.

#!/usr/bin/env python
import time

counter = 0

while 1:
    time.sleep(1)
    counter += 1

    print 'Script has been looping for', counter, 'seconds...'

This program will loop until the user presses Ctrl+C. Notice that we use something else new here. The time package is imported so that we can use the sleep function. The sleep function will sleep for the number of seconds passed in. The counter variable is updated using the += operator, which will increment the variable by the number on the right hand side.

For Loop

The for loop is used when you want to loop through a list of items. The body of the loop works the same as it does in a while loop. Let's say that we want to write a program that will validate numbers in a given list. These numbers can be loaded from a file, hard coded, or manually entered by the user. For our example, we will ask the user for a list of numbers separated with spaces. We will validate each number and make sure that it is between 1 and 100. The best way to write a program like this would be to use a for loop.

#!/usr/bin/env python

userInput = raw_input('Enter a list of numbers between 1 and 100, separated by spaces: ')
nums = userInput.split()

for strNum in nums:
    if not strNum.isdigit():
        print 'Not a Number:', strNum
    elif int(strNum) < 1:
        print 'Number is less than 1:', strNum
    elif int(strNum) > 100:
        print 'Number is greater than 100:', strNum
    else:
        print 'Number is valid:', strNum

If you enter the text "5 2 7 0 100 101 1 45 a b c", the function String.split will convert this into an array by taking each item separated by a space and converting it into a new array element. The array variable "num" is then given to the for loop using the in keyword. It will loop one time for each element in the array and assign the variable "strNum" the value of that object in the array.

Now that we have the strNum object, which is the string representation of the current item in the array, first we need to make sure that it's a number, we can do this with the String.isdigit() function. If it is not a number, it will return false, then we will print out the validation error. If it is a number, then the elseif conditions will continue, the next condition checks to see if the number is less than 1, if so it prints the error. Next it checks for greater than 100 and prints an error. If all checks pass, the else block is called, printing the valid number message. Here is an example run:

Enter a list of numbers between 1 and 100, separated by spaces: 5 2 7 0 100 101 1 45 a b c
Number is valid: 5
Number is valid: 2
Number is valid: 7
Number is less than 1: 0
Number is valid: 100
Number is greater than 100: 101
Number is valid: 1
Number is valid: 45
Not a Number: a
Not a Number: b
Not a Number: c

When your scripts start to get large or repetitive, it's time to start learning about functions, which are described in the next section.

Prev (OptionParser) | Next (Functions)


Blog Entries
Blob Entry 1
Blob Entry 2
Blob Entry 3
Blob Entry 4
Blob Entry 5
Blob Entry 6