DEV Community

Phylis Jepchumba
Phylis Jepchumba

Posted on

Day 3: Python Functions.

Day 3 of 30DaysOfPython

♠️What is a Function in Python?
♠️How to define and call a function in Python
♠️Function Parameters Vs Arguments
♠️Type of arguments in Function
♠️Recursive and Lambda Function

Function is a block of organized, reusable code that is used to perform a single, related action.

Syntax

def functionname( parameters ):
   "function_docstring"
   function_suite
   return [expression]
Enter fullscreen mode Exit fullscreen mode

From the above syntax:

  • def keyword is used to declare and define a function. def is a short form for "define function".
  • functionname is used to uniquely identify the function.
  • Parameters (arguments) through which we pass values to a function.
  • : marks the end of function header.
  • "function_docstring" describes what the function does.
  • return statement returns the value from the function.

Example

def myFun(): # define function name  
    print(" Welcome to my blog")  
myFun() # call to print the statement  
Enter fullscreen mode Exit fullscreen mode
Parameters Vs Arguments.
Parameters

They are the variables that are used within the function and are declared in the function header.

Arguments
  • Arguments are the variables that are passed to the function for execution.
  • They are the actual values that are passed to the function header.
  • The argument values are assigned to the parameters of the function and therefore the function can process these parameters for the final output.

Example to differentiate parameters and arguments.

def addNumbers(a, b):
    sum =a + b
    print("The sum is " ,sum)
addNumbers(2,9)
Enter fullscreen mode Exit fullscreen mode

from the above example;

  • We have a function called addNumbers which contains two values inside the parenthesis a, and b. These two values are called parameters.
  • We have passed two values along with the function 2 and 9. These values are called arguments.
Type of arguments in Function.
  • Default arguments.

Default arguments are values provided while defining function and are assigned using the assignment operator =.
Example

def addNumbers (a=2,b=5):
    result = a+b
    return result
Enter fullscreen mode Exit fullscreen mode

The above script defines a functionaddNumbers() with two default arguments a and b. The default value for argument a is set to 2 and argument b is set to 5.

  • Keyword arguments.

Keyword arguments are values that, when passed into a function, are identifiable by specific parameter names.
A keyword argument is preceded by a parameter and the assignment operator, = .
The order of keyword arguments doesn't matter.

  • Positional arguments.
    Positional arguments are values that are passed into a function based on the order in which the parameters were listed during the function definition.

  • Arbitrary positional arguments.

For arbitrary positional argument, an asterisk (*) is placed before a parameter in function definition which can hold non-keyword variable-length arguments.

A single asterisk signifies elements of a tuple.

def team(*members):
    for member in members:
        print(member)

team("Phylis", "Mary")
Enter fullscreen mode Exit fullscreen mode

Output

Phylis
Mary
Enter fullscreen mode Exit fullscreen mode
  • Arbitrary keyword arguments. For arbitrary keyword arguments, a double asterisk (**) is placed before a parameter in a function which can hold keyword variable-length arguments. Double asterisks signify elements of a dictionary.

example

def fn(**a):
    for i in a.items():
        print (i)
fn(name="Korir",course="Computer science",Hobby="coding")
Enter fullscreen mode Exit fullscreen mode

output

('name', 'Korir')
('course', 'Computer science')
('Hobby', 'coding')
Enter fullscreen mode Exit fullscreen mode
Python Recursive Functions.

A recursive function is a function that calls itself and always has condition that stops calling itself.

Where do we use recursive functions in programming?

To divide a big problem that’s difficult to solve into smaller problems that are easier-to-solve.
In data structures and algorithms like trees, graphs, and binary searches.
Recursive Function Examples
1.Count Down to Zero

countdown()takes a positive number as an argument and prints the numbers from the specified argument down to zero:

def countdown(n):
    print(n)
    if n == 0:
        return  # Terminate recursion
    else:
        countdown(n - 1)  # Recursive call
countdown(5)
Enter fullscreen mode Exit fullscreen mode

Output

5
4
3
2
1
0
Enter fullscreen mode Exit fullscreen mode

2.Calculating the sum of a sequence
Recursive functions makes a code shorter and readable.
Suppose we want to calculate the sum of sequence from 1 to n instead of using for loop with range() function we can use recursive function.

def sum(n):
    if n > 0:
        return n + sum(n - 1)
    return 0
result = sum(100)
print(result)
Enter fullscreen mode Exit fullscreen mode
Python Lambda Expressions.

A lambda function is a small anonymous function that can take any number of arguments, but can only have one expression.
Syntax

lambda arguments : expression
Enter fullscreen mode Exit fullscreen mode

Examples:

def times(n):
    return lambda x: x * n
double = times(2)
result = double(2)
print(result)
result = double(3)
print(result)
Enter fullscreen mode Exit fullscreen mode

Output

4
6
Enter fullscreen mode Exit fullscreen mode

From the above example times() function returns a function which is a lambda expression.

Top comments (2)

Collapse
 
patricktingen profile image
Patrick Tingen

Cool! I like series like this, thanks!

What would make your series more findable for others is when it would have a landing page that explains the purpose and provide links to all posts.

Collapse
 
phylis profile image
Phylis Jepchumba

Okey thanks for your feedback....will add the links