learning python - part 2 - chapter 5

32
Learning Python Part 2 | Winter 2014 | Koosha Zarei | QIAU

Upload: koosha-zarei

Post on 19-May-2015

151 views

Category:

Software


0 download

DESCRIPTION

Learning python series based on "Beginning Python Using Python 2.6 and P - James Payne" book presented by Koosha Zarei.

TRANSCRIPT

Page 1: Learning python - part 2 - chapter 5

Learning PythonPart 2 | Winter 2014 | Koosha Zarei | QIAU

Page 2: Learning python - part 2 - chapter 5

Part 2Chapter 5 – Functions

Page 3: Learning python - part 2 - chapter 5

3February 2014Learning Python | Part 2- Chapter 5 | Koosha Zarei

Putting Your Program into Its Own FileFunctions: Grouping Code under a NameFunction Arguments

Required argumentsKeyword argumentsDefault argumentsVariable-length arguments

The return StatementScope of Variables

Content

Page 4: Learning python - part 2 - chapter 5

4February 2014Learning Python | Part 2- Chapter 5 | Koosha Zarei

Putting Your Program into Its Own File

Putting codes into several files...

Page 5: Learning python - part 2 - chapter 5

5February 2014Learning Python | Part 2- Chapter 5 | Koosha Zarei

Functions: Grouping Code under a Name

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.

To create a named function that will contain your code, you use the word def, which you can think of as defining a functional block of code.

Page 6: Learning python - part 2 - chapter 5

6February 2014Learning Python | Part 2- Chapter 5 | Koosha Zarei

Functions: Grouping Code under a Name

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.

Page 7: Learning python - part 2 - chapter 5

7February 2014Learning Python | Part 2- Chapter 5 | Koosha Zarei

Functions: Grouping Code under a Name

Defining a FunctionHere are simple rules to define a function in Python.

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.

Page 8: Learning python - part 2 - chapter 5

8February 2014Learning Python | Part 2- Chapter 5 | Koosha Zarei

Functions: Grouping Code under a Name

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.

Page 9: Learning python - part 2 - chapter 5

9February 2014Learning Python | Part 2- Chapter 5 | Koosha Zarei

Functions: Grouping Code under a Name

def functionname( parameters ): "function_docstring" function_suite return [expression]

def printme( str ): "This prints a passed string into this function" print str return

Page 10: Learning python - part 2 - chapter 5

10February 2014Learning Python | Part 2- Chapter 5 | Koosha Zarei

Functions: Grouping Code under a Name

# Function definition is heredef printme( str ): "This prints a passed string into this function" print str; return;

# Now you can call printme functionprintme("I'm first call to user defined function!");printme("Again second call to the same function");

I'm first call to user defined function!Again second call to the same function

Calling a Function

Page 11: Learning python - part 2 - chapter 5

11February 2014Learning Python | Part 2- Chapter 5 | Koosha Zarei

Functions: Grouping Code under a Name

if test:def func(): # Define func this way

...else:

def func(): # Or else this way...

...Func() # Call the version selected and built

def Executes at Runtime

Page 12: Learning python - part 2 - chapter 5

12February 2014Learning Python | Part 2- Chapter 5 | Koosha Zarei

Functions: Grouping Code under a Name

def is much like an = statement: it simply assigns a name at runtime. Unlike in compiled languages such as C, Python functions do not need to be fully defined before the program runs. More generally, defs are not evaluated until they are reached and run, and the code inside defs is not evaluated until the functions are later called.

Page 13: Learning python - part 2 - chapter 5

13February 2014Learning Python | Part 2- Chapter 5 | Koosha Zarei

Functions: Grouping Code under a Name

Pass by reference vs valueAll parameters (arguments) in the Python language are passed by reference. It means if you change what a parameter refers to within a function, the change also reflects back in the calling function.

Page 14: Learning python - part 2 - chapter 5

14February 2014Learning Python | Part 2- Chapter 5 | Koosha Zarei

Functions: Grouping Code under a Name

Pass by reference vs valueIf you pass a mutable object into a method, the method gets a reference to that same object and you can mutate it to your heart's delight, but if you rebind the reference in the method, the outer scope will know nothing about it, and after you're done, the outer reference will still point at the original object.If you pass an immutable object to a method, you still can't rebind the outer reference, and you can't even mutate the object.

Page 15: Learning python - part 2 - chapter 5

15February 2014Learning Python | Part 2- Chapter 5 | Koosha Zarei

Functions: Grouping Code under a Name

def try_to_change_list_contents(the_list): print 'got', the_list the_list.append('four') print 'changed to', the_list

outer_list = ['one', 'two', 'three']

print 'before, outer_list =', outer_listtry_to_change_list_contents(outer_list)print 'after, outer_list =', outer_list

before, outer_list = ['one', 'two', 'three']got ['one', 'two', 'three']changed to ['one', 'two', 'three', 'four']after, outer_list = ['one', 'two', 'three', 'four']

Pass by reference vs value

Page 16: Learning python - part 2 - chapter 5

16February 2014Learning Python | Part 2- Chapter 5 | Koosha Zarei

Functions: Grouping Code under a Name

Pass by reference vs valuedef try_to_change_list_reference(the_list): print 'got', the_list the_list = ['and', 'we', 'can', 'not', 'lie'] print 'set to', the_list

outer_list = ['we', 'like', 'proper', 'English']

print 'before, outer_list =', outer_listtry_to_change_list_reference(outer_list)print 'after, outer_list =', outer_list

before, outer_list = ['we', 'like', 'proper', 'English']got ['we', 'like', 'proper', 'English']set to ['and', 'we', 'can', 'not', 'lie']after, outer_list = ['we', 'like', 'proper', 'English']

Page 17: Learning python - part 2 - chapter 5

17February 2014Learning Python | Part 2- Chapter 5 | Koosha Zarei

Functions: Grouping Code under a Name

Pass by reference vs valuedef try_to_change_string_reference(the_string): print 'got', the_string the_string = 'In a kingdom by the sea' print 'set to', the_string

outer_string = 'It was many and many a year ago'

print 'before, outer_string =', outer_stringtry_to_change_string_reference(outer_string)print 'after, outer_string =', outer_string

before, outer_string = It was many and many a year agogot It was many and many a year agoset to In a kingdom by the seaafter, outer_string = It was many and many a year ago

Page 18: Learning python - part 2 - chapter 5

18February 2014Learning Python | Part 2- Chapter 5 | Koosha Zarei

Function ArgumentsWe can call a function by using the following types of formal arguments:

Required argumentsKeyword argumentsDefault argumentsVariable-length arguments

Page 19: Learning python - part 2 - chapter 5

19February 2014Learning Python | Part 2- Chapter 5 | Koosha Zarei

Function ArgumentsRequired arguments:

Required arguments are the arguments passed to a function in correct positional order. Here, the number of arguments in the function call should match exactly with the function definition

Page 20: Learning python - part 2 - chapter 5

20February 2014Learning Python | Part 2- Chapter 5 | Koosha Zarei

Function ArgumentsRequired arguments:

# Function definition is heredef printme( str ): "This prints a passed string into this function" print str; return;

# Now you can call printme functionPrintme();

Traceback (most recent call last): File "test.py", line 11, in <module> printme();TypeError: printme() takes exactly 1 argument (0 given)

Page 21: Learning python - part 2 - chapter 5

21February 2014Learning Python | Part 2- Chapter 5 | Koosha Zarei

Function ArgumentsKeyword arguments:

Keyword arguments are related to the function calls. When you use keyword arguments in a function call, the caller identifies the arguments by the parameter name.This allows you to skip arguments or place them out of order because the Python interpreter is able to use the keywords provided to match the values with parameters.

Page 22: Learning python - part 2 - chapter 5

22February 2014Learning Python | Part 2- Chapter 5 | Koosha Zarei

Function ArgumentsKeyword arguments:

# Function definition is heredef printinfo( name, age ): "This prints a passed info into this function" print "Name: ", name; print "Age ", age; return;

# Now you can call printinfo functionprintinfo( age=50, name="miki" );

Name: mikiAge 50

Page 23: Learning python - part 2 - chapter 5

23February 2014Learning Python | Part 2- Chapter 5 | Koosha Zarei

Function ArgumentsDefault arguments:

A default argument is an argument that assumes a default value if a value is not provided in the function call for that argument.

Page 24: Learning python - part 2 - chapter 5

24February 2014Learning Python | Part 2- Chapter 5 | Koosha Zarei

Function ArgumentsDefault arguments:

# Function definition is heredef printinfo( name, age = 35 ): "This prints a passed info into this function" print "Name: ", name; print "Age ", age; return;

# Now you can call printinfo functionprintinfo( age=50, name="miki" );printinfo( name="miki" );

Name: mikiAge 50Name: mikiAge 35

Page 25: Learning python - part 2 - chapter 5

25February 2014Learning Python | Part 2- Chapter 5 | Koosha Zarei

Function ArgumentsVariable-length arguments:

You may need to process a function for more arguments than you specified while defining the function. These arguments are called variable-length arguments and are not named in the function definition, unlike required and default arguments.

Page 26: Learning python - part 2 - chapter 5

26February 2014Learning Python | Part 2- Chapter 5 | Koosha Zarei

Function ArgumentsVariable-length arguments:

General syntaxAn asterisk (*) is placed before the variable name that will hold the values of all non-keyword variable arguments. This tuple remains empty if no additional arguments are specified during the function call.

def functionname([formal_args,] *var_args_tuple ): "function_docstring" function_suite return [expression]

Page 27: Learning python - part 2 - chapter 5

27February 2014Learning Python | Part 2- Chapter 5 | Koosha Zarei

Function ArgumentsVariable-length arguments:

# Function definition is heredef printinfo( arg1, *vartuple ): "This prints a variable passed arguments" print "Output is: " print arg1 for var in vartuple: print var return;

# Now you can call printinfo functionprintinfo( 10 );Printinfo( 70, 60, 50 );

Output is:10Output is:706050

Page 28: Learning python - part 2 - chapter 5

28February 2014Learning Python | Part 2- Chapter 5 | Koosha Zarei

The return StatementThe 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.

Page 29: Learning python - part 2 - chapter 5

29February 2014Learning Python | Part 2- Chapter 5 | Koosha Zarei

The return Statement

# Function definition is heredef sum( arg1, arg2 ): # Add both the parameters and return them." total = arg1 + arg2 print "Inside the function : ", total return total;

# Now you can call sum functiontotal = sum( 10, 20 );print "Outside the function : ", total

Inside the function : 30Outside the function : 30

Page 30: Learning python - part 2 - chapter 5

30February 2014Learning Python | Part 2- Chapter 5 | Koosha Zarei

Scope of VariablesAll variables in a program may not be accessible at all locations in that program. This depends on where you have declared a variable.The scope of a variable determines the portion of the program where you can access a particular identifier. There are two basic scopes of variables in Python:

Global variablesLocal variables

Page 31: Learning python - part 2 - chapter 5

31February 2014Learning Python | Part 2- Chapter 5 | Koosha Zarei

Scope of VariablesVariables that are defined inside a function body have a local scope, and those defined outside have a global scope.This means that local variables can be accessed only inside the function in which they are declared, whereas global variables can be accessed throughout the program body by all functions. When you call a function, the variables declared inside it are brought into scope.

Page 32: Learning python - part 2 - chapter 5

32February 2014Learning Python | Part 2- Chapter 5 | Koosha Zarei

Scope of Variables

total = 0; # This is global variable.# Function definition is heredef sum( arg1, arg2 ): # Add both the parameters and return them." total = arg1 + arg2; # Here total is local variable. print "Inside the function local total : ", total return total;

# Now you can call sum functionsum( 10, 20 );print "Outside the function global total : ", total

Inside the function local total : 30Outside the function global total : 0