How to use Python While with Assignment[4 Examples]

In this Python tutorial, you will learn “How to use Python While with Assignment“, with multiple examples and different approaches.

While working on a project, I was assigned to optimise the code. In the research, I found that we can assign variables within a while loop in Python. This helps to reduce some lines of code.

Generally, we use the ” = “ assignment operator to assign the variable in Python. But we will also try the walrus operator “:= “ to assign the variable within the while loop in Python.

Let’s understand every example one by one with some practical scenarios.

Python while loop with the assignment using the “=” operator

First, we will use the “=” operator, an assignment operator in Python. This operator is used to assign a value to a variable, and we will assign a variable inside the loop in Python using the ” = “ operator.

Let’s see how Python, while with assignment, works.

while True:
    line = "Hello"
    i = 0 
    while i<len(line):
        print(line[i],'-',ord(line[i]))
        i+=1
    break
Python while loop with the assignment

In the above code, we always initialize the while loop with the true condition.
while True:” means it will iterate infinite times and then assign the variable ‘line = “Hello” inside the while loop with one default string value.

Then assigned i = 0, and again initialize nested while loop “print(line[i],’-‘,ord(line[i]))” to target every character one by one and print its ascii value using ord() method in Python

READ:  Python check if a variable is an integer

Python assign variables in the while condition using the walrus operator

We can also use the walrus operator ” := “, a new assignment expression operator introduced in the 3.8 version of Python. It can create a new variable inside the expression even if that variable does not exist previously.

Syntax

var_name := value 

Let’s see how we can use it in a while loop:

capitals = ["Denver", "Tallahassee", "Boise", "Austin", "Olympia", "Madison"]

print("Logging state capitals:")

while (current_capital := capitals.pop(0)) != "Austin":
    print(current_capital)

print("Reached Austin! Time to stop.")
Python assign variable in while condition using walrus operator

In the above code, we have a list named capitals. Then we initialize a while loop and create current_capital, giving a value as capitals.pop(0), which means removing the first element in every iteration using the walrus operator like this:‘current_capital:= capitals.pop(0)) != “Austin” .

When it iterates at “Austin”, the condition will be False because “Austin” != “Austin” will return false, and the loop will stop iterating.

Python while with assignment by taking user input

Here, we will see how Python While with Assignment will work if we take user input with a while loop using the walrus operator in Python.

while number:=int(input("Enter the number: ")):
    if number % 2 == 0:
        print(number, "is even number\n")
    else:
        print(number, "is odd number\n")
python while assignment with walrus operator in python

In the above code, we are initializing a variable with a while loop and taking user input for an integer. Then, it will check whether the number is even or odd using the % operator.

Look at how it asks the user to enter the number repeatedly because we are not giving a break statement anywhere so it will work infinite times.

READ:  PyTorch Early Stopping + Examples

Python While with Assignment by calling the function

Now, we will see how to assign a variable inside a while loop in Python by calling the function name. We will create a user-defined function so you will understand how it is working.

How Python While with Assignment can be created by calling the user-defined function.

def get_ascii_value(string):
    dict = {}
    for i in string:
        dict.update({i: ord(i)})
    return dict


while True:
    user_input = input("Enter any word : ")
    result = get_ascii_value(user_input)
    print(result)
    break
Python While with Assignment by calling the function

In the above code, we create a function called get_ascii_value(). This function takes a string as a parameter and returns the ASCII value of each character.

Then, we initialize a while loop, taking user_input as a string. The result variable calls a function and returns a character and ASCII value in a dictionary datatype.

Conclusion

In this Python article, you learned how to use Python while with assignment with different approaches and examples. We tried to cover all types of scenarios, such as creating user-defined functions, assigning within a while loop, taking user input, etc.

You may like to read: