function at the end of code- why do i have to place it?

Question:

I’m just starting my adventure with Python. Unfortunately, I can’t figure out why, at the end of my code, I have to add myfunc(). Without it my code doesn’t display.

How is it if I use more than one definition then I have to put each definition at the end of the code?

def myfunc(a=4,b=6):
    sum = a + b
    print(sum)
    
myfunc()
Asked By: WiktorCN

||

Answers:

When you define a function with def, all you’re doing is telling Python that your function exists. If you only had that def block and didn’t call myFunc() at the end, Python would simply have gone, "Okay, your function exists. Neat."

What you want is not only to tell Python about the function but instruct Python to run the function. That’s where the function call comes from.

Answered By: Daniel Walker

The thing throwing you off is that you don’t need to put all your code into a function. Your code could (and should) be rewritten as this:

sum = a + b
print(sum)

This code will do the exact same thing. A function, by definition, is a block of code that is given a name, so you can use it multiple times without having to rewrite the whole block of code every time you want to use it. Because you are putting your code into a function, you must tell Python that you want to run that code too.

Answered By: Michael M.
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.