Functions in Python
Syntax of Function def function_name(arguments): """docstring""" statement(s) • Keyword def marks the start of function header. • arguments through which we pass values to a function. They are optional. • A colon (:) to mark the starting of function • Optional documentation string (docstring) to describe what the function does. • One or more valid python statements that make up the function body. Statements must have same indentation level (usually 4 spaces). • An optional return statement to return a value from the function.
Defining and Calling Functions Step 1: Declare the function with the keyword def followed by the function name. Step 2: Write the arguments inside the opening and closing parentheses of the function, and end the declaration with a colon. Step 3: Add the program statements to be executed. Step 4: End the function with/without return statement. Ex: def hello(): print("Hello, World!") #statements inside function hello() #function calling
Example of Function that takes one string arguments def greet(name): """This function greets to the person passed in as parameter""" print("Hello, " + name + ". Good morning!") greet('vani') #function calling Output: Hello, vani. Good morning! print(greet.__doc__) Output: This function greets to the person passed into the name parameter
return statement The return statement is used to exit a function and go back to the place from where it was called. the return statement itself is not present inside a function, then the function will return the None object. def absolute_value(num): if num >= 0: return num else: return -num print(absolute_value(2)) Output: 2 print(absolute_value(-4)) Output: 4
Return multiple values def add_numbers(x, y, z): a = x + y b = x + z c = y + z return a, b, c sums = add_numbers(1, 2, 3) print(sums) Output (3, 4, 5)
Functions exit immediately when they hit a return statement def loop_five(): for x in range(0, 25): print(x) if x == 5: # Stop function at x == 5 return print("This line will not execute.") loop_five()
Using main() as a Function def hello(): print("Hello, World!") def main(): print("This is the main function.") hello() main() Output: This is the main function. Hello, World!
def sum(): a=15 #local variable b=8 print("in fun", a) sum() print("outside", a) $python3 main.py in fun 15 Traceback (most recent call last): File "main.py", line 8, in <module> print("outside", a) NameError: name 'a' is not defined a=15 def sum(): b=8 print("in fun", a) sum() print("outside", a) $python3 main.py in fun 15 outside 15 a=15 def sum(): a=10 b=8 print("in fun", a) sum() print("outside", a) a=15 def sum(): global a a=10 b=8 print("in fun", a) sum() print("outside", a) Scope of a Variable: Local and Global Variables
In the next program we’ll declare a global variable and modify our original names() function so that the instructions are in two discrete functions. The first function, has_vowel() will check to see if the name string contains a vowel. The second function print_letters() will print each letter of the name string.
name = str(input('Enter your name: ')) # Declare global variable name for use in all functions # Define function to check if name contains a vowel def has_vowel(): if set('aeiou').intersection(name.lower()): print('Your name contains a vowel.') else: print('Your name does not contain a vowel.') def print_letters(): # Iterate over letters in name string for letter in name: print(letter) def main(): # Define main method that calls other functions has_vowel() print_letters() main() # calling main() function
Four types of function arguments. • Default Arguments • Required Arguments • Keyword Arguments • Arbitrary Arguments
Default arguments example Default values indicate that the function argument will take that value if no argument value is passed during function call. The default value is assigned by using assignment (=) operator. Here, msg parameter has a default value Good morning!. def greet(name, msg = "Good morning!"): print("Hello",name + ', ' + msg) greet("Kate") greet("Bruce","How do you do?")
Required Arguments Required arguments are the mandatory arguments of a function. def greet(name,msg): print("Hello",name + ', ' + msg) greet("Monica","Good morning!") >>> greet("Monica") # only one argument TypeError: greet() missing 1 required positional argument: 'msg'
Keyword arguments example The keywords are mentioned during the function call along with their corresponding values. These keywords are mapped with the function arguments so the function can easily identify the corresponding values even if the order is not maintained during the function call. def greet(name, msg): print("Hello",name + ', ' + msg) greet(msg = "How do you do?",name = "Bruce")
Variable number of arguments example we can have a design where any number of arguments can be passed based on the requirement. def greet(*names): for name in names: print("Hello",name) greet("Monica","Luke","Steve","John") Output Hello Monica Hello Luke Hello Steve Hello John
def sum(a,*b): for i in b: print(i) sum(5,6,7.3) # output: 6 7.3 def person(a,**b): for i,j in b.items(): print(i,j); person(5,age=18,mob=9542352) Output: age 18 mob 9542352

