Download presentation
Presentation is loading. Please wait.
1
Functions John R. Woodward
2
Functions A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing. As you already know, Python gives you many built-in functions like print(), etc. but you can also create your own functions. These functions are called user-defined functions.
3
Defining a Function Function blocks begin with the keyword def followed by the function name and parentheses ( ). Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses. The first statement of a function can be an optional statement - the documentation string of the function or docstring. The code block within every function starts with a colon (:) and is indented. The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None.
4
Docstring def add(x, y): """Return the sum of x and y.""" return x + y
help(add) Help on function add in module __main__: add(x, y) Return the sum of x and y. None
5
Syntax & Example def functionname( parameters ): function_suite
return [expression] The following function takes a string as input parameter and prints it on standard screen. def printme( str ): print str return
6
Argument does not need to be string
def printme( str ): print str return printme("cat") printme(5) printme([1,2,3])
7
Appending a list in a function
def changeme( mylist ): "This changes a passed list into this function" mylist.append([1,2,3,4]); print "Values inside the function: ", mylist return mylist = [10,20,30]; print "Values outside the function: ", mylist changeme( mylist );
8
Output Values outside the function: [10, 20, 30]
Values inside the function: [10, 20, 30, [1, 2, 3, 4]] Values outside the function: [10, 20, 30, [1, 2, 3, 4]]
9
Reassigning a list in a function
def changeme( mylist ): "This changes a passed list into this function" mylist = [1,2,3,4]; # This would assig new reference in mylist print "Values inside the function: ", mylist return mylist = [10,20,30]; print "Values outside the function: ", mylist changeme( mylist );
10
Output Values outside the function: [10, 20, 30]
Values inside the function: [1, 2, 3, 4]
11
Default arguments def printinfo( name, age = 35 ): "This prints passed info into this function" print "Name: ", name print "Age ", age return; printinfo( age=50, name="miki" ) printinfo( name="miki" )
12
Default arguments Name: miki Age 50 Age 35
def printinfo( name, age = 35 ): "This prints a passed info into this function" print "Name: ", name print "Age ", age return; printinfo( age=50, name="miki" ) printinfo( name="miki" ) Name: miki Age 50 Age 35
13
Variable-length arguments
def printinfo( arg1, *varArg ): "This prints a variable passed arguments" print "Output is: " print arg1 for var in varArg: print var return; printinfo( 10 ) printinfo( 70, 60, 50 )
14
Variable-length arguments
def printinfo( arg1, *varArg ): "This prints a variable passed arguments" print "Output is: " print arg1 for var in varArg: print var return; printinfo( 10 ) printinfo( 70, 60, 50 ) Output is: 10 70 60 50
15
What would this mean? def printinfo2( arg1, *vartuple, *vartuple2 ):
"This prints a variable passed arguments“ If your programming langauge did not have this, how could you achieve it? arrays
16
What type is varArg def printinfo( arg1, *varArg ):
print "Output is: " print arg1 print type(arg1) print type(varArg) if (len(varArg)>2): print varArg[2] return; printinfo( 70, 60, 50, 40 )
17
What type is varArg Output is: 70 <type 'int'>
def printinfo( arg1, *varArg ): print "Output is: " print arg1 print type(arg1) print type(varArg) if (len(varArg)>2): print varArg[2] return; printinfo( 70, 60, 50, 40 ) Output is: 70 <type 'int'> <type 'tuple'> 40
18
Functional Programming
In a few weeks we will do a few lectures on functional programming. Anonymous functions will be very useful. name = “John” # assigns print name # references Or we can do it directly Print “John” # we do not name a variable
19
Anonymous Functions These functions are called anonymous because they are not declared in the standard manner by using the def keyword. You can use the lambda keyword to create small anonymous functions. Lambda forms can take any number of arguments but return just one value in the form of an expression. They cannot contain commands or multiple expressions. An anonymous function cannot be a direct call to print because lambda requires an expression
20
Lambda example sum = lambda arg1, arg2: arg1 + arg2;
print "Value of total : ", sum(10,20) print "Value of total : ", sum(20,20) OUTPUT Value of total : 30 Value of total : 40
21
The return Statement def sum( arg1, arg2 ): total = arg1 + arg2 print "Inside the function : " print total return total; total = sum( 10, 20 ); print "Outside the function : "
22
output Inside the function : 30 Outside the function :
23
Multiple return statements
def max(x1, x2): if x1 > x2: return x1 else: return x2
24
None (Null in other languages)
def f(): print "in f() now" f()
25
None (Null in other languages)
def f(): print "in f() now" f() in f() now
26
None (Null in other languages)
def f(): print "in f() now" print f()
27
None (Null in other languages)
def f(): print "in f() now" print f() in f() now None
28
Do you return None def f(x): print "you passed in x " + str(x) y = f("argument") print "y = " + str(y) print y==None print type(None) print type(y)
29
Do you return None def f(x): print "you passed in x " + str(x) y = f("argument") print "y = " + str(y) print y==None print type(None) print type(y) you passed in x argument y = None True <type 'NoneType'>
30
eval On this website you can try Clojure (
31
eval On this website you can try Python (
32
Python Modules Simply, a module is a file consisting of Python code. A module can define functions, classes and variables. A module can also include runnable code.
33
In a file called aname.py
x = "hi there" def print_func( par ): print "Hello : ", par return
34
In a different file import aname print aname.x
aname.print_func("JOHN") We can now import that file and use it.
35
as import aname as an print an.x an.print_func("JOHN")
“as” means you can call the module a different name. You will often see import numpy as np
36
Are these the same? def printme( str ): def printme( str ): print str
return def printme( str ): print str
37
Are these the same? def printme( str ): def printme( str ): print str
return def printme( str ): print str Yes, the only difference is one has an explicit return statement and the other one does not. Which is better programming style. WHY
38
Are these the same? def printme( str ): def printme( str ): print str
return def printme( str ): print str
39
Are these the same? def printme( str ): def printme( str ): print str
return def printme( str ): print str Which is better programming style. WHY??? I would say the left side with explicit return, because you do not look like you forgot it. But not much difference really.
40
Are these the same? def printme( str ): def printme( str ): print str
return def printme( str ): print str return None Which is better programming style. WHY??? I would say the left side with explicit return, because you do not look like you forgot it. But not much difference really.
41
“” and None are different
name = "" print name print type(name) name = None
42
“” and None are different
name = "" print name print type(name) name = None <type 'str'> None <type 'NoneType'>
43
() and None are different
tupleNames = ("John", "David") print tupleNames print type(tupleNames) tupleNames = () tupleNames = None
44
() and None are different
tupleNames = ("John", "David") print tupleNames print type(tupleNames) tupleNames = () tupleNames = None ('John', 'David') <type 'tuple'> () None <type 'NoneType'>
45
A SINGLE TUPLE tupleNames = ("John") print tupleNames
print type(tupleNames)
46
A SINGLE TUPLE tupleNames = ("John") print tupleNames
print type(tupleNames) OUTPUT John <type 'str'>
47
Type of Single List listNames = ["John", "David"] print listNames
print type(listNames) listNames = ["John"]
48
Type of Single List ['John', 'David'] <type 'list'> ['John']
listNames = ["John", "David"] print listNames print type(listNames) listNames = ["John"] ['John', 'David'] <type 'list'> ['John']
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.