Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
5 views

Python Tutorial_ Functions

This document is a tutorial on functions in Python, covering their syntax, usage, and different types of parameters including mandatory, optional, and arbitrary parameters. It explains how to define functions, return values, and the difference between arguments and parameters. Additionally, it discusses local and global variables, as well as how to handle an arbitrary number of parameters using tuple and keyword references.

Uploaded by

Sentinel
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Python Tutorial_ Functions

This document is a tutorial on functions in Python, covering their syntax, usage, and different types of parameters including mandatory, optional, and arbitrary parameters. It explains how to define functions, return values, and the difference between arguments and parameters. Additionally, it discusses local and global variables, as well as how to handle an arbitrary number of parameters using tuple and keyword references.

Uploaded by

Sentinel
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

Python Course

Home Python 2 Tutorial Python 3 Tutorial Advanced Topics Numerical Programming Machine Learning Tkinter Tutorial Contact

Previous Chapter: Formatted output with string modulo and the format method
Next Chapter: Recursion and Recursive Functions

Functions

Syntax
Follow Bernd Klein,
the author of this
The concept of a function is one of the most important ones in mathematics. A common usage of functions in computer languages is to implement mathematical functions. Such a
website, at Google+:
function is computing one or more results, which are entirely determined by the parameters passed to it.
Bernd Klein on
Google
Python 3 In the most general sense, a function is a structuring element in programming languages to group a set of statements so they can be utilized more than once in a program. The
only way to accomplish this without functions would be to reuse code by copying it and adapt it to its different context. Using functions usually enhances the comprehensibility
Tutorial Bernd Klein on
and quality of the program. It also lowers the cost for development and maintenance of the software.
Facebook
The Origins of
Functions are known under various names in programming languages, e.g. as subroutines, routines, procedures, methods, or subprograms.
Python
Starting with Search this website:
A function in Python is defined by a def statement. The general syntax looks like this:
Python: The
Interactive Shell def function-name(Parameter list): Go
Executing a statements, i.e. the function body
Script This topic in German
The parameter list consists of none or more parameters. Parameters are called arguments, if the function is called. The function body consists of indented statements. The / Deutsche
Indentation
function body gets executed every time the function is called. Übersetzung:
Data Types and Parameter can be mandatory or optional. The optional parameters (zero or more) must follow the mandatory parameters. Funktionen
Variables
Operators Function bodies can contain one or more return statement. They can be situated anywhere in the function body. A return statement ends the execution of the function call and "returns" the result, i.e. the value of
Python 3
Sequential Data the expression following the return keyword, to the caller. If the return statement is without an expression, the special value None is returned. If there is no return statement in the function code, the function ends,
Types: Lists and when the control flow reaches the end of the function body and the value "None" will be returned.
This is a tutorial in
Strings Example:
Python3, but this
List def fahrenheit(T_in_celsius): chapter of our course
Manipulations """ returns the temperature in degrees Fahrenheit """ is available in a
Shallow and return (T_in_celsius * 9 / 5) + 32 version for Python
Deep Copy 2.x as well: Functions
for t in (22.6, 25.8, 27.3, 29.8): in Python 2.x
Dictionaries print(t, ": ", fahrenheit(t))
Sets and Frozen
Sets The output of this script looks like this: Classroom
An Extensive Training
Example Using
22.6 : 72.68 Courses
25.8 : 78.44
Sets 27.3 : 81.14
The goal of this
input via the 29.8 : 85.64
website is to provide
keyboard
educational material,
Conditional allowing you to learn
Statements Python on your own.
Loops, while
Optional Parameters
Nevertheless, it is
Loop faster and more
Functions can have optional parameters, also called default parameters. Default parameters are parameters, which don't have to be given, if the function is called. In this case, the default values are used. We will efficient to attend a
For Loops
demonstrate the operating principle of default parameters with an example. The following little script, which isn't very useful, greets a person. If no name is given, it will greet everybody: "real" Python course
Difference
between in a classroom, with
def Hello(name="everybody"):
an experienced
interators und """ Greets a person """
print("Hello " + name + "!") trainer. So why not
Iterables
attend one of the live
Output with Print Python courses in
Hello("Peter")
Formatted output Hello() Strasbourg, Paris,
with string Luxembourg,
modulo and the The output looks like this: Amsterdam, Zürich /
format method Zurich, Vienna /
Hello Peter! Wien, London, Berlin,
Functions Hello everybody!
Munich, Hamburg,
Recursion and
Frankfurt, Stuttgart,
Recursive
or Lake Constance by
Functions Bernd Klein, the
Parameter Docstring author of this
Passing in tutorial?
Functions The first statement in the body of a function is usually a string, which can be accessed with function_name.__doc__
Namespaces This statement is called Docstring. You can book on-site
Global and Local Example: classes at your
Variables company or
def Hello(name="everybody"): organization, e.g. in
Decorators
""" Greets a person """ England, Switzerland,
Memoization with print("Hello " + name + "!") Austria, Germany,
Decorators France, Belgium, the
Read and Write print("The docstring of the function Hello: " + Hello.__doc__)
Netherlands,
Files Luxembourg, Poland,
The output:
Modular UK, Italy and other
Programming The docstring of the function Hello: Greets a person locations in Europe
and Modules and in Canada.
Packages in
We had courses in
Python
the following cities:
Regular Keyword Parameters
Amsterdam (The
Expressions Netherlands), Berlin
Regular Using keyword parameters is an alternative way to make function calls. The definition of the function doesn't change. (Germany), Bern
Expressions, An example: (Switzerland), Basel
Advanced (Switzerland), Zurich
def sumsub(a, b, c=0, d=0): (Switzerland),
Lambda return a - b + c - d
Operator, Filter, Locarno
print(sumsub(12,4)) (Switzerland), Den
Reduce and Map
print(sumsub(42,15,d=10)) Haag (The Hague),
List
Hamburg, Toronto
Comprehension (Canada), Edmonton
Keyword parameters can only be those, which are not used as positional arguments. We can see the benefit in the example. If we hadn't keyword parameters, the second call to function would have needed all four
Iterators and arguments, even though the c needs just the default value: (Canada), Munich
Generators (Germany) and many
Exception print(sumsub(42,15,0,10)) other cities.
Handling
Tests, DocTests, Contact us so we can
define and find the
UnitTests
Return Values best course
Object Oriented
curriculum to meet
Programming your needs, and
In our previous examples, we used a return statement in the function sumsub but not in Hello. So, we can see that it is not mandatory to have a return statement. But what will be returned, if we don't explicitly
Class and schedule course
give a return statement. Let's see:
Instance sessions to be held at
Attributes def no_return(x,y): your location.
Properties vs. c = x + y
getters and
res = no_return(4,5)
setters print(res) Skilled Python
Inheritance Programmers
Multiple If we start this little script, None will be printed, i.e. the special value None will be returned by a return-less function. None will also be returned, if we have just a return in a function without an expression:
Inheritance You are looking for
def empty_return(x,y): experienced Python
Magic Methods c = x + y developers or
and Operator return
programmers? We
Overloading can help you, please
res = empty_return(4,5)
OOP, Inheritance contact us.
print(res)
Example
Slots Otherwise the value of the expression following return will be returned. In the next example 9 will be printed: Quote of the
Classes and Day:
Class Creation def return_sum(x,y):
c = x + y
Road to return c "If you want to
Metaclasses accomplish
Metaclasses res = return_sum(4,5) something in the
print(res) world, idealism is not
Metaclass Use
Case: Count enough - you need to
choose a method that
Function Calls
works to achieve the
Abstract Classes
Returning Multiple Values goal." (Richard
Stallmann)
A function can return exactly one value, or we should better say one object. An object can be a numerical value, like an integer or a float. But it can also be e.g. a list or a dictionary. So, if we have to return, for
Difference example, 3 integer values, we can return a list or a tuple with these three integer values. This means that we can indirectly return multiple values. The following example, which is calculating the Fibonacci boundary
between for a positive number, returns a 2-tuple. The first element is the Largest Fibonacci Number smaller than x and the second component is the Smallest Fibonacci Number larger than x. The return value is immediately
Arguments and stored via unpacking into the variables lub and sup:
Parameters
def fib_intervall(x): Data Protection
""" returns the largest fibonacci Declaration
Argument and
number smaller than x and the lowest
parameter are often fibonacci number higher than x"""
seen and used as if x < 0: Data Protection
synonyms. But there return -1 Declaration
is a difference. In (old,new, lub) = (0,1,0)
Python and many while True:
other programming if new < x:
languages, lub = new
(old,new) = (new,old+new)
parameters are the
else:
comma separated return (lub, new)
identifiers between
the parenthesis while True:
following the function x = int(input("Your number: "))
name. While if x <= 0:
arguments are the break
(lub, sup) = fib_intervall(x)
comma separated list
print("Largest Fibonacci Number smaller than x: " + str(lub))
between the print("Smallest Fibonacci Number larger than x: " + str(sup))
parenthesis in a
function call.

