0
0
Pythonprogramming~5 mins

Methods with parameters in Python

Choose your learning style9 modes available
Introduction

Methods with parameters let you give extra information to a method so it can do different things each time you use it.

When you want a method to greet different people by name.
When you need to calculate the area of shapes with different sizes.
When you want to add two numbers that can change each time.
When you want to print a message with a custom number of times.
Syntax
Python
def method_name(parameter1, parameter2):
    # code using parameters
    pass

Parameters are like placeholders for values you give when calling the method.

You can have as many parameters as you need, separated by commas.

Examples
This method takes one parameter name and prints a greeting.
Python
def greet(name):
    print(f"Hello, {name}!")
This method takes two numbers and returns their sum.
Python
def add(a, b):
    return a + b
This method prints a message multiple times based on the times parameter.
Python
def repeat(message, times):
    for _ in range(times):
        print(message)
Sample Program

This program shows three methods with parameters. It greets Alice, adds two numbers, and repeats a message.

Python
def greet(name):
    print(f"Hello, {name}!")

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

def repeat(message, times):
    for _ in range(times):
        print(message)

# Using the methods

greet("Alice")
result = add(5, 7)
print(f"5 + 7 = {result}")
repeat("Hi!", 3)
OutputSuccess
Important Notes

Parameters let methods be flexible and reusable.

Always give the right number of arguments when calling a method.

You can use default values for parameters to make some optional.

Summary

Methods with parameters take inputs to work with different data.

Parameters are listed inside the parentheses in the method definition.

You call methods with arguments that match the parameters.