How To Get Input From User In Python Using For Loop

In this tutorial, you will learn how you can get input from a user using a For Loop in Python. Working with user input is crucial when creating applications that require interaction with the user. By the end of this tutorial, you should have a good understanding of using For Loop to collect input from users in Python.

Step 1: Understanding the basics of Python Input Function and For Loop

The input() function in Python allows you to get input from users. It reads a line from the input and returns it as a string. Here is a simple example of using the input() function:

In this example, we asked the user to input their name, and the program displays a greeting message that includes the user’s name.

To perform iterative tasks, you can use a For Loop in Python. A For Loop allows you to iterate over a sequence (such as a list or range) and execute a block of code for each item in the sequence. Here’s an example of a For Loop iterating over a range of numbers:

This code will print the numbers from 0 to 4, as the range() function generates a sequence of numbers from 0 to n-1.

Step 2: Combine Input Function with For Loop

Now that you are familiar with the input() function and For Loop, let’s combine them to get input from a user using a For Loop.

First, you need to determine how many times you want to get input from the user. For this example, let’s say we want to get the names of 5 students.

To achieve this, you can follow these steps:

  1. Create a for i in range(5): loop.
  2. Inside the loop, use the input() function to get the names of the students and store them in a variable.
  3. Append each name to a list.

Here’s the code snippet for the above steps:

Step 3: Display the List of User Inputs

Finally, you can display the list of user inputs after the For Loop has executed. Use the print() function to display the list.

Here’s the complete code for getting the input from the user using a For Loop:

Running the code will ask the user to input the names of 5 students and displays the list of names at the end.

Output:

Enter the name of student 1: John
Enter the name of student 2: Jane
Enter the name of student 3: Mike
Enter the name of student 4: Emma
Enter the name of student 5: Tom

The names of the students are:
['John', 'Jane', 'Mike', 'Emma', 'Tom']

Conclusion

In this tutorial, you have learned how to get input from a user using a For Loop in Python. As a recap, you should now understand how to combine the input() function with a For Loop to collect inputs from users and store them in a list for later use. You can use this technique to collect user inputs not only for names but also for any other similar cases where you need to get multiple inputs from users.