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

Python 当input()用作函数参数时,为什么它在main()之前运行,python,input,main,Python,Input,Main,我有两个功能 read_operator_rate_file(filename = 'test_scenarios.csv') & get_input(phone_number_to_dial = input("enter phone number>> ")) 大体上,我是按顺序调用它们的,第一个函数检查CSV的条件,如果有任何错误,可能会退出。但是,现在当我把input function作为get_input function的参数时,我在执行第一个函

我有两个功能

read_operator_rate_file(filename = 'test_scenarios.csv') &
get_input(phone_number_to_dial = input("enter phone number>> "))
大体上,我是按顺序调用它们的,第一个函数检查CSV的条件,如果有任何错误,可能会退出。但是,现在当我把input function作为get_input function的参数时,我在执行第一个函数之前读取提示

代码示例:

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()
导入csv
def read_operator_rate_文件(文件名='test_scenarios.csv'):
尝试:
将open(filename,newline='')作为f:
#将每一行作为列表读取,并将其存储在列表中
操作员_数据=列表(csv.reader(f))
运算符_data.sort(key=lambda x:int(x[0]))
返回运算符\u数据
除FileNotFoundError作为错误代码外:
打印(错误代码)
除IOError外:
打印(“无法读取文件:”),文件名
def get_输入(电话号码到拨号=输入(“输入电话号码>>”)):
尝试:
断言(电话号码到拨号。开始使用(+)和电话号码到拨号[
1:][.isdigit())或拨打电话号码[
:].isdigit(),“无效电话号码”
断言len(电话号码到拨号)>2,“电话号码太短”
#9点的时候有这个,但打112改成了2
断言len(电话号码到拨号)<16,“电话号码太长”
例外情况除外,如e:
打印(e)
退出()
其他:
返回(电话号码到拨号)
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
操作员列表=读取操作员速率文件()
获取_输入()

我不确定为什么会发生这种情况,但我可以想象,默认参数是在定义函数时计算的,也就是在调用代码之前

而不是

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

请出示代码的一部分
main
一点也不特别,因此如果在调用
main
之前调用
input
,则将首先运行
input
。当我运行此部分时,首先会出现提示“输入电话号码”,然后按照main中调用的顺序调用函数。我不知道为什么。参数是用函数头(def get_input)计算的。您希望何时调用
input
?这是否回答了您的问题@wjandrea并非如此,但Q&A提供了大量关于何时(以及为什么)评估默认值的信息。FWIW,我可以愚弄hammer–我的评论确实会问它是否回答了这个问题。事实上,@wjandrea在评论中分享的链接似乎更清楚地解释了这个答案中的所有内容。我不知道该怎么做才是正确的习惯用法。