Function Fundamentals in Python
A Python function is a named block of code that runs only when it is called, and is used to perform a specific task, optionally taking input and returning a value.
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 6.67
Function Fundamentals in Python
Swipe to show menu
A Python function is a named block of code that runs only when it is called, and is used to perform a specific task, optionally taking input and returning a value.
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!