Debug School

rakesh kumar
rakesh kumar

Posted on • Edited on

Python Functions

User-Defined Function
Calling a Function
Variable-Length Arguments
(i) args
(ii)kwargs
Types of function

Example of a User-Defined Function
sum = calculate_sum(5, 10)
factorial(num):
getattr()
pow()
callable()
abs()
eval()
sum()
any()
format()

def square( num ):  
 return num**2     
object_ = square(6)
Enter fullscreen mode Exit fullscreen mode
def square(item_list):
    squares = []
    for l in item_list:
        squares.append(l ** 2)
    return squares

# Example usage:
nums = [1, 2, 3, 4, 5]
squared_nums = square(nums)
print(squared_nums)  # Output: [1, 4, 9, 16, 25] 
Enter fullscreen mode Exit fullscreen mode
def function( n1, n2 ):  
function( 50, 30)
Enter fullscreen mode Exit fullscreen mode
def function( *args_list ):    
    ans = []    
    for l in args_list:    
        ans.append( l.upper() ) 
Enter fullscreen mode Exit fullscreen mode
def function( **kargs_list ):    
    ans = []    
    for key, value in kargs_list.items():    
        ans.append([key, value])  
Enter fullscreen mode Exit fullscreen mode
# Function to convert all arguments to uppercase using *args
def function_args(*args_list):
    ans = []
    for l in args_list:
        ans.append(l.upper())
    return ans
# Example usage:
print(function_args('hello', 'world'))   # Output: ['HELLO', 'WORLD']
Enter fullscreen mode Exit fullscreen mode
# Function definition
def function_args(*args_list):
    ans = []
    for l in args_list:
        ans.append(l.upper())
    return ans

# Variables containing the values
words = ('hello', 'world')  # or ['hello', 'world']

# Call function by unpacking the values
print(function_args(*words))  # Output: ['HELLO', 'WORLD']
Enter fullscreen mode Exit fullscreen mode

Note

Using a Tuple (Recommended for Fixed Values)
stringwords = ('hello', 'world')   # Tuple format (immutable)

def function_args(*args_list):
    ans = []
    for l in args_list:
        ans.append(l.upper())
    return ans

# Unpack the tuple into the function
print(function_args(*stringwords))   # Output: ['HELLO', 'WORLD']
This is clean and works perfectly with the *args syntax because the tuple unpacks into individual arguments.

2. Using a List (If You Might Modify It)
python
stringwords = ['hello', 'world']   # List format (mutable)

def function_args(*args_list):
    return [l.upper() for l in args_list]

print(function_args(*stringwords))   # Output: ['HELLO', 'WORLD']
Enter fullscreen mode Exit fullscreen mode


# Function to collect key-value pairs as lists using **kwargs
def function_kwargs(**kargs_list):
    ans = []
    for key, value in kargs_list.items():
        ans.append([key, value])
    return ans

# Example usage:

print(function_kwargs(a=1, b=2))                # Output: [['a', 1], ['b', 2]]
Enter fullscreen mode Exit fullscreen mode
kwargs3 = {'a': 1, 'b': [1, 2, 3], 'c': 'hello'}

def process_kwargs(**kwargs):
    for key, value in kwargs.items():
        print(f"Key: {key}, Value: {value}")

# Call the function unpacking the dictionary with **
process_kwargs(**kwargs3)
Enter fullscreen mode Exit fullscreen mode

Note

Simple key-value pairs
kwargs1 = {'a': 1, 'b': 2}
With string keys explicitly quoted


kwargs2 = {"name": "Alice", "age": 25}

Mixed types as values
kwargs3 = {'a': 1, 'b': [1, 2, 3], 'c': 'hello'}

Using variables as values
x = 10
y = "test"
kwargs4 = {'x': x, 'y': y}

Empty dictionary
kwargs5 = {}
Additionally:

You can create dictionaries dynamically with the constructor:


kwargs6 = dict(a=1, b=2)

