Building an Array of Strings: 10 User Inputs Made Easy
Have you ever needed to collect a list of words from a user and store them for later use? This is a common task in programming, and arrays are the perfect tool for the job. In this article, we'll explore how to create an array of strings and populate it with 10 user inputs.
Scenario: Imagine you're building a simple application that asks users for their favorite fruits. You want to store their responses in an array so you can later display them or perform other actions with the data.
Code Example (Python):
fruits = [] # Create an empty array to store fruits
for i in range(10): # Loop 10 times
fruit = input(f"Enter fruit {i+1}: ") # Get user input
fruits.append(fruit) # Add the input to the array
# Print the array
print("Your favorite fruits are:", fruits)
Breaking it down:
fruits = []
: We initialize an empty list namedfruits
. In Python, lists are used as arrays to store collections of data.for i in range(10)
: This loop runs 10 times, allowing us to collect 10 inputs.fruit = input(f"Enter fruit {i+1}: ")
: Inside the loop, we prompt the user to enter a fruit name using theinput()
function. Thef
before the string makes it a formatted string, which allows us to dynamically insert the loop counter (i+1
) into the prompt message.fruits.append(fruit)
: After receiving the user input, we use theappend()
method to add thefruit
to the end of ourfruits
array.print("Your favorite fruits are:", fruits)
: Finally, we display the collected fruits using theprint()
function.
Key Insights:
- Arrays are versatile: You can use arrays to store various data types like numbers, strings, or even other arrays.
- Loops are essential: Loops allow us to automate repetitive tasks like collecting multiple inputs from the user.
- Flexibility: You can easily adapt this code to collect a different number of inputs by simply changing the range in the
for
loop.
Example:
Let's say the user inputs the following fruits:
- Apple
- Banana
- Orange
- Grape
- Mango
- Strawberry
- Kiwi
- Watermelon
- Pineapple
- Peach
The output will be:
Your favorite fruits are: ['Apple', 'Banana', 'Orange', 'Grape', 'Mango', 'Strawberry', 'Kiwi', 'Watermelon', 'Pineapple', 'Peach']
Additional Resources:
- Python documentation: https://docs.python.org/3/tutorial/datastructures.html
- W3Schools - Python Arrays: https://www.w3schools.com/python/python_arrays.asp
This example shows how simple it is to collect user input and store it in an array. With this foundation, you can explore more advanced data structures and algorithms in your programming journey.