Lesson 7: Conditional Program Execution

Learn python programming in 12 lessons


Python programs are written to either be run as programs or modules that have methods that are used by other programs when imported. Sometimes a module can be used as both a module and a program and to ensure that the main method is not run when the program is imported into another program, a conditional statement is used.
Take for example the program DistributeGrade.py from the previous post. it has the allocateGrade method which can be very useful to other programs but you would definitely not want the part that asks the user to enter a grade to be imported and executed. Because of this, that part is put into a method we call main and the control statement is added at the end as seen below


#Name this file DistributeGrade.py

def allocateGrade(mark):
    if (mark < 0 or mark > 100):
        print("Invalid mark!")
    elif (mark > 79):
        print("A")
    elif (mark > 74 and mark <=79):
        print("B")
    elif (mark > 69 and mark <=74):
        print("C")
    elif (mark > 59 and mark <= 69):
        print("D")
    elif (mark > 49 and mark <= 59):
        print("E")
    else:
        print("F")

def main():
    marks = input("Enter a grade: ")
    allocateGrade(eval(marks))

if __name__ == '__main__':
    main()


In the program above, you see the last control statement with the __name__ and __main__ variable. Before you know why it is there, remove that whole line and try running your program and you will notice that it does not execute because that line is missing. But if you remove the last condition statement and get rid of the main method, the program would run.

By using the __name__ variable, you are actually saying that if this program is imported into another program, do not run the main method but just allow the use of the functions. So if the file containing the program above is imported into another program maybe because the person wants to use the allocateGrade method, then the __name__ variable will be replaced by the file name contacting the method.

This means if you import the file DistributeGrade.py into another Python program, __name__ variable would be replaced by DistributeGrade but if you press run within the DistributeGrade.py file, the __name__ variable would be replaced by the name of the main method. Note that the name of the main method does not necessarily have to be called main, it can be whatever you call it. But main is preferred because it is an industry standard.

Share your thoughts