Nested dictionaries are also possible:
kwargs7 = {'a': 1, 'b': {'c': 2, 'd': 3}}
Enter fullscreen mode Exit fullscreen mode
lambda_ = lambda argument1, argument2: argument1 + argument2;    
print( "Value of the function is : ", lambda_( 20, 30 ) ) 
Enter fullscreen mode Exit fullscreen mode
def user_profile(**info):
    return [[k, v] for k, v in info.items()]

print(user_profile(name="Alice", age=30, country="India"))
# Output: [['name', 'Alice'], ['age', 30], ['country', 'India']]
Enter fullscreen mode Exit fullscreen mode
def log_event(**event_data):
    return [[k, v] for k, v in event_data.items()]

print(log_event(event="login", status="success", timestamp="2025-10-02"))
# Output: [['event', 'login'], ['status', 'success'], ['timestamp', '2025-10-02']]
Enter fullscreen mode Exit fullscreen mode
def shipping_address(**address):
    return [[k, v] for k, v in address.items()]

print(shipping_address(street="123 Main St", city="Pune", zip="411001"))
# Output: [['street', '123 Main St'], ['city', 'Pune'], ['zip', '411001']]
Enter fullscreen mode Exit fullscreen mode

convert given dynamic data into list

using flask

settings = Setting.query.all()
values_list = [row.setting_value for row in settings]
#output ['dark', 'en', 'UTC'].
def function_args(*args):
    return [v.upper() for v in args]  # or any processing

result = function_args(*values_list)
print(result)
#output ['DARK', 'EN', 'UTC'].
Enter fullscreen mode Exit fullscreen mode

how to get data in list format from database in flask

settings = Setting.query.all()
values_list = [row.setting_value for row in settings]
Enter fullscreen mode Exit fullscreen mode

using django

# Fetch all settings objects from the database
settings = Setting.objects.all()

# Extract the setting_value from each Setting object
values_list = [row.setting_value for row in settings]

# Define a function that accepts *args and processes them
def function_args(*args):
    return [v.upper() for v in args]  # You can modify processing as needed

# Call the function with each value as an argument
result = function_args(*values_list)

# Print the result
print(result)
Enter fullscreen mode Exit fullscreen mode

how to get data in list format from database in django

# Fetch all settings objects from the database
settings = Setting.objects.all()

# Extract the setting_value from each Setting object
values_list = [row.setting_value for row in settings]
Enter fullscreen mode Exit fullscreen mode

convert given dynamic data into keyvalue pair structured as a two-element list

Fetch Data from Database (Example in Python with SQLite) and convert into dictionarty

# Connect and fetch data
conn = sqlite3.connect('your_database.db')
cursor = conn.cursor()
cursor.execute("SELECT setting_name, setting_value FROM settings")
rows = cursor.fetchall()  # Each row is (key, value) tuple
# Convert to dictionary
data_dict = {key: value for key, value in rows}
Enter fullscreen mode Exit fullscreen mode

how to get data in dictionary format from database in sqlite

rows = cursor.fetchall()  # Each row is (key, value) tuple
# Convert to dictionary
data_dict = {key: value for key, value in rows}
Enter fullscreen mode Exit fullscreen mode
{'theme': 'dark', 'language': 'en'}
Enter fullscreen mode Exit fullscreen mode

*Use as **kwargs for Function to convert dictionary into two-element list *

def function_kwargs(**kwargs):
    ans = []
    for key, value in kwargs.items():
        ans.append([key, value])
    return ans

result = function_kwargs(**data_dict)
print(result)  # Each row as a [key, value] pair in a list
Enter fullscreen mode Exit fullscreen mode
[['theme', 'dark'], ['language', 'en']]
Enter fullscreen mode Exit fullscreen mode

using flask

settings = Setting.query.all()
data_dict = {row.setting_name: row.setting_value for row in settings}

def function_kwargs(**kwargs):
    return [[k, v] for k, v in kwargs.items()]

result = function_kwargs(**data_dict)
print(result)
Enter fullscreen mode Exit fullscreen mode

