What Is Function?
In Python, a function is a named block of reusable code that performs a specific task. Functions act like LEGO pieces: small, reusable building blocks you can use throughout your program.
Using functions helps avoid rewriting code, reduces mistakes, and breaks large tasks into smaller steps. Each function handles one action, making programs clearer and easier to maintain. In short, functions let you reuse logic and keep your code organized.
Defining a Function
Define the simplest function in Python.
- Use the
defkeyword; - Write the function name using snake_case;
- Add
():β parameters go inside the parentheses; - Write the function body on an indented line;
- Optionally specify a return value;
- Call the function using its name.
Create a simple function that prints 'Hello, world!' and call it.
123456789# Specify the function name # The function doesn't require any parameters, so we simply use `():` def print_hello(): # Function body: we have to use indentation when defining it. print('Hello, world!') # The function doesn't return anything, so we don't need to write additional code # Call the function print_hello()
The print() inside print_hello() is a built-in function. A function may perform an action without returning a value. Since print_hello() only prints a message and doesnβt provide output for further use, it has no return value.
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat
Awesome!
Completion rate improved to 4.17
What Is Function?
Swipe to show menu
In Python, a function is a named block of reusable code that performs a specific task. Functions act like LEGO pieces: small, reusable building blocks you can use throughout your program.
Using functions helps avoid rewriting code, reduces mistakes, and breaks large tasks into smaller steps. Each function handles one action, making programs clearer and easier to maintain. In short, functions let you reuse logic and keep your code organized.
Defining a Function
Define the simplest function in Python.
- Use the
defkeyword; - Write the function name using snake_case;
- Add
():β parameters go inside the parentheses; - Write the function body on an indented line;
- Optionally specify a return value;
- Call the function using its name.
Create a simple function that prints 'Hello, world!' and call it.
123456789# Specify the function name # The function doesn't require any parameters, so we simply use `():` def print_hello(): # Function body: we have to use indentation when defining it. print('Hello, world!') # The function doesn't return anything, so we don't need to write additional code # Call the function print_hello()
The print() inside print_hello() is a built-in function. A function may perform an action without returning a value. Since print_hello() only prints a message and doesnβt provide output for further use, it has no return value.
Thanks for your feedback!