当 input() 用作函数参数时,为什么它在 main() 之前 运行

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

我有两个功能

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

在 main 中,我按顺序调用它们,第一个函数检查 CSV 的条件,如果有任何错误可能会退出。但是,现在当我将输入函数作为 get_input 函数的参数时,我正在阅读第一个函数执行前的提示。

代码示例:

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()

我不确定为什么会这样,但我想默认参数是在定义函数时计算的,也就是在调用代码之前。

而不是

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

我建议您使用类似的东西:

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