how to get data in dictionary format from database in flask

settings = Setting.query.all()
data_dict = {row.setting_name: row.setting_value for row in settings}
Enter fullscreen mode Exit fullscreen mode

using django

settings = Setting.objects.all().values('setting_name', 'setting_value')
data_dict = {row['setting_name']: row['setting_value'] for row in settings}

def function_kwargs(**kwargs):
    return [[k, v] for k, v in kwargs.items()]

result = function_kwargs(**data_dict)
print(result)
Enter fullscreen mode Exit fullscreen mode

how to get data in dictionary format from database in django

settings = Setting.objects.all().values('setting_name', 'setting_value')
data_dict = {row['setting_name']: row['setting_value'] for row in settings}
Enter fullscreen mode Exit fullscreen mode

python-tutorials-list-of-functions-of-list-datatypes
What are Python Functions?
A function is a collection of related assertions(statement) that performs a mathematical, analytical, or evaluative operation. Python functions are simple to define and essential to intermediate-level programming. The exact criteria hold to function names as they do to variable names. The goal is to group up certain often performed actions and define a function. Rather than rewriting the same code block over and over for varied input variables, we may call the function and repurpose the code included within it with different variables.

The functions are broad of two types, user-defined and built-in functions. It aids in keeping the software succinct, non-repetitive, and well-organized.

Advantages of Functions in Python
Python functions have the following benefits.

By including functions, we can prevent repeating the same code block repeatedly in a program.
Python functions, once defined, can be called many times and from anywhere in a program.
If our Python program is large, it can be separated into numerous functions which is simple to track.
The key accomplishment of Python functions is we can return as many outputs as we want with different arguments.

Example of a User-Defined Function
We will define a function that when called will return the square of the number passed to it as an argument.

Code

def square( num ):  
    """ 
    This function computes the square of the number. 
    """  
    return num**2   
object_ = square(9)  
print( "The square of the number is: ", object_ ) 
Enter fullscreen mode Exit fullscreen mode

Output:

The square of the number is:  81
Enter fullscreen mode Exit fullscreen mode

Calling a Function
A function is defined by using the def keyword and giving it a name, specifying the arguments that must be passed to the function, and structuring the code block.

After a function's fundamental framework is complete, we can call it from anywhere in the program. The following is an example of how to use the a_function function.

Code

# Defining a function  
def a_function( string ):  
    "This prints the value of length of string"  
    return len(string)  

# Calling the function we defined  
print( "Length of the string Functions is: ", a_function( "Functions" ) )  
print( "Length of the string Python is: ", a_function( "Python" ) )  
Enter fullscreen mode Exit fullscreen mode

Output:

Length of the string Functions is:  9
Length of the string Python is:  6
Enter fullscreen mode Exit fullscreen mode

Variable-Length Arguments
We can use special characters in Python functions to pass as many arguments as we want in a function. There are two types of characters that we can use for this purpose:

*args -These are Non-Keyword Arguments
**kwargs - These are Keyword Arguments.
Enter fullscreen mode Exit fullscreen mode

Here is an example to clarify Variable length arguments

Code

# Python code to demonstrate the use of variable-length arguments  

# Defining a function  
def function( *args_list ):  
    ans = []  
    for l in args_list:  
        ans.append( l.upper() )  
    return ans  
# Passing args arguments  
object = function('Python', 'Functions', 'tutorial')  
print( object )  

# defining a function  
def function( **kargs_list ):  
    ans = []  
    for key, value in kargs_list.items():  
        ans.append([key, value])  
    return ans  
# Paasing kwargs arguments  
object = function(First = "Python", Second = "Functions", Third = "Tutorial")  
print(object)  
Enter fullscreen mode Exit fullscreen mode

Output:

['PYTHON', 'FUNCTIONS', 'TUTORIAL']
[['First', 'Python'], ['Second', 'Functions'], ['Third', 'Tutorial']]
Enter fullscreen mode Exit fullscreen mode

return Statement
We write a return statement in a function to leave a function and give the calculated value when a defined function is called.