Function Local and Global Variables in Functions

The word function Variable names are by default local to the function, in which they get defined.
can mean a lot of
things. It can be a def f():
mathematical print(s) Output:
function. It can mean s = "Python" Python
the purpose, role or f()
use of a thing: The
function of a hammer
is to hit nails into a def f():
wall or wood. The s = "Perl"
actions and activities print(s)
Output:
assigned to or Perl
required or expected s = "Python" Python
of a person or group; f()
"the function of a print(s)
lecturer". Function
can define a relation,
like "Wisdom is a def f():
function of age!" print(s)
s = "Perl" If we execute the previous script, we get the error message:
print(s)
UnboundLocalError: local variable 's' referenced before assignment
The variable s is ambigious in f(), i.e. in the first print in f() the global s could be used with the value "Python". After this we define a
This website is local variable s with the assignment s = "Perl"
s = "Python"
supported by: f()
print(s)
Linux and Python
Courses
def f(): We made the variable s global inside of the script on the left side. Therefore anything we do to s inside of the function body of f is
global s done to the global variable s outside of f.
print(s)
s = "dog"
print(s) Output:
s = "cat" cat
f() dog
print(s) dog

Arbitrary Number of Parameters

There are many situations in programming, in which the exact number of necessary parameters cannot be determined a-priori. An arbitrary parameter number can be accomplished in Python with so-called tuple
references. An asterisk "*" is used in front of the last parameter name to denote it as a tuple reference. This asterisk shouldn't be mistaken with the C syntax, where this notation is connected with pointers.
Example:

