# while loop - count up

## Introduction

{% embed url="<https://docs.google.com/presentation/d/1AjjEWWYHkzchI36kPRuC9pFnBSihVYZhATW42ZItpic/edit?usp=sharing>" %}

## Introductory Problem

Ask the user, "what is your favorite programming language".  If they enter Python, print, "Python is my favorite too!" 5 times. &#x20;

```python
fav = input("What is your favorite programming language? ")
if fav == "Python":
    print("Python is my favorite too!")
    print("Python is my favorite too!")
    print("Python is my favorite too!")
    print("Python is my favorite too!")
    print("Python is my favorite too!")
```

## while loop

A while loop executes an indented block of code, or instructions, repeatedly while a condition is true.  Previously, you learned about if statements that executed an indented block of code while a condition was true.  You can think of a while loop like an if condition but the indented block of code executes more than once.  Hence, a loop.

![](https://729613953-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LVVKHMnpflHwghmbdgi%2F-Ld0paZ4YUVk-YNDC9XV%2F-Ld0qJWMmEcT1pBE2wGX%2FScreen%20Shot%202019-04-21%20at%205.41.41%20PM.png?alt=media\&token=d8ee2a4c-7915-4e29-a957-29d64166677e)

## Variable Roles

Recall that a stepper variable iterates, or loops, a specific number of time&#x73;**.**

![](https://729613953-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LVVKHMnpflHwghmbdgi%2F-Ld0paZ4YUVk-YNDC9XV%2F-Ld0qcvH-d0fjritjUCO%2FScreen%20Shot%202019-04-21%20at%205.43.11%20PM.png?alt=media\&token=448c64e9-2a8b-4126-a6f3-ed4bcff0c174)

{% hint style="info" %}
Programmers us&#x65;**`x`**&#x6F;&#x72;**`i`**&#x61;s a stepper variable.
{% endhint %}

## Common Mistakes

{% hint style="danger" %}
**Infinite Loops**

An infinite loop is a loop that runs forever.  It can only be stopped by killing the program. If there are output statements in the loop, these lines will flash by on the screen.  To kill the program, press Ctrl+C in the Terminal. Or click on CS50 IDE -> Restart your Workspace.
{% endhint %}

{% hint style="warning" %}
**Never Starts**

Because the first action of a while loop is to evaluate the Boolean expression, if that expression is False, the indented block of code will never be executed.
{% endhint %}

{% hint style="warning" %}
**Off by one**

Another common error you may encounter is being off by one.  Change the initial stepper value or the condition to correct this.
{% endhint %}

## while loop Examples

### Example 1

Again, ask the user, "what is your favorite programming language".   This time, print "Python is my favorite too!" 5 times using a while loop.

{% hint style="info" %}
Python programmers typically start counting at 0.  This will become more clear when we introduce lists. &#x20;
{% endhint %}

Steps:

* Initialize the stepper variable x to 0.
* Combine while with a condition that will execute 5 times.
* Print "Python is my favorite language!"&#x20;
* Increment the stepper variable.

{% tabs %}
{% tab title="example1.py" %}

```python
x = 0
while x < 5:
    print("Python is my favorite language!")
    x = x + 1
```

{% endtab %}
{% endtabs %}

### Example 2

Using a while loop, print numbers from 1 to 5. &#x20;

{% hint style="warning" %}
What value can you initialize the stepper variable to?
{% endhint %}

{% tabs %}
{% tab title="example2.py" %}

```python
x = 1
while x <= 5:
    print(x)
    x = x + 1
```

{% endtab %}
{% endtabs %}

or

{% tabs %}
{% tab title="example2.py" %}

```python
x = 1
while x < 6:
    print(x)
    x = x + 1
```

{% endtab %}
{% endtabs %}

{% hint style="danger" %}
The placement of x = x + 1 in the while loop matters. &#x20;

If you print x after x = x + 1, the value will be different than if you printed it before.
{% endhint %}

### Example 3

Using a while loop, print odd numbers from 1 to 99.&#x20;

{% hint style="warning" %}
What value can you initialize the stepper variable to? What can you increment the variable by?
{% endhint %}

{% tabs %}
{% tab title="example3.py" %}

```python
x = 1
while x < 100:
    print(x)
    x = x + 2
```

{% endtab %}
{% endtabs %}

or

{% tabs %}
{% tab title="example3.py" %}

```python
x = 1
while x <= 99:
    print(x)
    x = x + 2
```

{% endtab %}
{% endtabs %}

### Example 4

Print the sum of the first 10 numbers.  For example: 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10

Create a variable called sum and initialize it to 0.

* What value can you initialize the stepper variable to?
* How can you use x to calculate the sum?

![](https://729613953-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LVVKHMnpflHwghmbdgi%2F-Ld0vAfqKJXmnq48xX8z%2F-Ld0vX4W2sLAt64Wm09v%2FScreen%20Shot%202019-04-21%20at%206.04.35%20PM.png?alt=media\&token=d67eb4ce-4f95-4a26-a692-020ab9fca2bf)

{% tabs %}
{% tab title="example4.py" %}

```python
x = 1
sum = 0
while x <= 10:
    sum = sum + x
    x = x + 1
print("Sum:", sum)
```

{% endtab %}
{% endtabs %}

### Example 5

Ask the user for a number 3 times using a while loop.  Print the sum of the 3 numbers.

{% tabs %}
{% tab title="example5.py" %}

```python
x = 0
sum = 0
while x < 3:
    num = int(input("Number: "))
    sum = sum + num
    x = x + 1
print("Sum:", sum)
```

{% endtab %}
{% endtabs %}

## Conclusion

* In your own words, what is a while loop?&#x20;
* Give a simple example of something you do over and over again everyday.
* Explain the role of the stepper variable when the while loop counts up.
* How is using a while loop more efficient than the solution to the introductory problem?
