Clair Davis
Clair Davis

Reputation: 37

Execute a function for a user defined number of times python

I have two functions, one that asks the user for three pieces of input, and another that asks the user to enter a number. I would like to make a for loop, so that the first function runs for the number of times entered by the user in the second function.

Here's my code:

def get_user_input():
    name = raw_input("What is the name?")
    bas_lat = float(input("What is the latitude?"))
    bas_long = float(input("What is the longitude?"))
    print name, "has a latitude of ", bas_lat, 
    print "degrees and a longitude of ", bas_long

def get_number_stations():
    number_of_stations = float(input("How many stations are there?"))
    print "There are ", number_of_stations, 
    print "stations to have their distance from"
    print "from the headquarters determined"
    return number_of_stations

main()

Upvotes: 1

Views: 2148

Answers (3)

Padraic Cunningham
Padraic Cunningham

Reputation: 180391

You can return the number and pass it to the function as a parameter, doing the looping in the function:

def get_user_input(t):
    for _ in xrange(t):
        name = raw_input("What is the name?")
        # raw_input not input
        bas_lat = float(raw_input("What is the latitude?"))
        bas_long = float(raw_input("What is the longitude?"))
        print "{} has a latitude and longitude of ({},{})".format(name, bas_lat, bas_long)


def get_number_stations():
    # get int to pass to range
    number_of_stations = int(raw_input("How many stations are there?"))
    print "There are {} stations to have their distance " \
          "from from the headquarters determined.".format(number_of_stations,) 
    return number_of_stations


# get number of stations/times to loop returned from get_number_stations
t = get_number_stations()
# pass t to get_user_input
get_user_input(t)

You need an int for range, you should also cast raw_input when you want a float,int etc.. don't use input.

If you want to store the data you can use a dict, using the name as the key and tuples as the values which store the coordinates:

def get_user_input(t):
    data = {}
    for _ in xrange(t):
        name = raw_input("What is the name?")
        bas_lat = float(raw_input("What is the latitude?"))
        bas_long = float(raw_input("What is the longitude?"))
        print "{} has a latitude and longitude of ({},{})".format(name, bas_lat, bas_long)
        data[name] = (bas_lat,bas_long)
    return data

You also may want a try/except to catch invalid input that cannot be cast to a float:

def get_user_input(t):
    data = {}
    for _ in xrange(t):
        name = raw_input("What is the name?")
        while True:
            try:
                bas_lat = float(raw_input("What is the latitude?"))
                bas_long = float(raw_input("What is the longitude?"))
                print "{} has a latitude and longitude of {},{}".format(bas_lat, bas_long)g
                # if all data was valid break
                break
            except ValueError:
                # else we got data that could not be cast
                # so print message and aska again
                print("Invald input")
                continue
        data[name] = (bas_lat,bas_long)
    return data

It might be a little nicer to make the validation a functionvalidate that takes a string as a parameter and a type _type which can validate the lat and long inputs and the number of stations:

def validate(s ,_type):
    while True:
        try:
            return _type(raw_input(s))
        except ValueError:
            print("Invalid input")


def get_user_input(t):
    data = {}
    for _ in xrange(t):
        name = raw_input("What is the name? ")
        bas_lat = validate("What is the latitude? ", float)
        bas_long = validate("What is the longitude? ", float)
        print "{} has a latitude and longitude of ({},{})".format(name, bas_lat, bas_long)
        data[name] = (bas_lat, bas_long)
    return data


def get_number_stations():
    number_of_stations = validate("How many stations are there? ",int)
    print "There are {} stations to have their distance " \
          "from from the headquarters determined.".format(number_of_stations)
    return number_of_stations



t = get_number_stations()

get_user_input(t)

You could repeatedly call get_user_input in a loop but that would be a bit pointless as you are not passing any new information to get_user_input.

Output:

How many stations are there?s
Invalid input
How many stations are there?2
There are 2 stations to have their distance from from the headquarters determined.
What is the name? foo
What is the latitude? 0.123
What is the longitude? 1.12s
Invalid input
What is the longitude? 1.345
foo has a latitude and longitude of (0.123,1.345)
What is the name? bar
What is the latitude? 1.234
What is the longitude? 2.345
bar has a latitude and longitude of (1.234,2.345)

Upvotes: 0

user
user

Reputation: 5696

num = get_number_stations()

for _ in xrange(int(num)):
    get_user_input()

xrange() needs an int as argument. You can use the code above, or make get_number_stations() return an int (which would make more sense, since the number of stations should be an integer anyway).

Upvotes: 2

Will
Will

Reputation: 24689

Try this:

def get_user_input():
    name = raw_input("What is the name? ")
    bas_lat = float(input("What is the latitude? "))
    bas_long = float(input("What is the longitude? "))

    print "{} has a latitude of {} degrees and a longitude of {}.\n".format(
        name, bas_lat, bas_long
    )

    return name, bas_lat, bas_long


def get_number_stations():
    number_of_stations = int(input("How many stations are there? "))
    print "There are {} stations to have their distance from the headquarters determined.\n".format(
        number_of_stations
    )

    return number_of_stations

def main():
    stations = []
    number_of_stations = get_number_stations()

    for station_number in xrange(0, number_of_stations):
        (name, bas_lat, bas_long) = get_user_input()
        stations.append((name, bas_lat, bas_long))

    print "\nHere are the stations:"
    for station in stations:
        print "\t{}\t\t{}, {}".format(station[0], station[1], station[2])


main()

My results:

How many stations are there? 2
There are 2 stations to have their distance from the headquarters determined.

What is the name? Station One
What is the latitude? -44.3
What is the longitude? 33.2
Station One has a latitude of -44.3 degrees and a longitude of 33.2.

What is the name? Station Two
What is the latitude? -33.2
What is the longitude? 11.55
Station Two has a latitude of -33.2 degrees and a longitude of 11.55.


Here are the stations:
    Station One     -44.3, 33.2
    Station Two     -33.2, 11.55

Note that this doesn't take error handling into account, and some inputs may will not convert to float or int.

Upvotes: 0

Related Questions