In Python, while loops allow you to repeat things forever, or up until a certain point. Here’s an example:
keep_going = True
while (keep_going == True):
print("Hello world!")
This will print “Hello world!” indefinitely. The keep_going
value is set to True
, and the while
loop checks continuously check that the keep_going
value is equal to True
. As long as it is, it will keep repeating.
Let’s try modifying the code so that it only repeats 9 times. Let’s try:
count = 1
while (count < 9):
print("Hello world!")
count = count + 1
The count
value is set at 1 at the start. The while
loop checks if count
is less than 9, which it is. It then prints “Hello world!” and adds 1 to count
. It keeps repeating, until Python reaches the while
loop and realised count
is no longer less than 9, so it skips and exits.
Now, let’s try adding user input into the code. An example is a counting program. Python asks the user what they want to count to, they enter it, and Python counts to it.
count_to = int(input("Count to: "))
count_to = count_to + 1
count = 1
while (count < count_to):
print(count)
count = count + 1
This program asks the user what they want to count to, then it adds 1 to it as it will count up to a number 1 less than it, which will be the original number the user entered. This is stored in count_to
. It then sets count
to 1, and then the while
loop checks if count
is less than count_to
, and prints out count
and adds one. It should count up all the way to the number specified in count_to
, and then stop once it reaches the number.
You can experiment further with while loops, these are just the basics and while loops can be found in all sorts of Python programs. Enjoy!