Lesson goal: The while-loop to average numbers

Previous: Type some words | Home | Next: Mouse clicks

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 that asks you to type a number. As long as you type a positive number, it'll keep computing the average of your numbers. As soon as you type in a negative number, it'll stop and tell you the average.

The code won't quite work. What condition you put in the while ... do line that will keep it looping as long as $n \ge 0$?

Now you try. Put a condition in the while ... do line that will keep the while loop running as long as $n\ge 0$.

Type your code here:

See your results here:

This code will not run! What condition will you put in the while loop to cause it to have a true condition as long as the text in variable n is $\ge 0$? Note: the tonumber() function around the input() function it to ensure the information read from the keyboard will be an actual number (not a string). Dismiss.
Show a friend, family member, or teacher what you've done!

Here is a share link to your code:

Does your code work? Want to run it on your iPhone?

Here's your code:

  1. Use [Control]-[C] (Windows) or [⌘]-[C] (MacOS) to copy your code.

  2. Paste it using [Control]-[V] (Windows) or [⌘]-[V] (MacOS) into this page

  3. Then click the "Use on iPhone" button that you'll see.