Syntax:

return < expression to be returned as output >

An argument, a statement, or a value can be used in the return statement, which is given as output when a specific task or function is completed. If we do not write a return statement, then None object is returned by a defined function.

Here is an example of a return statement in Python functions.

Code

# Python code to demonstrate the use of return statements  

# Defining a function with return statement  
def square( num ):  
    return num**2  

# Calling function and passing arguments.  
print( "With return statement" )  
print( square( 39 ) )  

# Defining a function without return statement   
def square( num ):  
     num**2   

# Calling function and passing arguments.  
print( "Without return statement" )  
print( square( 39 ) )  
Enter fullscreen mode Exit fullscreen mode

Output:

With return statement
1521
Without return statement
None
Enter fullscreen mode Exit fullscreen mode

Some Important Function

Python bin() Function
The python bin() function is used to return the binary representation of a specified integer. A result always starts with the prefix 0b.

Python bin() Function Example

x = 10

y = bin(x)

print (y)

Output:

0b1010

Python float()
The python float() function returns a floating-point number from a number or string.

Python float() Example

for integers

print(float(9))

for floats

print(float(8.19))

for string floats

print(float("-24.27"))

for string floats with whitespaces

print(float(" -17.19\n"))

string float error

print(float("xyz"))

Output:

9.0
8.19
-24.27
-17.19
ValueError: could not convert string to float: 'xyz'

Python len() Function
The python len() function is used to return the length (the number of items) of an object.

Python len() Function Example

strA = 'Python'

print(len(strA))

Output:

6

Python min() Function
Python min() function is used to get the smallest element from the collection. This function takes two arguments, first is a collection of elements and second is key, and returns the smallest element from the collection.

Python min() Function Example

Calling function

small = min(2225,325,2025) # returns smallest element

small2 = min(1000.25,2025.35,5625.36,10052.50)

Displaying result

print(small)

print(small2)

Output:

325
1000.25
Python set() Function
In python, a set is a built-in class, and this function is a constructor of this class. It is used to create a new set using elements passed during the call. It takes an iterable object as an argument and returns a new set object.

Python set() Function Example

Calling function

result = set() # empty set

result2 = set('12')

result3 = set('javatpoint')

Displaying result

print(result)

print(result2)

print(result3)

Output:

set()
{'1', '2'}
{'a', 'n', 'v', 't', 'j', 'p', 'i', 'o'}

Python slice() Function
Python slice() function is used to get a slice of elements from the collection of elements. Python provides two overloaded slice functions. The first function takes a single argument while the second function takes three arguments and returns a slice object. This slice object can be used to get a subsection of the collection.

Python slice() Function Example

# Calling function  
result = slice(5) # returns slice object  
result2 = slice(0,5,3) # returns slice object  
# Displaying result  
print(result)  
print(result2)  
Enter fullscreen mode Exit fullscreen mode

Output:

slice(None, 5, None)
slice(0, 5, 3)
Enter fullscreen mode Exit fullscreen mode

Python sorted() Function
Python sorted() function is used to sort elements. By default, it sorts elements in an ascending order but can be sorted in descending also. It takes four arguments and returns a collection in sorted order. In the case of a dictionary, it sorts only keys, not values.

Python sorted() Function Example

str = "javatpoint" # declaring string  
# Calling function  
sorted1 = sorted(str) # sorting string  
# Displaying result  
print(sorted1) 
Enter fullscreen mode Exit fullscreen mode

Output:

['a', 'a', 'i', 'j', 'n', 'o', 'p', 't', 't', 'v']
Enter fullscreen mode Exit fullscreen mode

Python pow() Function
The python pow() function is used to compute the power of a number. It returns x to the power of y. If the third argument(z) is given, it returns x to the power of y modulus z, i.e. (x, y) % z.

Python pow() function Example

# positive x, positive y (x**y)  
print(pow(4, 2))  

# negative x, positive y  
print(pow(-4, 2))  

# positive x, negative y (x**-y)  
print(pow(4, -2))  

# negative x, negative y  
print(pow(-4, -2)) 
Enter fullscreen mode Exit fullscreen mode

Output:

16
16
0.0625
0.0625
Enter fullscreen mode Exit fullscreen mode

Python round() Function
The python round() function rounds off the digits of a number and returns the floating point number.

Python round() Function Example

#  for integers  
print(round(10))  

#  for floating point  
print(round(10.8))  

#  even choice  
print(round(6.6))  
Enter fullscreen mode Exit fullscreen mode

Output:

10
11
7
Enter fullscreen mode Exit fullscreen mode

Types of function

Anonymous Functions (Lambda Functions):

Definition: Functions that are defined without a name using the lambda keyword.

Syntax:

lambda arguments: expression
Enter fullscreen mode Exit fullscreen mode

Example:

add = lambda x, y: x + y
print(add(2, 3))  # Output: 5
Enter fullscreen mode Exit fullscreen mode

Use Cases:

Quick one-liner functions.

Functions used as arguments to higher-order functions like map(), filter(), and sorted().

  1. Regular Functions (Def Functions):

Definition: Functions that are defined using the def keyword with a name.

Syntax:

def function_name(parameters):
    # function body
    return value
Enter fullscreen mode Exit fullscreen mode

Example:

def add(x, y):
    return x + y
print(add(2, 3))  # Output: 5
Enter fullscreen mode Exit fullscreen mode

Use Cases:

Used for defining reusable blocks of code.

Functions with complex logic or multiple statements.

  1. Recursive Functions:

Definition: Functions that call themselves.

Syntax:

def recursive_function():
    if condition:
        return base_case
    else:
        return recursive_function()
Enter fullscreen mode Exit fullscreen mode

Example (Factorial):

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n-1)
print(factorial(5))  # Output: 120
Enter fullscreen mode Exit fullscreen mode

Use Cases:

Used in problems that can be broken into smaller subproblems (like tree traversal, divide and conquer algorithms).

Higher-order Functions:

Definition: Functions that take other functions as arguments or return them as results.

Example:

def apply_function(f, x):
    return f(x)

def square(x):
    return x * x

print(apply_function(square, 3))  # Output: 9
Enter fullscreen mode Exit fullscreen mode

Use Cases:

When you need to pass functions as parameters or return functions from other functions.

Functional programming style.

Generator Functions:

Definition: Functions that use the yield keyword to return an iterable generator object.

Syntax:

def generator_function():
    yield value
Enter fullscreen mode Exit fullscreen mode

Example:

def countdown(n):
    while n > 0:
        yield n
        n -= 1

for number in countdown(5):
    print(number)
Enter fullscreen mode Exit fullscreen mode

Use Cases:

Used when dealing with large datasets or streams of data where you don’t want to store all the values in memory.

Lambda Functions with Multiple Expressions:

Definition: A variation of lambda functions where you use logical expressions within them (only one expression is allowed).

Example:

max_value = lambda x, y: x if x > y else y
print(max_value(5, 10))  # Output: 10
Enter fullscreen mode Exit fullscreen mode

Closure Functions:

Definition: Functions that are defined within another function and remember the values from the enclosing function's scope.

Syntax:

def outer_function(outer_variable):
    def inner_function(inner_variable):
        return outer_variable + inner_variable
    return inner_function
Enter fullscreen mode Exit fullscreen mode

Example:

def multiply_by(n):
    def multiplier(x):
        return x * n
    return multiplier

multiply_by_5 = multiply_by(5)
print(multiply_by_5(10))  # Output: 50
Enter fullscreen mode Exit fullscreen mode

Use Cases:

Useful for creating function factories and handling data encapsulation.

Built-in Functions:

Definition: Python provides several built-in functions that can be used without needing to define them.

Example:

print()

len()

sum()

sorted()
Enter fullscreen mode Exit fullscreen mode

Use Cases:

Everyday operations like printing, sorting, or finding lengths of data structures.

Partial Functions:

