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
# Prompting the user for input user_input = int ( input ()) # Splitting the input string into individual numbers number_list = [] for i in range (user_input): number_list.append( int ( input ())) # Printing the list of numbers 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
# the user to input a series of numbers separated by spaces user_input = input () # Split the input string into individual numbers and convert each to an integer numbers = [ int (num) for num in user_input.split()] # Initialize an empty list to store even numbers even_numbers = [] # Iterate through the numbers using a for loop for num in numbers: if num % 2 = = 0 : even_numbers.append(num) # Print the list of even numbers 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]
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.