0
0
Pythonprogramming~10 mins

Function definition and syntax in Python - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Function definition and syntax
Start
Define function with def
Function name and parameters
Function body indented
Function ends
Call function to run it
Function runs and returns
End
This flow shows how a function is defined with def, given a name and parameters, has an indented body, and then is called to run.
Execution Sample
Python
def greet(name):
    print(f"Hello, {name}!")

greet("Alice")
Defines a function greet that prints a hello message, then calls it with 'Alice'.
Execution Table
StepActionEvaluationResult
1Define function greet with parameter nameNo outputFunction greet created
2Call greet with argument 'Alice'name = 'Alice'Function greet starts
3Execute print inside greetPrints 'Hello, Alice!'Output: Hello, Alice!
4Function greet endsNo return valueBack to main program
💡 Function greet has finished running after printing the message.
Variable Tracker
VariableStartAfter call greet('Alice')Final
nameundefined'Alice'undefined after function ends
Key Moments - 3 Insights
Why do we indent the function body?
Indentation shows which lines belong inside the function, as seen in step 3 where print is indented under greet.
What happens if we call the function without parentheses?
Without parentheses, the function does not run; step 2 shows calling greet() with parentheses runs the function.
Is the variable 'name' available outside the function?
No, 'name' exists only inside the function during step 2 and 3, then disappears after step 4.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'name' during step 3?
A'Alice'
Bundefined
CNone
Dgreet
💡 Hint
Check the 'Evaluation' column at step 3 in the execution table.
At which step does the function greet actually run its code?
AStep 2
BStep 3
CStep 1
DStep 4
💡 Hint
Look for the step where the print statement executes in the execution table.
If we remove the parentheses in greet("Alice"), what changes in the execution table?
AError occurs at step 2
BFunction greet runs twice
CFunction greet is defined but never called
DOutput prints twice
💡 Hint
Refer to step 2 where the function call happens with parentheses.
Concept Snapshot
def function_name(parameters):
    indented function body

- Use def to define a function.
- Function body must be indented.
- Call function with parentheses to run it.
- Parameters receive input values.
Full Transcript
This example shows how to define a function in Python using def, give it a name and parameters, write an indented body, and then call it with parentheses to run. The variable inside the function exists only during the function call. Indentation is important to mark the function body. Calling the function without parentheses does not run it.