0
0
Pythonprogramming~5 mins

Function definition and syntax in Python

Choose your learning style9 modes available
Introduction

Functions help us group instructions together to do a specific job. This makes our code easier to read and reuse.

When you want to repeat a task many times without writing the same code again.
When you want to organize your code into small, clear parts.
When you want to give a name to a set of instructions to use later.
When you want to make your program easier to test and fix.
Syntax
Python
def function_name(parameters):
    # code to run
    return result  # optional

Use def to start a function.

Parameters are optional and go inside parentheses.

Examples
A simple function with no parameters that prints a greeting.
Python
def greet():
    print("Hello!")
A function that takes two numbers and returns their sum.
Python
def add(a, b):
    return a + b
A function that takes one parameter and prints it inside a message.
Python
def say_name(name):
    print(f"Your name is {name}.")
Sample Program

This program defines a function to multiply two numbers and then uses it to multiply 4 and 5. It prints the result.

Python
def multiply(x, y):
    result = x * y
    return result

answer = multiply(4, 5)
print(f"4 times 5 is {answer}")
OutputSuccess
Important Notes

Indentation is important in Python to show which code belongs inside the function.

If you don't use return, the function will return None by default.

Summary

Functions group code to do one job.

Use def to create a function with a name and optional parameters.

Use return to send back a result from the function.