How to do inputs in Python
Question: I have to open file in Python, what looks like this:

    
    
    Rapla;Tartu;157
    Tallinn;Narva;211
    Valga;Haapsalu;249
    Viljandi;Paide;71
    Tartu;Rakvere;123
    Rapla;Narva;259
    Paide;Narva;196
    Paide;Tallinn;92
    

I want to get program to work like this with an example:

    
    
    Please enter starting point: Rapla
    Now please enter ending point: Tartu
    Distance between Rapla and Tartu is 157 km.
    

I managed to make a list in python, but I'm fairly new in Python and I dont
know, how to do inputs, so I could get a accetable output.

What I managed to do so far:

    
    
    town1 = []
    town2 = []
    distance = []
    
    f = open('town.csv')
    for list in f:
        x = list.split(';')
        town1.append(x[0])
        town2.append(x[1])
        distance.append(x[2])
    
    f.close()
    
    n = len(town1)
    for i in range(n):
        print('Starting point is: ' + town1[i])
        print('Ending point is:  ' + town2[i])
        print('Distance between', town1[i], 'and', town2[i], 'is', distance[i], 'km.')
    

Program just prints every single town starting point and ending point with
distance, but I want to make program to ask me starting point and ending
point.


Answer: 
    # assumes Python 2.x
    from collections import defaultdict
    import csv
    
    def load_distances(fname):
        distance = defaultdict(dict)
        with open(fname, "rb") as inf:
            incsv = csv.reader(inf, delimiter=";")
            for town_a, town_b, dist in incsv:
                distance[town_a][town_b] = int(dist)
        return distance
    
    def main():
        distance = load_distances("town.csv")
    
        town_a = raw_input("Please enter starting point: ")
        town_b = raw_input("Now please enter ending point: ")
        if town_a not in distance or town_b not in distance[town_a]:
            print("I don't know how to get from {} to {}".format(town_a, town_b))
        else:
            print("Distance between {} and {} is {} km.".format(town_a, town_b, distance[town_a][town_b]))
    
    if __name__=="__main__":
        main()
    

If you are using Python 3, you need to replace `raw_input()` with `input()`
and `open(fname, "rb")` with `open(fname, newline="")`.

`defaultdict` is a special type of `dict`; if you ask it for an object it
doesn't have, it returns a new default object instead of causing an error.

