简体   繁体   English

如何将 __name__ == "__main__" 转换为函数 main()?

[英]How to convert if __name__ == "__main__" to function main()?

  • Hello I am fairly new to python and wondering how to convert __name__ == "__main__" to function def main() ?您好,我对 python 相当__name__ == "__main__" ,想知道如何将__name__ == "__main__"转换为函数def main()
def compute_time(list_of_times):
    """Function to convert time in seconds to time in millisecond.
    Parameters:
    times_list = List of times_string splitted by space ' ' (List)
    Returns:
    times = Converted times (List)
    """
    times = [] # In seconds
    for time_string in list_of_times:
        times.append(int(time_string) / 1000)
    return times

def compute_speed(times_after_computation):
    """Function to compute speeds based on times.
    Parameters:
    times = Converted times (List)
    Returns:
    speeds = Computed speeds (List)
    """
    speeds = []
    for i in range(len(times_after_computation) - 1):
        speed_m_per_s = circumference / ((times_after_computation[i + 1] \
                                          - times_after_computation[i]))
        speeds.append(speed_m_per_s)
    return speeds

def print_table(times_computed, speeds_computed):
    """Function to print times speeds like a table.
    Parameters:
    times = Converted times (List)
    speeds = Computed speeds (List)
    """
    print("Time (s) Speed (m/s)")
    for i, _ in enumerate(speeds_computed):
        print("{:6.2f} {:9.2f}".format(times_computed[i], speeds_computed[i]))

if __name__ == "__main__":
    circumference = float(input("Circumference (m)? "))
    times_string = input("Times (msecs, space seperated)? ")
    times_list = times_string.split()
    computed_times = compute_time(times_list)
    computed_speeds = compute_speed(computed_times)
    print_table(computed_times, computed_speeds)

Change the if statement to just call main() :将 if 语句更改为只调用main()

if __name__ == "__main__":
    main()

And move all the code that was underneath the if statement into a function named main() .并将 if 语句下的所有代码移动到名为main()的函数中。

You can define your own main function and call it from within the if statement like so:您可以定义自己的主函数并从 if 语句中调用它,如下所示:

def main():
    # Code for main here

if __name__ == "__main__":
   main()

The if statement gets executed if the program is executed directly (ie. python [name of program] from terminal), as opposed to being imported.如果程序是直接执行的(即来自终端的python [name of program] ),则 if 语句将被执行,而不是被导入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM