0% found this document useful (0 votes)
13 views22 pages

Functions in Python

Uploaded by

pari.jasbeer
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
13 views22 pages

Functions in Python

Uploaded by

pari.jasbeer
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 22

Functions in python

Here’s an example with a detailed explanation of parameters and arguments:


Code Example:
python
Copy code

# Function definition with parameters


def calculate_area(length, width):
"""
This function calculates the area of a rectangle.
Parameters:
length: The length of the rectangle (parameter).
width: The width of the rectangle (parameter).
"""
area = length * width
print(f"The area of the rectangle is: {area} square units.")

# Function call with arguments


calculate_area(5, 3) # Arguments: 5 and 3
calculate_area(7, 2) # Arguments: 7 and 2

Explanation:
1. Parameters:
o length and width are parameters.

o Parameters act as placeholders in the function definition. They


represent the data that the function will use when called.
2. Arguments:
o When the function is called, values like 5 and 3 are passed. These
are arguments.
o Arguments provide the actual data to the function.

o In the first function call, 5 is assigned to length and 3 is assigned to


width.

1
What Happens in the Example:
1. First Call: calculate_area(5, 3)
o Arguments: 5 and 3

o Parameters receive the values: length = 5, width = 3

o The function calculates 5 * 3 = 15 and prints:


"The area of the rectangle is: 15 square units."
2. Second Call: calculate_area(7, 2)
o Arguments: 7 and 2

o Parameters receive the values: length = 7, width = 2

o The function calculates 7 * 2 = 14 and prints:


"The area of the rectangle is: 14 square units."
In Summary:
 Parameter: A placeholder in the function definition (length, width).
 Argument: The actual value you pass to the function (5, 3, etc.). These
arguments replace the parameters when the function is called.

Arguments in a function are the values or data you pass to a function when you
call it. They allow you to provide input to the function so it can perform its
operations or calculations using that data.
Key Points About Arguments:
1. Definition:
o Arguments are specified in the parentheses when you define a
function.
o When calling the function, you provide the actual values, called
arguments.
2. Types of Arguments:
o Positional Arguments: These are the most common. They are
assigned to parameters in the same order they are listed.
python
Copy code
def greet(name, age):
print(f"Hello, {name}. You are {age} years old.")

greet("Alice", 25) # Output: Hello, Alice. You are 25 years old.

2
o Keyword Arguments: These are arguments passed by explicitly
naming the parameter.
python
Copy code
greet(age=25, name="Alice") # Output: Hello, Alice. You are 25 years old.
o Default Arguments: Parameters can have default values. If no
argument is provided, the default is used.
python
Copy code
def greet(name, age=30):
print(f"Hello, {name}. You are {age} years old.")

greet("Alice") # Output: Hello, Alice. You are 30 years old.


o Variable-Length Arguments: Allow a function to accept any
number of positional (*args) or keyword (**kwargs) arguments.
python
Copy code
def sum_numbers(*args):
print(sum(args))

sum_numbers(1, 2, 3, 4) # Output: 10
3. Why Use Arguments?
o To make functions reusable and flexible.

o You can pass different data to the same function and get different
results.
4. Arguments vs Parameters:
o Parameters are the variables listed in the function's definition.

o Arguments are the actual values passed to the function when


called.
Example:
python
Copy code
# Defining the function with parameters (placeholders)
def multiply(a, b):

3
return a * b

# Calling the function with arguments (actual values)


result = multiply(3, 4) # Arguments: 3 and 4
print(result) # Output: 12
In this example:
 a and b are parameters.
 3 and 4 are arguments.

Here are a few examples of Python functions to help you understand how they
work:

1. Simple Function
A function that prints a message.
python
Copy code
def greet():
print("Hello! Welcome to Python programming.")

# Calling the function

4
greet()

2. Function with Parameters and Arguments


A function that takes input and uses it.
python
Copy code
def add_numbers(a, b):
result = a + b
print(f"The sum of {a} and {b} is {result}.")

