Functions in Python
Python : Functions
A function is a block of code that performs a specific task and can be reused multiple times in a program.
How to create a function in Python?
In Python, functions are defined using the def
keyword, followed by the function name, parameters(Arguments) in parentheses, and a colon.
Function's Syntax in Python
# Function definition
def function_name(...parameters):
# function_body(function definitions)
# It can't be empty
# Calling a Function
function_name(...parameters)
How to paas Arguments(parameters) to Function
Information can be passed into functions as arguments(also called parameters).
- Argument With Default Value
def greet(name, greeting='Hello'): print(greeting + ', ' + name) greet('John') # Output: Hello, John greet('Jane', 'Hi') # Output: Hi, Jane
- Missing Argument
def greet(name, greeting): print(greeting + ', ' + name) greet('John') # Output: throw error as greeting is not defined greet('Jane', 'Hi') # Output: Hi, Jane
Returns Multiple Value using tuples
def calculate_stats(numbers):
mean = sum(numbers) / len(numbers)
variance = sum((x - mean) ** 2 for x in numbers) / len(numbers)
return mean, variance
result = calculate_stats([1, 2, 3, 4, 5])
print(result) # Output 3.0, 2.0
Previous Article
Next Article
Python Tutorials
- Hello World
- Variables and Types
- Lists
- Tuple
- Basic Operators
- Strings
- Conditions
- Loops
- Functions
- Classes and Objects
- Dictionaries
- Map
- Filter
- Reduce
- Sets
- Decorators
- Generators
- Modules and Packages
- Numpy Arrays
- Pandas Basics
- List Comprehensions
- Lambda functions
- Multiple Function Arguments
- Partial functions
- Regular Expressions
- Exception Handling
- Serialization
- Code Introspection