Definition: Functions created using the functools.partial() function to fix a certain number of arguments of a function and generate a new function.

Syntax:

from functools import partial

Example:

def power(base, exponent):
    return base ** exponent

cube = partial(power, exponent=3)
print(cube(2))  # Output: 8
Enter fullscreen mode Exit fullscreen mode

Use Cases:

Used for creating a function with some arguments preset.

Function with Variable Number of Arguments:

Definition: Functions that can accept any number of arguments using *args for positional arguments and **kwargs for keyword arguments.

Syntax:

def func(*args, **kwargs):
    # handle arguments
Enter fullscreen mode Exit fullscreen mode

Example:

def add(*args):
    return sum(args)

print(add(1, 2, 3))  # Output: 6
Enter fullscreen mode Exit fullscreen mode

Use Cases:

Functions that need to handle a dynamic number of arguments, like when working with a variable-length list of items.

Static Methods:

Definition: Methods that do not require an instance to be called. They can be called on the class itself.

Syntax:

class MyClass:
    @staticmethod
    def my_static_method():
        pass
Enter fullscreen mode Exit fullscreen mode

Example:

class MyClass:
    @staticmethod
    def greet(name):
        return f"Hello, {name}!"

print(MyClass.greet("Alice"))  # Output: Hello, Alice!
Enter fullscreen mode Exit fullscreen mode

Use Cases:

When the method doesn't rely on instance attributes and doesn't modify the state of the object.

SUMMARY

1.wap to square of num
2.function that takes a list of numbers and returns a new list containing the squares of those numbers.
3.function takes any number of string arguments and returns a list of those arguments converted to uppercase

  1. function takes any number of keyword arguments and returns a list where each element is a two-item list containing each argument’s key and its value. (i)collects user information fields into key-value pairs. (ii)records details about an event by capturing any number of event-related properties as key-value pairs. (III)shipping_address

5.list out format in which *args_list and **kwargs apply
*args_list=tuple,list,set,Dict keys,range,generator
kwargs=Simple key-value pairs,With string keys explicitly quoted,Mixed types as values,Using variables as values,Empty dictionary

6.convert given dynamic data into list using flask and django.
7.convert given dynamic data into keyvalue pair structured as a two-element list using sqlite,flask,django
8.how to get data in list format from database in sqlite,flask,django
9.how to get data in dictionary format from database in flask django

  1. defination of fun and its advantage 11.pow,slice,sorted
  2. types of function==anonymous,regular,recursive.
  for l in item_list:
        squares.append(l ** 2)
Enter fullscreen mode Exit fullscreen mode
for l in args_list:    
        ans.append( l.upper() ) 
Enter fullscreen mode Exit fullscreen mode
  for key, value in kargs_list.items():    
        ans.append([key, value]) 
Enter fullscreen mode Exit fullscreen mode
def user_profile(**info):
    return [[k, v] for k, v in info.items()]
Enter fullscreen mode Exit fullscreen mode
settings = Setting.query.all()
values_list = [row.setting_value for row in settings]
Enter fullscreen mode Exit fullscreen mode
def function_args(*args):
    return [v.upper() for v in args]  # or any processing
Enter fullscreen mode Exit fullscreen mode
settings = Setting.objects.all()
values_list = [row.setting_value for row in settings]
Enter fullscreen mode Exit fullscreen mode
rows = cursor.fetchall()  # Each row is (key, value) tuple
# Convert to dictionary
data_dict = {key: value for key, value in rows}
Enter fullscreen mode Exit fullscreen mode
settings = Setting.query.all()
data_dict = {row.setting_name: row.setting_value for row in settings}
Enter fullscreen mode Exit fullscreen mode
settings = Setting.objects.all().values('setting_name', 'setting_value')
data_dict = {row['setting_name']: row['setting_value'] for row in settings}
Enter fullscreen mode Exit fullscreen mode
for key, value in kwargs.items():
        ans.append([key, value])
==============or=========================
def function_kwargs(**kwargs):
    return [[k, v] for k, v in kwargs.items()]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)