Support Online
Skip to main content

Python While Loop

Introduction

Computer programs are great for automating and repeating tasks without us having to do them over and over again.
One way to repeat similar operations is to use loops.

In this lesson, we will discuss Python's while loop.

Logic of While Loop

The while loop allows code to be executed repeatedly based on a given Boolean (true/false) condition.
That is, the code inside the while block continues to run as long as the condition is True.

You can think of a while loop as a repeating if statement.

  • If the condition if is met, the code runs once and continues.
  • When the condition while is met, the code runs and then goes back to the beginning and checks the condition. This loop continues until the condition becomes False.

Difference from cycle for:

  • The for cycle usually repeats a certain number of times.
  • In the while loop, there is conditional repetition, it is not necessary to know in advance how many times it will run.

Prerequisites

Python 3 must be installed on your computer or server and a programming environment must be set up.
If you do not have such an environment yet, you can install Python and prepare the necessary environment by following the installation and environment preparation guides appropriate to the operating system (Ubuntu, CentOS, Debian, etc.).

While Loop

In Python, the while loop is written as follows:

while koşul:
# koşul True olduğu sürece çalışacak kodlar

As long as the condition is True, the operations inside the loop are executed repeatedly.
When the condition is now False, the loop ends.

Let's write a small block of code and use a while loop.
In this program, we will ask the user to enter a password.
As the loop continues there will be two possibilities:

  • If the password is correct, the while loop will terminate.
  • If the password is incorrect, the while loop will continue running.

We will create a file named password.py in a text editor.
As a first step, let's initialize the variable password with an empty string:

password = " "

The empty string ("") value will be used to store the input received from the user in the while loop.

Now, let's write the while loop with the condition:

password = ""

while password != "python123":

Here is the comparison with the variable password after the expression while.
Our goal is to check whether the value entered by the user is the same as the string we specified (for example "password").
You can choose the string you want.

  • If the user enters the string "password", the loop will stop and the program will continue with the codes outside the loop.
  • If the user enters something different, the condition will continue to be met and the loop will run again.

Now let's add the operation to the while loop:

password = ""

while password != "python123":
password = input("Şifreyi girin: ")
print("Yanlış şifre, tekrar deneyin...")

Inside the while loop, the program executes an print statement to prompt the user for a password.
Then, the value entered with the input() function is assigned to the password variable.

The program checks the variable password each time. If the variable is equal to "password" (the correct password we chose), the loop ends.

In this case, let's add one more line that will run after the loop ends:

password = ""

while password != "python123":
password = input("Şifreyi girin: ")
print("Yanlış şifre, tekrar deneyin...")

print("Şifre doğru! Giriş yapıldı ✅")

The last print() statement is located outside the while loop.
So when the user enters the correct password (if we set it as "password"), the loop ends and this last message is printed on the screen.

But if the user never enters the correct password, the program will constantly loop, resulting in an infinite loop.

To exit the endless loop, you can use the CTRL + C key combination on the command line.

Now save and run the program:

python password.py

When you run the program, it will ask you for a password.
You can test the result by trying different inputs.

Output
Şifreyi girin: test
Yanlış şifre, tekrar deneyin...
Şifreyi girin: 12345
Yanlış şifre, tekrar deneyin...
Şifreyi girin: python123
Şifre doğru! Giriş yapıldı ✅

Remember: Strings are case sensitive.
So "Python123" and "python123" are not considered the same.

Sample Program with While Loop

Now that we understand the basic logic of the while loop, let's make a command line guessing game using it.
The while loop will be used effectively in this program.

To best understand how the program works, I also recommend that you review conditional statements (if, else) and data type conversion.

First, we will create a file named tahmin.py in a text editor of our choice.
Since we want the computer to generate random numbers for the user to guess, we will add the random module with the expression import.

If you haven't worked with this package before, you can find more information about random number generation in the Python documentation.

import random

In the next step, we will assign a random integer to the variable number.
We will keep the range between 1 and 20 so that the game is not too difficult.

import random

number = random.randint(1, 20)

At this point we can now start setting up the while loop.
First we will define a variable and then create the loop.

import random

number = random.randint(1, 25)

tahmin_hakki = 0

while tahmin_hakki < 5:
print("1 ile 25 arasında bir sayı tahmin et:")

tahmin = input()
tahmin = int(tahmin)

tahmin_hakki = tahmin_hakki + 1

if tahmin == number:
break

We initially defined the variable tahmin_hakki as 0.
We increase this value by 1 every time the loop runs. Thus, we prevented the formation of an infinite loop.

Since we wrote tahmin_hakki < 5 in the condition while, the user has 5 guesses in total.
After the fifth guess, the loop ends and the user returns to the command line.

As it stands now, if the user enters anything other than an integer, the program will throw an error.

Inside the loop, we show a message to the user with print() to enter a number.
Then we assign the value we get with the input() function to the tahmin variable.
Since this value is of string type by default, we convert it to integer with int().

Before the loop ends, we increment the variable tahmin_hakki by 1, so the loop can run at most 5 times.

Then we check if the user's guess is equal to the number produced by the computer with a condition if.
If equal, we exit the loop with the expression break.

The program is now fully functional. You can use the following command to run it:

python tahmin.py

The program is now working, but there is something missing:
The user does not know whether he guessed correctly or not. So even if he guesses 5 times, he doesn't see whether he got it right or not.

The output of the program in its current form looks like this:

Output

1 ile 20 arasında bir sayı tahmin et:
10
1 ile 20 arasında bir sayı tahmin et:
7
1 ile 20 arasında bir sayı tahmin et:
14
1 ile 20 arasında bir sayı tahmin et:
5
1 ile 20 arasında bir sayı tahmin et:
18

Now let's add some conditional statements after the loop so the user can see if they guessed correctly.
These lines will be added to the very end of the current file:

if tahmin == sayi:
print("Tebrikler! Sayıyı doğru bildiniz 🎉")
else:
print(f"Üzgünüm, tahmin hakkınız bitti. Doğru sayı &#123;sayi&#125; idi.")

Now the program tells you whether the user guessed right or wrong, but this information is only revealed when the guess runs out.

Let's add a few conditional statements to the while loop to guide the user.
These will indicate whether the entered number is too small or too large.
In this way, the user will be able to get closer to the correct prediction more easily.

In our code, we can add the following before the if tahmin == sayi: line:

while tahmin_hakki < 5:
print("1 ile 25 arasında bir sayı tahmin et:")

tahmin = int(input())
tahmin_hakki += 1

if tahmin < sayi:
print("Tahminin çok küçük 📉")
elif tahmin > sayi:
print("Tahminin çok büyük 📈")

if tahmin == sayi:
break

When we run the program again with the python tahmin.py command, we can see that the user is now given more guidance in their predictions.
For example, if the randomly generated number is 12 and the user enters 18, the program will say the guess is too high. So the user will be able to adjust his next prediction accordingly.

Of course, this code can be improved further.
For example, error handling can be added to avoid getting an error if the user enters something other than an integer**.

But this simple example is enough to show how a while loop works in a short command line program.

Result

In this lesson, we learned how while loops work in Python and how to set them up.
While loops continue executing the block of code over and over again as long as the condition is True.
When the condition is False, the loop ends.