Python FunctionsPython Functions1

Python Exception HandlingPython Exception Handling1

🔍

Python Functions



As you write more code, you’ll notice that some parts of your code repeat. Instead of writing the same thing again and again, we can group that code into something called a function.

Functions let you give a name to a block of code. Later, you can use that name to run the code whenever you want — as many times as you want!

Why Do We Need Functions?

Basic Syntax of a Function

This is how you define a simple function in Python:

def function_name():
    # block of code
    print("Hello!")

Explanation:

How to Call (Use) a Function

Once the function is defined, you can use it like this:

def say_hello():
    print("Hello!")

say_hello()

Output:

Hello!

Explanation: The line say_hello() tells Python to run the code inside the function.

Functions with Parameters (Inputs)

You can also send information to a function by using parameters:

def greet(name):
    print("Hello, " + name + "!")

greet("Alice")
greet("Bob")

Output:

Hello, Alice!
Hello, Bob!

Explanation: The word you pass inside greet() goes into the name variable inside the function.

Functions That Return a Value

Sometimes you want a function to calculate and give back a value. For that, we use the return keyword:

def add(a, b):
    return a + b

result = add(3, 4)
print(result)

Output:

7

Explanation: The function add() calculates 3 + 4 and returns 7, which we print.

Different Types of Functions

Examples of All Types

# No input, no return
def show_message():
    print("Welcome!")

# Input, no return
def greet_user(name):
    print("Hi, " + name)

# Input and return
def multiply(x, y):
    return x * y

# Using the functions
show_message()
greet_user("Zara")
print(multiply(3, 5))

Output:

Welcome!
Hi, Zara
15

Conclusion

Functions are like mini-programs inside your main program. You can call them whenever you need them. This makes your code easier to read, write, and fix. You’ll be using functions a lot in Python!



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M