Search code examples
pythoninputprogram-entry-point

When input() is used as function argument, why does it run before main()


I have two functions

read_operator_rate_file(filename = 'test_scenarios.csv') &
get_input(phone_number_to_dial = input("enter phone number>> "))

In main I am calling them in order and the first function checks the condition for the CSV and may exit if there's any error. But, now when I put input function as the parameter for get_input function I am reading the prompt before the first function is being executed.

the code sample:

import csv

def read_operator_rate_file(filename = 'test_scenarios.csv'):
   
    try:
    with open(filename, newline='') as f:
        # read each row as a list and store it in a list
        operator_data = list(csv.reader(f))
        operator_data.sort(key = lambda x:int(x[0]))
        return operator_data
except FileNotFoundError as errorcode:
    print(errorcode)
except IOError:
    print("Could not read file:"), filename


def get_input(phone_number_to_dial = input("enter phone number>> ")):
   
    try:
       
        assert (phone_number_to_dial.startswith('+') and     phone_number_to_dial[
                                                         1:].isdigit())     or phone_number_to_dial[
                                                                           :].isdigit(), 'Invalid phone number'
        assert len(phone_number_to_dial) > 2, 'Phone number too short'
        # had this at 9 but changed it to 2 for calling 112
        assert len(phone_number_to_dial) < 16, 'Phone number too long'
    except Exception as e:
        print(e)
        exit()
    else:
        return (phone_number_to_dial)

if __name__ == '__main__':
    operator_list = read_operator_rate_file()
    get_input()

Solution

  • I'm not sure why exactly it happens like that, but I would imagine that the default argument is evaluated when the function is defined, which is before you call your code.

    Rather than

    def get_input(phone_number_to_dial = input("enter phone number>> ")):
    

    I would suggest that you use something like:

    def get_input(phone_number_to_dial=None):
        if phone_number_to_dial is None:
            phone_number_to_dial = input("enter phone number>> ")