November 27, 2019

Python Functions

Functions in Python

def my_function ():
"""This function will do..."""
print ...

def foo(bar):
...
return value

def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
  while 1:
    ok = raw_input(prompt)
    if ok in ('y', 'ye', 'yes'): return 1
    if ok in ('n', 'no'): return 0
    retries = retries - 1
    if retries < 0: raise IOError, 'error'
    print complaint

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

def total(*manyargs, **manymoreargs):
return(sum(manyargs))

scope of local & global variables, in Python:-
x = 50
def func():
    global x
    print('x is', x)
    x = 2
    print('Changed global x to', x)

functions with default values:-
def func(a, b=9):
# Default values are provided in function definition.
Arguments with default values should be at the right side of argument list.
func(25, b=24)
func(b=50, a=100)
func(94) # if parameter is omitted, default value is used

order of arguments is important.

def print_max(x, y):

    '''Prints the maximum of two numbers.

    The two values must be integers.'''

    ...

print(print_max.__doc__)

A function can call itself, this is called recursion.
Function can return multiple values using tuples.

Lambda expressions:-
function_name = lambda input_parameters  :  output_parameters
str_to_list=lambda x: x.split()
large = lambda x, y : x if x >y else y
proper = lambda x, y: x[0].upper()+x[1:] +' '+ y[0].upper()+y[1:]

Related Python Articles:  Python Abbreviations  File Handling in Python


No comments:

Post a Comment