Welcome to the CSC Q&A, on our server named in honor of Ada Lovelace. Write great code! Get help and give help!
It is our choices... that show what we truly are, far more than our abilities.


+5 votes

I'm just wondering why it's important to type def main(): and then have all of our code indented in the program if the code works fine when it's just typed into the program lines.


def main():
    print("Hello world!")


instead of just

print("Hello world!")
asked in CSC201 Spring 2021 by (1 point)
edited by

Note: I edited your question slightly to get better code formatting using the { } button on the code chunks.

3 Answers

+3 votes

Great question -- you are right that your code will work just fine without it, and you don't need to use a main() function.

We are just introducing this concept of functions here, because later as the programs get larger it will be useful to split big programs into multiple smaller procedures, so main() would just be one function among many. (And it's traditional to name the main/primary function "main()").

For example, in the graphics lab, we could have made a separate function called "drawHat()" for drawing the hat, and another one called drawFace() for drawing the eyes & mouth...

answered by (508 points)
+3 votes

We will need functions to take different inputs as we move on later in the course. Furthermore, functions can make the code much simpler as we will use them to break code into smaller parts which will make it easy for us to debug the code.

answered by (1 point)
+2 votes

So, def main(), is the main function in python which is the point of execution, that means when you start your program it executes it from the def main(), and ends the program at main(), it's like an indication where to start from and where to end. Also, the main function in Python programming is a necessity to start the execution of the program as it gets executed only when the program is run directly and not executed when imported as a module.
Hope this helps! :)

answered by (1 point)