thatguy123
thatguy123

Reputation: 25

How to convert if __name__ == "__main__" to function 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)

Upvotes: 0

Views: 422

Answers (2)

Tob
Tob

Reputation: 1025

You can define your own main function and call it from within the if statement like so:

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.

Upvotes: 1

John Gordon
John Gordon

Reputation: 33335

Change the if statement to just call main():

if __name__ == "__main__":
    main()

And move all the code that was underneath the if statement into a function named main().

Upvotes: 3

Related Questions