Functions in Python

📘 Python 👁 54 views 📅 Nov 05, 2025
⏱ Estimated reading time: 2 min

Functions in Python

Functions allow you to group code into reusable blocks that can be called multiple times.


1. Defining a Function

def greet(): print("Hello, Python!")
  • def keyword is used to define a function.

  • Function name follows Python naming rules.

  • Parentheses () can contain parameters.

  • Colon : and indentation define the function body.


2. Calling a Function

greet() # Output: Hello, Python!

3. Function with Parameters

def greet_user(name): print(f"Hello, {name}!") greet_user("Alice") # Output: Hello, Alice!
  • Parameters allow functions to accept input values.


4. Function with Return Value

def add(a, b): return a + b result = add(5, 3) print(result) # Output: 8
  • return sends a value back to the caller.


5. Default Parameters

def greet(name="Guest"): print(f"Hello, {name}!") greet() # Output: Hello, Guest! greet("Alice") # Output: Hello, Alice!
  • Use default values if arguments are not provided.


6. Keyword Arguments

def describe_pet(name, animal="dog"): print(f"{name} is a {animal}") describe_pet(animal="cat", name="Whiskers") # Output: Whiskers is a cat
  • Pass arguments by name, not just position.


7. Variable-Length Arguments

def add_numbers(*args): return sum(args) print(add_numbers(1, 2, 3, 4)) # Output: 10
  • *args allows any number of positional arguments.

  • **kwargs allows any number of keyword arguments.


8. Key Points

  • Functions improve code reusability and readability.

  • Can accept parameters and return values.

  • Supports default, keyword, and variable-length arguments.

  • Always use meaningful function names for clarity.


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes