Lesson goal: The while-loop to guesss your number

Previous: You guess my number | Home | Next: Solving equations

As mentioned, while-loops can make a chunk of program code run over and over until the condition of the while-loop becomes false.

Here's an example of using a while loop: you think of a random number between 1 and 100. The computer will keep guessing WHILE it hasn't guessed your number correctly. Get the use of the "while?"

So go ahead, think of a number between 1 and 100. If you answer the questions truthfully, the computer will guess your number in 10 tries or less every time.

Now you try. Put a condition in the while ... do line to have the loop keep running as long as variable ans $\ne$ "y".

The code will not run!

You want the while loop to keep looping if the correct guess was not given, right? In this case, this means the person has answered the question (in the 2 print statements) with an answer other than "y" (with "y" standing for "yes"). What condition would you put in the while loop to keep it looping if $ans \ne$ "y"?

The code works as follows: we start our guess range to be between low and high which is between 1 and 100. We always guess a number that is midway between the numbers in low and high. As the program begins, this will be 50, which is $(100+1)/2$ (the math.floor function is used to drop any decimal point).

The program works by reassiging either low or high to its last guess and deriving its next guess from "guess=$\frac{low+high}{2}$." For example, if its first guess of 50 is "too low," it'll assign varible low to 50 (high is still 100). The next guess will be $\frac{50+100}{2}=75$, etc. Dismiss.

Show a friend, family member, or teacher what you've done!