📙
Python Programming
  • Python Programming
  • Installation and Setup
  • Part 1: Basics
    • Variables
      • Primitive Data Types
      • Secondary Data Types
    • Control Flow and Loop
    • Functions
    • Error Handling
    • Decorators
    • Constructor
    • Built-in Functions and Modules
    • Pythonic Code
    • Miscellaneous Functionalities
    • Understanding Checkpoint I
    • Python Problem Practice I
      • Solutions
  • Part 2: Level Up
    • Real Life Application I
    • Real Life Application II
    • OOP Concepts
    • Creating Library
    • Real Life Application III
  • Processing Related
    • Parallel Processing
    • Oreilly - High Performance Python
    • Memory Management
      • Memory Leak
      • String
      • Array
      • Dictionary
    • Ubuntu CPU and RAM
    • Time and Space Complexity
  • Data Structure
    • Data Structure Overview
    • Array
    • Stack
    • Queue
    • LinkedList
    • Hash-table and Hash-map
    • Recursion
    • Binary Tree
    • Heap Data Structure
    • Graphs
      • Python Graph Visualisation
    • Dynamic Programming
    • Problem Solving Techniques
    • Additional topics
Powered by GitBook
On this page
  1. Part 1: Basics

Functions

PreviousControl Flow and LoopNextError Handling

Last updated 4 years ago

Was this helpful?

CtrlK
  • Defining Functions
  • Arguments and Parameters
  • Types of Functions
  • Perform a Task
  • Return a Value
  • Arguments in Function
  • Keyword Argument
  • Default Argument
  • Xargs, Variable number of arguments
  • XXargs
  • Scope of a Function
  • Global Variable

Was this helpful?

Defining Functions

  • For defining a function in python we use def(define) followed by function_name() and colon

  • Make sure that the function name is meaningful and descriptive

  • Function names are generally given in snake_case in python

def greet():
    print("Hi there")
    print("Welcome abroad")
    
greet()

Arguments and Parameters

  • A parameter is an input that we define for our function

  • In the below example, first_name and last_name are parameters

  • While an argument is an actual value for a given parameter ("Ankit", "Choudhary" are arguments)

def greet(first_name,last_name):
    print(first_name + " " + last_name))
    print("Welcome aboard")  
    
greet("OoBA","Labs")

Types of Functions

Perform a Task

  • Below is a sample function in python

  • In Python, all functions by default return None values

def greet(first_name,last_name):
    print("Hi {} {}".format(first_name,last_name)) #Python2
    #print(f"Hi {first_name} {last_name}") #Python3
    print("Welcome aboard")
       
greet("OoBA","Labs")

Return a Value

def greet(first_name,last_name):
    return first_name + " " + last_name

full_name = greet("Ankit","Choudhary")
print(full_name) # prints "Ankit Choudhary"

Arguments in Function

  • Specifying the name of a parameter with an argument is called a keyword argument

  • For example: "number=1" is a keyword argument in the next example

Keyword Argument

def increment(number,by):
    return number + by

print(increment(number=1,by=2)) # prints 3

Default Argument

  • All the parameters which we define for a function are required by default

  • We can make a parameter optional by specifying the default value while defining the function

  • In the below given example "by" is having 1 as default value if no value is passed as an argument

  • All the optional parameters must be defined after the required parameters.

def increment(number,by = 1):
    return number + by

print(increment(number=1)) # print 2

Xargs, Variable number of arguments

  • We can pass a variable number of arguments to a function by using * before the parameter name

  • The variable arguments will be stored in a tuple and can be iterated.

  • Note that variable arguments parameter should be at the end of function parameters

def multiply(x,*numbers):
    print(x) # prints 2
    print(numbers) # prints (3,4,5)
    total = 1
    for number in numbers:
        total *= number
    return total
    
print(multiply(2,3,4,5)) # prints 60

XXargs

  • We can also pass multiple "key: value" pairs by using ** before the parameter name

  • Note that variable arguments parameter should be at the end of function parameters

def save_user(number,**user):
    print(number) # prints 1
    print(user) # prints dictionary with all key value pairs
    print(user["name"]) # "John"
        
save_user(1,id =1, name="John", age=22)

Scope of a Function

def greet(name):
    message = "a"
        
def send_mail(name):
    message = "b"

Global Variable

  • A Global variable is will be accessible throughout the file and inside each and every function

  • Global variables stay for a longer period of time in a program until it is garbage collected, so we should not use them often

  • If the same variable is defined in a function's scope, the local variable will override the global variable

  • Here in function greet, the global variable "message" will be used While in the function send_mail as message variable is defined locally so that will be used.

messge = "global variable"
def greet(name):
    print(messge)
        
def send_mail(name):
    message = "local variable"
    print(message)
    
greet("OoBA")
send_mail("OoBA")