WSQ06 – ‘While’ Loops (Python3)

--Originally published at Elu's Blog

For this assignment these were my instructions:

Create a program that asks the user for a non-negative integer (let’s call that number n) and display for them the value of n! (n factorial).

After showing them the answer, ask them if they would like to try another number (with a simple y/n response) and either ask again (for y) or quit the program and wish them a nice day (if they answered n).

This is what I came up with:

Captura de pantalla 2017-02-14 a la(s) 12.06.28.png

Captura de pantalla 2017-02-14 a la(s) 12.06.54.png

A ‘while’ loop is very similar to a ‘for’ loop in a way that it repeats a certain task until you tell it to stop. In this case, I made two loops. The first one takes the variable ‘counter’, and the variable ‘n’ and it subtracts 1 to it. The instructions inside that loop will repeat until the argument ‘counter < n-1’ stops being true. To stop this loop for being an infinite loop, every time the loop runs, it will add 1 to the variable counter.

The second loop has the argument ‘True’, so in theory it will run forever. The thing is that in line 14 I added the word ‘break’, what this does is that it stops the loop. So whenever the variable ‘follow’ is assigned the value ‘n’, the loop will stop.

Alternative Explanation

“Python 3 programming tutorial: While Loop” by sentdex