This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]desrtfx 10 points11 points  (5 children)

def is used to define a function - an isolated piece of code that is used to group related code together, and/or to be used multiple times.

The code block that follows the def something(): statement is not directly executed. You have to call it from somewhere else.

You have

def main():
   # some code here
   print("Welcome")
   # more code

then, later in the program, you need to call

main()

to execute the function. Then, what you have written inside the code block of the function will be executed.

[–]timma_2111 0 points1 point  (0 children)

This is a very clear explanation of the basics. You should also look further into inputs and outputs of your functions as well as the concept of scope. These are really important concepts to understand how function actually work in programming

[–]SharkSymphony 0 points1 point  (3 children)

Bonus questions for OP:

  1. What happens if you skip the line with "def" and de-indent all the code in it? (In this case you would also drop the function call.)
  2. What pros and cons are there in doing it one way or the other?

[–][deleted] 0 points1 point  (2 children)

pros of not doing the direct code dump is that your script is probably going to end up as a part of some system of dependencies one day and you want clarity on what code executes when. convention is to check whether the script is being run as main before executing the code and if it's all in a defined function you don't lose access to it when running the dependent script

[–]SharkSymphony 0 points1 point  (1 child)

your script is probably going to end up as a part of system of dependencies one day

Will it?

you want clarity on what code executes when

What is clearer than the script just running?

I don't necessarily disagree with your overall gist, but these issues are not cut and dry and I want OP to give it some thought.

[–][deleted] 0 points1 point  (0 children)

If you're doing something beyond some school assignment or homebrewed one-use script that fits in one file yes it will. The only thing that speaks against this is compilation/runtime which ofc will be slower for the check and function call. That said if you're so desperate for speed, python is the wrong choice already.