Taking input values in a program is an essential task for getting dynamic data from the user. In Python, there are various ways to take inputs from users.
One of the most common methods is to take space-separated input. In this tutorial, we will learn how to take space-separated input in Python using for loop.
Steps:
Step 1: Ask the User for Input
The first step is to ask the user for input. You can do this by using the input() function in Python. This function takes a parameter, a string you want to display to the user.
1 |
num = input("Enter space separated values: ") |
Step 2: Split the Input String
The next step is to split the input string into individual values. In Python, you can split a string into a list of values using the split() function. By default, the split function splits a string at spaces.
1 |
num_list = num.split() |
Step 3: Convert the List to Integers
After we split the string into individual values, we need to convert them to integers so that we can perform operations on them.
1 2 |
for i in range(len(num_list)): num_list[i] = int(num_list[i]) |
Step 4: Use the Input Values
Now we can use these input values in our program as required. Here, we are just printing the input values.
1 2 |
for i in range(len(num_list)): print(num_list[i]) |
Conclusion
In this tutorial, we learned how to take space-separated input using for loop in Python. It’s a simple way to get input from the user and use it in your program.
Full Code:
1 2 3 4 5 6 7 8 |
num = input("Enter space separated values: ") num_list = num.split() for i in range(len(num_list)): num_list[i] = int(num_list[i]) for i in range(len(num_list)): print(num_list[i]) |