Wednesday, September 15, 2010

Random Number Game - Python

In my logic class we were instructed to produce psuedocode for a program that produces a random number 1-10, asks the user to input a number, and outputs both numbers. Here is my version and the python code for it:

Start
Declarations
  int randomNumber = random(10)
  int guess = 0
output "Guess my number! (1-10)"
input guess
while guess != randomNumber
  if guess == randomNumber
    output "Good Job!"
  else
    output "Sorry you're wrong"
    if guess < randomNumber
      output "Guess too Low. Try again."
    else
      output "Guess too High. Try again."
Stop

The nice thing about Python is that it is not much different than psuedocode, we just have to pay attention to the syntax. The only thing new here from previous posts is the random number generator which you will see below.

#Start
import random    # Necessary to call random later
randomNumber=random.randint(1,10)
guess=0
while guess != randomNumber:
    guess=int(input("Pick a number 1-10: "))
    if guess == randomNumber:
        print("Good Job!")
    else:
        print("Sorry you're wrong.")
        if guess < randomNumber:
            print("Guess too low. Try again.")
        else:print("Guess too high. Try again.")
#Stop


I used random.randint(x,y), x and y being low and high values respectively, to generate my number. You could also have used random.randrange(x,y,z) with x as low value, y as high value, and z being step. For example:

>>random.randrange(0,100,10)
80

The above code generates a random number 0 through 100 at steps of 10 (i.e. 10, 20, 30,...). How would you produce the above "game"?

1 comment: