User Input and While Loops in Python

Below are some of the examples by which we can use while loops for user input in Python:

Taking User Input Using While Loop

In this example, the code initializes an empty list, prompts the user to enter numbers iteratively until the user inputs ‘done,’ converts each input to an integer, appends it to the list, and finally prints the resulting list of numbers.

Python3




# Initializing an empty list to store numbers
number_list = []
 
# Prompting the user to enter numbers
while True:
    num = input("Enter a number (or 'done' to finish): ")
    if num == 'done':
        break
    number_list.append(int(num))
 
# Printing the list of numbers
print("List of numbers:", number_list)


Output:

Enter a number (or 'done' to finish): 1
Enter a number (or 'done' to finish): 2
Enter a number (or 'done' to finish): 3
Enter a number (or 'done' to finish): 4
Enter a number (or 'done' to finish): done
List of numbers: [1, 2, 3, 4]


Get User Input in Loop using Python

In Python, for and while loops are used to iterate over a sequence of elements or to execute a block of code repeatedly. When it comes to user input, these loops can be used to prompt the user for input and process the input based on certain conditions. In this article, we will explore how to use for and while loops for user input in Python.

Similar Reads

User Input and For Loops in Python

Below are some of the examples by which we can understand how we can use for loop for user input in Python:...

User Input and While Loops in Python

...