Functions in python3

  • 1.
  • 2.
    Syntax of Function deffunction_name(arguments): """docstring""" statement(s) • Keyword def marks the start of function header. • arguments through which we pass values to a function. They are optional. • A colon (:) to mark the starting of function • Optional documentation string (docstring) to describe what the function does. • One or more valid python statements that make up the function body. Statements must have same indentation level (usually 4 spaces). • An optional return statement to return a value from the function.
  • 3.
    Defining and CallingFunctions Step 1: Declare the function with the keyword def followed by the function name. Step 2: Write the arguments inside the opening and closing parentheses of the function, and end the declaration with a colon. Step 3: Add the program statements to be executed. Step 4: End the function with/without return statement. Ex: def hello(): print("Hello, World!") #statements inside function hello() #function calling
  • 4.
    Example of Functionthat takes one string arguments def greet(name): """This function greets to the person passed in as parameter""" print("Hello, " + name + ". Good morning!") greet('vani') #function calling Output: Hello, vani. Good morning! print(greet.__doc__) Output: This function greets to the person passed into the name parameter
  • 5.
    return statement The returnstatement is used to exit a function and go back to the place from where it was called. the return statement itself is not present inside a function, then the function will return the None object. def absolute_value(num): if num >= 0: return num else: return -num print(absolute_value(2)) Output: 2 print(absolute_value(-4)) Output: 4
  • 6.
    Return multiple values defadd_numbers(x, y, z): a = x + y b = x + z c = y + z return a, b, c sums = add_numbers(1, 2, 3) print(sums) Output (3, 4, 5)
  • 7.
    Functions exit immediatelywhen they hit a return statement def loop_five(): for x in range(0, 25): print(x) if x == 5: # Stop function at x == 5 return print("This line will not execute.") loop_five()
  • 8.
    Using main() asa Function def hello(): print("Hello, World!") def main(): print("This is the main function.") hello() main() Output: This is the main function. Hello, World!
  • 9.
    def sum(): a=15 #localvariable b=8 print("in fun", a) sum() print("outside", a) $python3 main.py in fun 15 Traceback (most recent call last): File "main.py", line 8, in <module> print("outside", a) NameError: name 'a' is not defined a=15 def sum(): b=8 print("in fun", a) sum() print("outside", a) $python3 main.py in fun 15 outside 15 a=15 def sum(): a=10 b=8 print("in fun", a) sum() print("outside", a) a=15 def sum(): global a a=10 b=8 print("in fun", a) sum() print("outside", a) Scope of a Variable: Local and Global Variables
  • 10.
    In the nextprogram we’ll declare a global variable and modify our original names() function so that the instructions are in two discrete functions. The first function, has_vowel() will check to see if the name string contains a vowel. The second function print_letters() will print each letter of the name string.
  • 11.
    name = str(input('Enteryour name: ')) # Declare global variable name for use in all functions # Define function to check if name contains a vowel def has_vowel(): if set('aeiou').intersection(name.lower()): print('Your name contains a vowel.') else: print('Your name does not contain a vowel.') def print_letters(): # Iterate over letters in name string for letter in name: print(letter) def main(): # Define main method that calls other functions has_vowel() print_letters() main() # calling main() function
  • 12.
    Four types offunction arguments. • Default Arguments • Required Arguments • Keyword Arguments • Arbitrary Arguments
  • 13.
    Default arguments example Defaultvalues indicate that the function argument will take that value if no argument value is passed during function call. The default value is assigned by using assignment (=) operator. Here, msg parameter has a default value Good morning!. def greet(name, msg = "Good morning!"): print("Hello",name + ', ' + msg) greet("Kate") greet("Bruce","How do you do?")
  • 14.
    Required Arguments Required argumentsare the mandatory arguments of a function. def greet(name,msg): print("Hello",name + ', ' + msg) greet("Monica","Good morning!") >>> greet("Monica") # only one argument TypeError: greet() missing 1 required positional argument: 'msg'
  • 15.
    Keyword arguments example Thekeywords are mentioned during the function call along with their corresponding values. These keywords are mapped with the function arguments so the function can easily identify the corresponding values even if the order is not maintained during the function call. def greet(name, msg): print("Hello",name + ', ' + msg) greet(msg = "How do you do?",name = "Bruce")
  • 16.
    Variable number ofarguments example we can have a design where any number of arguments can be passed based on the requirement. def greet(*names): for name in names: print("Hello",name) greet("Monica","Luke","Steve","John") Output Hello Monica Hello Luke Hello Steve Hello John
  • 17.
    def sum(a,*b): for iin b: print(i) sum(5,6,7.3) # output: 6 7.3 def person(a,**b): for i,j in b.items(): print(i,j); person(5,age=18,mob=9542352) Output: age 18 mob 9542352