Skip to content

Exercise 6: While loop

Alternative course

While loop

A while loop repeats code until the condition is met. Unlike for loops, the number of iterations in it may be unknown.  A while loop always consists of a condition and a block of code.

A while loop ends if and only if the condition is true, in contrast to a for loop that always has a finite countable number of steps. For illustration: If you create a program that waits for network connectivity, you could use a while loop.

Type this code:

#!/usr/bin/python
 
x = 3                              
while x < 10:
    print(x)
    x = x + 1

Executes the code below until the condition x < 10 is met.   Unlike a for loop, the iterator i is increased in the loop.

You should see

python-while-loop

Study drill

Try the exercises below

1. Make a program that multiples itself by 2 until the number is large than 128
2. Ask a number until its the correct one

After completing these continue with the next exercise.

Answers

Exercise 5: For Loops
Exercise 7: Functions
Published inUncategorized

One Comment

  1. Anonymous Anonymous

    num = int(input(‘Enter number: ‘))
    ValueError: invalid literal for int() with base 10: ”
    >>> Traceback (most recent call last):
    File “”, line 1, in

Leave a Reply