# While Loop With Examples and Exercises

by Sam

**While Loop** is similar with ForLoop as they are used in repeating statements. However, While Loop does not run in n times. It only repeats until the condition becomes false.

Consider some of the examples below.

#### Example #1.

ctr = 0

while ctr <s; 5:

print(ctr , end="")

ctr += 1

**Output**

`01234`

#### Example #2.

count = 0

while True:

print(count, end="")

count += 1

if count > 5:

break

**Output**

`012345`

On example #2, the value of `count`

variable will be printed out until it reaches 5. It will stop at 6 since it satisfies the condition `count > 5`

.

#### Example #3.

Let’s loop the number from 1 to 10 and display the **Odd and Even numbers**.

tmp = 1

even = ""

odd = ""

while tmp <s;= 10:

if tmp % 2 == 0:

even += str(tmp) + " "

else:

odd += str(tmp) + " "tmp += 1

`print("Odd numbers are: " , odd)`

print("Even numbers are: " , even)

**Output**

Odd numbers are: 1 3 5 7 9

Even numbers are: 2 4 6 8 10

On this example, we need to use **str** function in order to convert integer to string.

### Exercises

Using while loop,

1. Create a program that will display the numbers from 1 to 50 which is divisible by 5.

Expected Output: 5 10 15 20 25 30 35 40 45 50

2. Display the numbers from 1 to 10 except 6.

Expected Output: 1 2 3 4 5 7 8 9 10

If you have solved the problems above, drop your solution on the comment section below.