Main function
In python it is considered good practice to define a main()
function as a starting point for executing your code. For example:
def main():
text = "For sale: baby shoes, never worn."
number_of_words = count_words(text)
print(f"There are {number_of_words} words in this text")
# some function
def count_words(string):
words = string.split()
n_words = len(words)
return n_words
if __name__ == '__main__':
main()
You see that in this case all the code is neatly wrapped in functions. The code on line 2 - 4, that you’d normally just put in the main body of the python file, is now all delegated to the function called main()
. To understand why and how, have a look at the video below.
The condition, if __name__ == '__main__':
, might look somewhat mysterious. For now, you don’t have to fully understand it. This condition becomes more relevant once you start creating bigger python projects that are spread out over multiple files.
If you already know how to create multi-file python projects, you can have a look here: if name is main