def arithmetic_mean(first, *values):


""" This function calculates the arithmetic mean of a non-empty
arbitrary number of numerical values """

return (first + sum(values)) / (1 + len(values))

print(arithmetic_mean(45,32,89,78))
print(arithmetic_mean(8989.8,78787.78,3453,78778.73))
print(arithmetic_mean(45,32))
print(arithmetic_mean(45))

Results:

61.0
42502.3275
38.5
45.0

This is great, but we have still have one problem. You may have a list of numerical values. Like, for example,

x = [3, 5, 9]

You cannot call it with

arithmetic_mean(x)

because "arithmetic_mean" can't cope with a list. Calling it with

arithmetic_mean(x[0], x[1], x[2])

is cumbersome and above all impossible inside of a program, because list can be of arbitrary length.

The solution is easy. We add a star in front of the x, when we call the function.

arithmetic_mean(*x)

This will "unpack" or singularize the list.

A practical example:
We have a list

my_list = [('a', 232),


('b', 343),
('c', 543),
('d', 23)]

We want to turn this list into the following list:

[('a', 'b', 'c', 'd'),


(232, 343, 543, 23)]

This can be done by using the *-operator and the zip function in the following way:

list(zip(*my_list))

Arbitrary Number of Keyword Parameters

In the previous chapter we demonstrated how to pass an arbitrary number of positional parameters to a function. It is also possible to pass an arbitrary number of keyword parameters to a function. To this purpose,
we have to use the double asterisk "**"

>>> def f(**kwargs):


... print(kwargs)
...
>>> f()
{}
>>> f(de="German",en="English",fr="French")
{'fr': 'French', 'de': 'German', 'en': 'English'}
>>>

One use case is the following:

>>> def f(a,b,x,y):


... print(a,b,x,y)

>>> d = {'a':'append', 'b':'block','x':'extract','y':'yes'}
>>> f(**d)
('append', 'block', 'extract', 'yes')

Previous Chapter: Formatted output with string modulo and the format method
Next Chapter: Recursion and Recursive Functions

© 2011 - 2018, Bernd Klein, Bodenseo; Design by Denise Mitchinson adapted for python-course.eu by Bernd Klein

You might also like