# Calling the function


add_numbers(5, 7) # Output: The sum of 5 and 7 is 12.

3. Function with Return Value


A function that calculates and returns a value.
python
Copy code
def multiply(a, b):
return a * b

# Calling the function and storing the result


product = multiply(4, 5)
print(f"The product is: {product}")

4. Default Arguments
A function with default parameter values.
python
Copy code
def greet_user(name="Guest"):
print(f"Hello, {name}!")

# Calling the function with and without arguments

5
greet_user("Alice") # Output: Hello, Alice!
greet_user() # Output: Hello, Guest!

5. Variable-Length Arguments (*args)


A function that accepts multiple arguments.
python
Copy code
def calculate_sum(*args):
total = sum(args)
print(f"The sum of the numbers is: {total}")

# Calling the function


calculate_sum(1, 2, 3, 4, 5) # Output: The sum of the numbers is: 15

6. Keyword Arguments (**kwargs)


A function that accepts named arguments.
python
Copy code
def display_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")

# Calling the function


display_info(name="John", age=25, profession="Engineer")

7. Nested Functions
A function defined inside another function.
python
Copy code
def outer_function():
def inner_function():
print("This is the inner function.")

6
print("This is the outer function.")
inner_function()

# Calling the outer function


outer_function()

8. Lambda Function (Anonymous Function)


A small one-line function.
python
Copy code
# Lambda to add two numbers
add = lambda x, y: x + y

print(add(3, 7)) # Output: 10

9. Function with Conditional Logic


A function that checks if a number is even or odd.
python
Copy code
def check_number(num):
if num % 2 == 0:
print(f"{num} is even.")
else:
print(f"{num} is odd.")

# Calling the function


check_number(10) # Output: 10 is even.
check_number(7) # Output: 7 is odd.

10. Recursive Function


A function that calls itself (e.g., to calculate factorial).
python

7
Copy code
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n - 1)

# Calling the function


print(factorial(5)) # Output: 120
These examples cover a range of basic to advanced concepts in Python
functions. Let me know if you'd like to explore a specific use case!

A function in Python is a reusable block of code designed to perform a specific


task. It allows you to group statements together, which can be executed

8
whenever the function is called. Functions help make code modular, readable,
and reusable.

Key Features of Functions in Python


1. Reusability: Write the logic once and use it multiple times.
2. Modularity: Break down complex tasks into smaller, manageable pieces.
3. Readability: Makes code cleaner and easier to understand.
4. Maintainability: Easier to update or debug a specific part of the program.

Structure of a Python Function


1. Defining a Function: Use the def keyword followed by the function name
and parentheses ( ).
2. Parameters (Optional): Variables listed in the function definition that
accept input values.
3. Body: Indented lines of code that perform the function's task.
4. Return Statement (Optional): Specifies the output of the function.
Syntax
python
Copy code
def function_name(parameters):
"""
Optional docstring to describe the function's purpose.
"""
# Code to execute
return value # Optional, returns a result

Example of a Simple Function


python
Copy code
def greet():
print("Hello, world!")

# Calling the function

9
greet() # Output: Hello, world!

Types of Functions in Python


1. Built-in Functions: Predefined functions provided by Python.
Examples: print(), len(), sum(), input(), etc.
2. User-defined Functions: Functions created by the programmer to
perform specific tasks.

Example of User-Defined Function with Parameters


python
Copy code
def add_numbers(a, b):
return a + b

# Calling the function


result = add_numbers(10, 20)
print(f"The sum is: {result}") # Output: The sum is: 30

Why Use Functions?


1. Avoid Redundancy: Eliminate duplicate code.
2. Improve Readability: Make programs easier to understand.
3. Facilitate Testing and Debugging: Isolate errors in smaller blocks of
code.
4. Enable Reuse: Functions can be reused in other parts of the program or
even in other projects.
Let me know if you want more examples or have any specific questions!

