Monday 4 March 2019

Function use in Python

Function Calls

A callable object is an object that can accept some arguments (also called parameters) and possibly return an object (often a tuple containing multiple objects). A function is the simplest callable object in Python, but there are others, such as classes or certain class instances.

Defining Functions

A function is defined in Python by the following format:
def functionname(arg1, arg2, ...):
def functionname(arg1,arg2):
return arg1+arg2
t = functionname(24,24) # Result: 48
If a function takes no arguments, it must still include the parentheses, but without anything in them:
def functionname():

The arguments in the function definition bind the arguments passed at function invocation (i.e. when the function is called), which are called actual parameters, to the names given when the function is defined, which are called formal parameters. The interior of the function has no knowledge of the names given to the actual parameters; the names of the actual parameters may not even be accessible (they could be inside another function).

A function can 'return' a value, for example:
def square(x):
return x*x

A function can define variables within the function body, which are considered 'local' to the function. The locals together with the arguments comprise all the variables within the scope of the function. Any names within the function are unbound when the function returns or reaches the end of the function body. You can return multiple values as follows:

def first2items(list1):
return list1[0], list1[1]
a, b = first2items(["Hello", "world", "hi", "universe"])
print a + " " + b

 Declaring Arguments

When calling a function that takes some values for further processing, we need to send some values as Function Arguments. For example:
def find_max(a,b):
if(a > b):
print str(a) + " is greater than " + str(b)
elif(b > a):
print str(b) + " is greater than " + str(a)
find_max(30, 45) #Here (30, 45) are the arguments passing for finding max between this two numbers
The ouput will be: 45 is greater than 30

Default Argument Values
If any of the formal parameters in the function definition are declared with the format "arg = value," then you will have the option of not specifying a value for those arguments when calling the function. If you do not specify a value, then that parameter will have the default value given when the function executes.
def display_message(message, truncate_after=4):
print message[:truncate_after]
display_message("message", 6)

Variable-Length Argument Lists

Python allows you to declare two special arguments which allow you to create arbitrary-length argument lists. This means that each time you call the function, you can specify any number of arguments above a certain number.
def function(first,second,*remaining):

When calling the above function, you must provide value for each of the first two arguments. However, since the third parameter is marked with an asterisk, any actual parameters after the first two will be packed into a tuple and bound to "remaining."
def print_tail(first,*tail):
print tail
print_tail(1, 5, 2, "omega")
(5, 2, 'omega')

If we declare a formal parameter prefixed with two asterisks, then it will be bound to a dictionary containing any keyword arguments in the actual parameters which do not correspond to any formal parameters. For example, consider the function:
def make_dictionary(max_length=10, **entries):
return dict([(key, entries[key]) for i, key in enumerate(entries.keys()) if i < max_length])

If we call this function with any keyword arguments other than max_length, they will be placed in the dictionary "entries." If we include the keyword argument of max_length, it will be bound to the formal parameter max_length, as usual.
make_dictionary(max_length=2, key1=5, key2=7, key3=9)
{'key3': 9, 'key2': 7}

By Value and by Reference
Objects passed as arguments to functions are passed by reference; they are not being copied around. Thus, passing a large list as an argument does not involve copying all its members to a new location in memory. Note that even integers are objects. However, the distinction of by value and by reference present in some other programming languages often serves to distinguish whether the passed arguments can be actually changed by the called function and whether the calling function can see the changes.
Passed objects of mutable types such as lists and dictionaries can be changed by the called function and the changes are visible to the calling function. Passed objects of immutable types such as integers and strings cannot be changed by the called function; the calling function can be certain that the called function will not change them. For mutability, see also Data Types chapter.
def appendItem(ilist, item):
ilist.append(item) # Modifies ilist in a way visible to the caller
def replaceItems(ilist, newcontentlist):
del ilist[:] # Modification visible to the caller
ilist.extend(newcontentlist) # Modification visible to the caller ilist = [5, 6] # No outside effect; lets the local ilist point to a new list object, # losing the reference to the list object passed as an argument
def clearSet(iset):
def tryToTouchAnInteger(iint):
iint += 1 # No outside effect; lets the local iint to point to a new int object,
# losing the reference to the int object passed as an argument
print "iint inside:",iint # 4 if iint was 3 on function entry
list1 = [1, 2]
appendItem(list1, 3)
print list1 # [1, 2, 3]
replaceItems(list1, [3, 4])
print list1 # [3, 4]
set1 = set([1, 2])
clearSet(set1 )
print set1 # set([])
int1 = 3
print int1 # 3
Calling Functions
A function can be called by appending the arguments in parentheses to the function name, or an empty matched set of parentheses if the function takes no arguments.
bar(5, x)
A function's return value can be used by assigning it to a variable, like so:
x = foo()
y = bar(5,x)
As shown above, when calling a function you can specify the parameters by name and you can do so in any order
def display_message(message, start=0, end=4):
print message[start:end]
display_message("message", end=3)
This above is valid and start will have the default value of 0. A restriction placed on this is after the first named argument then all arguments after it must also be named. The following is not valid
display_message(end=5, start=1, "my message")
because the third argument ("my message") is an unnamed argument.


Post a Comment

Popular Posts


AI (27) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (114) C (77) C# (12) C++ (82) Course (60) Coursera (176) coursewra (1) Cybersecurity (22) data management (11) Data Science (89) Data Strucures (6) Deep Learning (9) Django (6) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (5) flutter (1) FPL (17) Google (19) Hadoop (3) HTML&CSS (46) IBM (25) IoT (1) IS (25) Java (92) Leet Code (4) Machine Learning (44) Meta (18) MICHIGAN (5) microsoft (3) Pandas (3) PHP (20) Projects (29) Python (742) Python Coding Challenge (194) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (2) Software (17) SQL (40) UX Research (1) web application (8)


Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses