Get User Input in Loop using Python
Last Updated :
19 Feb, 2024
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.
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:
Example 1: Taking User Input Using for Loop
In this example, the code prompts the user for an integer input, then iteratively takes that many additional integer inputs to form a list, printing the resulting list of numbers.
Python3
user_input = int ( input ())
number_list = []
for i in range (user_input):
number_list.append( int ( input ()))
print ( "List of numbers:" , number_list)
|
Output:
5
1
2
3
4
5
List of numbers: [1, 2, 3, 4, 5]
Example 2: Printing Even Numbers Using for Loop and User Input
In this example, the code takes a series of numbers separated by spaces as user input, converts them to integers, identifies and extracts the even numbers from the input, and finally prints the list of those even numbers.
Python3
user_input = input ()
numbers = [ int (num) for num in user_input.split()]
even_numbers = []
for num in numbers:
if num % 2 = = 0 :
even_numbers.append(num)
print ( "Even numbers from the input:" , even_numbers)
|
Output:
129 12 23 24 26 28 233 333
Even numbers from the input: [12, 24, 26, 28]
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
number_list = []
while True :
num = input ( "Enter a number (or 'done' to finish): " )
if num = = 'done' :
break
number_list.append( int (num))
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]
Share your thoughts in the comments
Please Login to comment...