Skip to main content

Command Palette

Search for a command to run...

"Unlocking the Power of Functions in Python 🐍"

Updated
3 min read
"Unlocking the Power of Functions in Python 🐍"

What is a Function?

A function is a block of reusable code that performs a specific task. It allows you to break down programs into smaller, manageable parts. Functions improve code readability, reusability, and structure.

Defining a Function

In Python, functions are defined using the def keyword followed by the function name and parentheses.

The syntax is:

def function_name(parameters):
     # function body
     return result  # (optional)
# Example:
def greet(name):
     print(f"Hello, {name}!")

greet("boss")  # Output: Hello, boss!

python provides various types of built in functions:

  • print(): Prints the specified message.

  • len(): Returns the length of an object.

  • type(): Returns the type of an object.

  • range(): Generates a sequence of numbers.

a="hello"
print(a)       #hello
print(len(a))  #5
print(type(a))  #<class 'String'>

Key Concepts in Functions

Return Statement:

The return statement is used to send a result back to the caller of the function. If no return statement is used, the function returns None.

# Example:
def multiply(x, y):
    return x * y
result = multiply(4, 6)
print(result)  # Output: 24

Parameters and Argument:

Parameters: are the variables listed inside the parentheses in the function definition. Arguments: are the values passed into the function when it is called.

# Example:
def add(a, b):      # 'a' and 'b' are parameters
     return a + b
result = add(3, 5)  # '3' and '5' are arguments
print(result)       # Output: 8

Default Parameters

You can define default values for parameters, which are used if no argument is provided during the function call.

# Example:
def greet(name="User"):
    print(f"Hello, {name}!")
greet()         # Output: Hello, User!
greet("bro")  # Output: Hello, Alice!

Keyword Arguments

Functions can also be called using keyword arguments, where you explicitly assign values to the parameters by their names.

# Example:
def describe_pet(pet_name, animal_type="dog"):
    print(f"I have a {animal_type} named {pet_name}.")
describe_pet(pet_name="Max", animal_type="cat")  # Output: I have a cat named Max.
describe_pet(pet_name="Buddy")  # Output: I have a dog named Buddy.

Variable-Length Arguments

You can pass a variable number of arguments to a function using *args (non-keyworded) and **kwargs (keyworded) parameters.

*args allows you to pass a variable number of non-keyword arguments.

**kwargs allows you to pass a variable number of keyword arguments.

# Example:
def sum_numbers(*args):
    return sum(args)
print(sum_numbers(1, 2,90, 3))  # Output: 96
print(sum_numbers(4, 5))     # Output: 9

Example programs:

#addition of two numbers
def add(a,b):
     return a+b
print(add(1,21))  #22
# to print table of a number using functions
a=int(input("enter number for which you want to print table"))

def table(a):
    i=1
    while i<=20:
        print(a, "x", i, "=", a * i)
        i+=1

table(a)

# sum of n natural numbers:
def sum_of_natural_no():
    a = int(input("enter a number"))
    sum=0
    for i in range(1,a+1):
        sum=sum+i
    return sum

result=sum_of_natural_no()
print(result)

python

Part 3 of 7

🚀 Ready to Get Started? Join me on a journey through Python programming, This series is your friendly guide to learning Python. Whether you're a beginner or want to improve, join me to explore Python and see what you can create! Happy coding! 🎉

Up next

"Control Flow Statements in Python 🐍"

Control Flow Statements: Control flow statements are fundamental in programming as they allow you to change the execution order of your code based on certain conditions. In Python, control flow includes: 1.Conditional Statements (if, elif, else) 2.Lo...