Multiplication Arrays

Back to index

This program demonstrates the use of functions, while loops, and for loops. Get it up and running and run it a few times. Try to trace the course of execution to the best of your ability.
#!/usr/bin/python x=0 y=0 def getN(): innum = int(raw_input("Enter an integer between 2 and 12: ")) return innum while x<2 or x>12: x=getN() while y<2 or y>12: y=getN() for a in range(x): print "x" * y
Highlights:

def - As you might guess, def is short for define and it is used to begin the definition of a function. Rarely do you see functions which are only two lines long, but this is a demo program, so what do you expect? Anyways all the getN function does is take input and return that input so that it can be saved into a variable. BTW, the int function that's wrapped around the raw_input function changes input from string form to integer form so that it is treated as a number value as opposed to a string value.

while - You see two while loops in this program. Each basically loops for as many times as it takes for the user to enter the input being asked for. If the user enters 55, then the program stays in whichever loop it's in. Obviously this could go on for quite a long time if the user repeatedly fails to enter acceptable input.

for - The for-loop as written produces an array of x's the size of which depends on the numbers entered by the user. The range operator is used to take the value stored in x and use it to specify how many times the for-loop iterates.


ASSIGNMENT:

You will create a number guessing game. You will instruct the user to enter a number between 1 and 1000. You will continue to accept input from the user until the user guesses the correct number. After each wrong guess the user will be informed if the guess was too high or too low. Input which is not between 1 and 1000 will trigger an error message instructing the user to follow directions and enter appropriate input. (Keep in mind that a single equal sign is used for assigning a value to a variable, whereas double equal signs are used to compare values.)