Friday, 31 August 2018

Python Functions

Python Functions


Function Definition: Function is a group of statements which performs a specific task. It is also known as a Sub-routine or a Procedure or a Method.

In most programming languages two types of functions available:
  • Library Functions (also known as System defined function, for example print(), input(), etc.)
  • User defined functions (written by programmers, for example calculate(), find_area(), etc.)

Let's learn how Python Functions works.

Defining a Python Function

Following simple rules are followed while defining Python Functions:
  • Function blocks begin with the def keyword; followed by the function name and parentheses (  ).
  • Any number of parameters or arguments can be placed within function parentheses.
  • In the beginning of functions, writing a short comments about a function is one of the standard practice. 
  • Function code begins with a colon(:) and has indentation.
  • return statement at the end indicates end of function.

Syntax of Python Function


def function_name( arguments ):
   "function comments"
   function logic / code
   return

By default, arguments or parameters have a positional behavior and you need to write in the same order as they defined.

Python Function Example

The following python function prints line with a specified character as an parameter.

def print_line( chr ):
   "This function prints a line of given character"
   for i in range(0,15)
      print (chr)
   return

print_line('*')
print("")
print(" Welcome to Python Practicals ")
print_line('=')

Output of program

* * * * * * * * * * * * * * * 
 Welcome to Python Practicals 
= = = = = = = = = = = = = = = 

Examples of Popular Python Functions


1. Calculate Factorial

def factorial(n):
    """Calculate the factorial of a number."""
    if n == 0 or n == 1:
        return 1
    return n * factorial(n - 1)

# Example usage
print(factorial(5))  # Output: 120

2. Check if a Number is Prime

def is_prime(num):
    """Check if a number is prime."""
    if num <= 1:
        return False
    for i in range(2, int(num**0.5) + 1):
        if num % i == 0:
            return False
    return True

# Example usage
print(is_prime(7))  # Output: True

3. Find the Largest Element in a List

def find_largest(numbers):
    """Return the largest number in a list."""
    if not numbers:
        return None
    largest = numbers[0]
    for num in numbers:
        if num > largest:
            largest = num
    return largest

# Example usage
print(find_largest([3, 7, 2, 8, 5])) 
# Output: 8

4. Reverse a String

def reverse_string(s):
    """Reverse a given string."""
    return s[::-1]

# Example usage
print(reverse_string("hello"))  
# Output: 
"olleh"

5. Generate all permutations of a string using recursion

def string_permutations(s, prefix=""):
    """Generate all permutations of a string recursively."""
    if len(s) == 0:
        print(prefix)
    else:
        for i in range(len(s)):
            rem = s[:i] + s[i+1:]
            string_permutations(rem, prefix + s[i])

# Example usage
string_permutations("abc")   
# Output:
 abc
 acb
 bac
 bca
 cab
 cba

6. Fibonacci Sequence Generator

def fibonacci(n):
    """Generate a Fibonacci sequence up to n terms."""
    fib_sequence = [0, 1]
    for i in range(2, n):
        fib_sequence.append(fib_sequence[i - 1] + fib_sequence[i - 2])
    return fib_sequence[:n]

# Example usage
print(fibonacci(10)) 
 
# Output: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

No comments:

Post a Comment