10
What is an Argument in Python?
An argument in Python is the actual value or data you pass to a function when
calling it. Arguments are assigned to the function's parameters, which are
placeholders defined in the function definition.

11
Example: Argument vs Parameter
python
Copy code
# Function with parameters (placeholders)
def greet(name): # 'name' is a parameter
print(f"Hello, {name}!")

# Calling the function with an argument


greet("Alice") # "Alice" is the argument

# Output:
# Hello, Alice!

Code Examples with Output


1. Positional Arguments
Arguments are passed in the same order as the parameters are defined.
python
Copy code
def introduce(name, age):
print(f"My name is {name} and I am {age} years old.")

# Calling the function


introduce("John", 25)

# Output:
# My name is John and I am 25 years old.

2. Keyword Arguments
Arguments are passed using the parameter names, so order does not matter.
python
Copy code

12
def introduce(name, age):
print(f"My name is {name} and I am {age} years old.")

# Calling the function with keyword arguments


introduce(age=30, name="Alice")

# Output:
# My name is Alice and I am 30 years old.

3. Default Arguments
If an argument is not provided, the parameter uses its default value.
python
Copy code
def greet(name="Guest"):
print(f"Hello, {name}!")

# Calling the function


greet("John") # Output: Hello, John!
greet() # Output: Hello, Guest!

4. Variable-Length Arguments (*args)


Allows passing a variable number of positional arguments.
python
Copy code
def calculate_sum(*numbers):
total = sum(numbers)
print(f"The sum of the numbers is: {total}")

# Calling the function


calculate_sum(1, 2, 3, 4) # Output: The sum of the numbers is: 10
calculate_sum(10, 20) # Output: The sum of the numbers is: 30

13
5. Keyword Variable-Length Arguments (**kwargs)
Allows passing a variable number of keyword arguments.
python
Copy code
def describe_person(**details):
for key, value in details.items():
print(f"{key}: {value}")

# Calling the function


describe_person(name="Alice", age=25, city="New York")

# Output:
# name: Alice
# age: 25
# city: New York

Exercises with Solutions


Exercise 1: Find the Maximum of Three Numbers
Write a function that takes three numbers as arguments and returns the largest.
python
Copy code
def find_max(a, b, c):
return max(a, b, c)

# Test the function


print(find_max(10, 20, 15)) # Output: 20

Exercise 2: Create a Greeting


Write a function that takes a name and an optional message, then prints the
greeting.
python
Copy code

14
def greet(name, message="Welcome!"):
print(f"Hello, {name}. {message}")

# Test the function


greet("Alice") # Output: Hello, Alice. Welcome!
greet("Bob", "Good morning!") # Output: Hello, Bob. Good morning!

Exercise 3: Calculate the Product of Numbers


Write a function that takes any number of arguments and calculates the product.
python
Copy code
def calculate_product(*numbers):
product = 1
for num in numbers:
product *= num
return product

# Test the function


print(calculate_product(1, 2, 3, 4)) # Output: 24
print(calculate_product(5, 6)) # Output: 30

Exercise 4: Describe a Person


Write a function that accepts keyword arguments to describe a person.
python
Copy code
def describe_person(**kwargs):
for key, value in kwargs.items():
print(f"{key.capitalize()}: {value}")

# Test the function


describe_person(name="John", age=30, profession="Engineer")
# Output:

15
# Name: John
# Age: 30
# Profession: Engineer

Exercise 5: Check if a Number is Prime


Write a function that takes a number as an argument and checks if it's prime.
python
Copy code
def is_prime(num):
if num < 2:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True

# Test the function


print(is_prime(7)) # Output: True
print(is_prime(10)) # Output: False

These exercises and examples cover various scenarios of using arguments and
parameters in Python functions. Let me know if you'd like more examples or
assistance!
4o
You said:
more examples with code.
ChatGPT said:
ChatGPT
Here are more examples of Python functions with arguments and parameters,
showcasing different scenarios:

1. Function to Calculate the Average of Numbers


python

