Stanley Wilkins
Stanley Wilkins

Reputation: 125

How to index a user input list in Python 2.x?

want user to input the names of the cities he has been, and I want the script to store each of them individually.

I made this part working all right.

Then, for the sake of the project, the script should ask where each city is located at. But now, it works like this:

input:

Paris, Hamburg, London...

output:

Where is Paris located?
Where is Hamburg located?
Where is London located?
...

Code:

user_cities = raw_input("What cities have you visited so far?").split(", ")
if len(user_cities) > 0:
    index = 0
    for city in user_cities:
        print "Where is "+str(city)+" located?", 
        index+=1

There one thing missing from the expected output:

How do we index and/or iterate a user input list? I tried every piece of code in similar situations but none of them worked for me.

We don't know how many cities he has been to. He can write just 1 city or 20 cities. I can hardcode, writing dozens of unnecessary lines, but I know there is a right way to do it. I can't remember how.

In the expected result, I want it to take turns to ask user where the city is located one by one.

input:

Paris, Hamburg, London...

output 1:

Where is Paris located?

input 1:

France

output 2:

Where is Hamburg located?

input 2:

Germany

etc.

Upvotes: 1

Views: 1270

Answers (1)

Adam Smith
Adam Smith

Reputation: 54213

You could use an infinite loop with some sort of sentinel for the user to indicate "Okay no more." How about:

cities = []
while True:
    city = raw_input("Enter a city you've been to (or press enter to exit): ")
    if city == '':  # no input -- this is your sentinel
        break  # leave the loop
    else:
        cities.append(city)

Then you can prompt for the countries if you wanted to do that separately for some reason.

countries = []
for idx, city in enumerate(cities):
    country = raw_input("Where is " + city + " located? ")
    countries.append(country)
    # why did you need the index? enumerate is the way to go now....

Maybe you need a dictionary then?

cities_to_countries = dict(zip(cities, countries))

Upvotes: 2

Related Questions