16
Copy code
def calculate_average(*numbers):
if len(numbers) == 0:
return "No numbers provided."
return sum(numbers) / len(numbers)

# Test the function


print(calculate_average(10, 20, 30)) # Output: 20.0
print(calculate_average()) # Output: No numbers provided.

2. Function to Reverse a String


python
Copy code
def reverse_string(string):
return string[::-1]

# Test the function


print(reverse_string("Python")) # Output: nohtyP

3. Function to Check Palindrome


python
Copy code
def is_palindrome(string):
string = string.lower()
return string == string[::-1]

# Test the function


print(is_palindrome("Madam")) # Output: True
print(is_palindrome("Hello")) # Output: False

4. Function to Calculate Factorial


python

17
Copy code
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)

# Test the function


print(factorial(5)) # Output: 120
print(factorial(0)) # Output: 1

5. Function to Count Vowels in a String


python
Copy code
def count_vowels(string):
vowels = "aeiouAEIOU"
return sum(1 for char in string if char in vowels)

# Test the function


print(count_vowels("Hello World")) # Output: 3

6. Function to Find the Greatest Common Divisor (GCD)


python
Copy code
def gcd(a, b):
while b:
a, b = b, a % b
return a

# Test the function


print(gcd(48, 18)) # Output: 6

18
7. Function to Convert Celsius to Fahrenheit
python
Copy code
def celsius_to_fahrenheit(celsius):
return (celsius * 9/5) + 32

# Test the function


print(celsius_to_fahrenheit(0)) # Output: 32.0
print(celsius_to_fahrenheit(100)) # Output: 212.0

8. Function to Check if a Number is Even or Odd


python
Copy code
def even_or_odd(num):
return "Even" if num % 2 == 0 else "Odd"

# Test the function


print(even_or_odd(10)) # Output: Even
print(even_or_odd(7)) # Output: Odd

9. Function to Sort a List of Numbers


python
Copy code
def sort_numbers(numbers):
return sorted(numbers)

# Test the function


print(sort_numbers([5, 3, 8, 1, 4])) # Output: [1, 3, 4, 5, 8]

10. Function to Merge Two Dictionaries


python
Copy code

19
def merge_dictionaries(dict1, dict2):
return {**dict1, **dict2}

# Test the function


dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3, "d": 4}
print(merge_dictionaries(dict1, dict2)) # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}

11. Function to Generate Fibonacci Sequence


python
Copy code
def fibonacci(n):
sequence = []
a, b = 0, 1
while len(sequence) < n:
sequence.append(a)
a, b = b, a + b
return sequence

# Test the function


print(fibonacci(5)) # Output: [0, 1, 1, 2, 3]

12. Function to Capitalize Each Word in a Sentence


python
Copy code
def capitalize_words(sentence):
return " ".join(word.capitalize() for word in sentence.split())

# Test the function


print(capitalize_words("hello world")) # Output: Hello World

13. Function to Find Prime Numbers in a Range

20
python
Copy code
def primes_in_range(start, end):
primes = []
for num in range(start, end + 1):
if num > 1 and all(num % i != 0 for i in range(2, int(num ** 0.5) + 1)):
primes.append(num)
return primes

# Test the function


print(primes_in_range(10, 20)) # Output: [11, 13, 17, 19]

14. Function to Count Words in a String


python
Copy code
def word_count(string):
return len(string.split())

# Test the function


print(word_count("This is a Python function example")) # Output: 6

15. Function to Check if Two Strings are Anagrams


python
Copy code
def are_anagrams(str1, str2):
return sorted(str1.lower()) == sorted(str2.lower())

# Test the function


print(are_anagrams("listen", "silent")) # Output: True
print(are_anagrams("hello", "world")) # Output: False

Exercises to Try on Your Own:

21
1. Write a function to calculate the square of a number.
2. Write a function to find the minimum and maximum in a list.
3. Write a function to check if a string contains only alphabets.
4. Write a function to find the second largest number in a list.
5. Write a function to remove duplicates from a list.

22

You might also like