Functions in Python. The indentation matters… First line with less indentation is considered to be outside of the function definition. Defining Functions.

Slides:



Advertisements
Similar presentations
Optional Static Typing Guido van Rossum (with Paul Prescod, Greg Stein, and the types-SIG)
Advertisements

FUNCTIONS. • Function เป็นชื่อของชุดคำสั่ง • Syntax ของฟังก์ชั่น Def NAME (PARAMETERS ): STATEMENTS • NAME เป็นชื่อของฟังก์ชัน สามารถใช้ชื่อใดๆ ตามกฎการตั้งชื่อ.
Variables, Environments and Closures. Overview We will Touch on the notions of variable extent and scope Introduce the notions of lexical scope and.
Chapter 7: User-Defined Functions II
Python 2 Some material adapted from Upenn cis391 slides and other sources.
Chapter 9 Subprograms Sections 1-5 and 9. Copyright © 2007 Addison-Wesley. All rights reserved. 1–2 Introduction Two fundamental abstraction facilities.
CSE341: Programming Languages Lecture 8 Lexical Scope and Function Closures Dan Grossman Fall 2011.
1 Scheme Scheme is a functional language. Scheme is based on lambda calculus. lambda abstraction = function definition In Scheme, a function is defined.
CSE (c) S. Tanimoto, 2007 Python Introduction 1 Introduction to Python for Artificial Intelligence Outline: Why Python? Interactive programming,
1 Scheme Although Scheme is syntactically a simple language, it supports sophisticated modeling: higher-order functions are a powerful tool in describing.
1 Functional languages (e.g. Scheme, ML) Scheme is a functional language. Scheme is based on lambda calculus. lambda abstraction = function definition.
Introduction to Python II CIS 391: Artificial Intelligence Fall, 2008.
Introduction to Python II CSE-391: Artificial Intelligence University of Pennsylvania Matt Huenerfauth January 2005.
CSC 9010: Natural Language Processing
Python 3 Some material adapted from Upenn cis391 slides and other sources.
1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.
CSC1018F: Object Orientation, Exceptions and File Handling Diving into Python Ch. 5&6 Think Like a Comp. Scientist Ch
Introduction to Python Basics of the Language. Install Python Find the most recent distribution for your computer at:
Builtins, namespaces, functions. There are objects that are predefined in Python Python built-ins When you use something without defining it, it means.
Python – Part 3 Functions 1. Function Calls Function – A named sequence of statements that performs a computation – Name – Sequence of statements “call”
Functional Programming in Scheme and Lisp. Overview In a functional programming language, functions are first class objects. You can create them, put.
Functional Programming and Lisp. Overview In a functional programming language, functions are first class objects. In a functional programming language,
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
An Introduction to Python Blake Brogdon. What is Python?  Python is an interpreted, interactive, object-oriented programming language. (from python.org)
Oct 15, 2007Sprenkle - CS1111 Objectives Creating your own functions.
Python functional programming. Functions are first-class objects Functions can be used as any other datatype, eg: Arguments to function Return values.
CPSC 230 Computers and Programming I Spring 2003 Dr. Lynn Lambert.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
Built-in Data Structures in Python An Introduction.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 7 Clicker Questions September 22, 2009.
Chapter 8 More On Functions. "The Practice of Computing Using Python", Punch & Enbody, Copyright © 2013 Pearson Education, Inc. First cut, scope.
ECE122 Feb. 22, Any question on Vehicle sample code?
Objects & Dynamic Dispatch CSE 413 Autumn Plan We’ve learned a great deal about functional and object-oriented programming Now,  Look at semantics.
Classes In C++ 1. What is a class Can make a new type in C++ by declaring a class. A class is an expanded concept of a data structure: instead of holding.
Data TypestMyn1 Data Types The type of a variable is not set by the programmer; rather, it is decided at runtime by PHP depending on the context in which.
Functions CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Topics: Function Intitution Algorithm Example Function Definition (and Indentation) Function Call Naming and Binding Local Variables Function Arguments.
C463 / B551 Artificial Intelligence Dana Vrajitoru Python.
Python Functions.
Functions CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Slide 1 Chapter 8 Operator Overloading, Friends, and References.
An Introduction. What is Python? Interpreted language Created by Guido Van Rossum – early 90s Named after Monty Python
Python – Part 3 Functions 1. Getting help Start the Python interpreter and type help() to start the online help utility. Or you can type help(print) to.
Python Primer 1: Types and Operators © 2013 Goodrich, Tamassia, Goldwasser1Python Primer.
CS 261 – Data Structures Introduction to C Programming.
By Austin Laudenslager AN INTRODUCTION TO PYTHON.
1 Printing in Python Every program needs to do some output This is usually to the screen (shell window) Later we’ll see graphics windows and external files.
Functions  A Function is a self contained block of one or more statements or a sub program which is designed for a particular task is called functions.
Function and Function call Functions name programs Functions can be defined: def myFunction( ): function body (indented) Functions can be called: myFunction(
MIT-AITI: Functions Defining and Invoking Functions Functions as Data Function Scope: The call Object Function Arguments: The arguments objects Function.
Functions CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
LECTURE 2 Python Basics. MODULES So, we just put together our first real Python program. Let’s say we store this program in a file called fib.py. We have.
1 Python Data Structures LING 5200 Computational Corpus Linguistics Martha Palmer.
Tarik Booker CS 242. What we will cover…  Functions  Function Syntax  Local Variables  Global Variables  The Scope of Variables  Making Functions.
Introduction to Python
Functions CIS 40 – Introduction to Programming in Python
Methods The real power of an object-oriented programming language takes place when you start to manipulate objects. A method defines an action that allows.
Chapter 3 Introduction to Classes, Objects Methods and Strings
Variables, Environments and Closures
Introduction to Python
Python 2 Some material adapted from Upenn cis391 slides and other sources.
CSC1018F: Intermediate Python
Python Tutorial for C Programmer Boontee Kruatrachue Kritawan Siriboon
Python Primer 1: Types and Operators
G. Pullaiah College of Engineering and Technology
CISC101 Reminders All assignments are now posted.
COMPUTER PROGRAMMING SKILLS
Functions John R. Woodward.
Python fundamental.
Presentation transcript:

Functions in Python

The indentation matters… First line with less indentation is considered to be outside of the function definition. Defining Functions No header file or declaration of types of function or arguments def get_final_answer(filename): “““Documentation String””” line1 line2 return total_counter Function definition begins with “def.” Function name and its arguments. The keyword ‘return’ indicates the value to be sent back to the caller. Colon.

Python and Types  Dynamic typing: Python determines the data types of variable bindings in a program automatically  Strong typing: But Python’s not casual about types, it enforces the types of objects  For example, you can’t just append an integer to a string, but must first convert it to a string x = “the answer is ” # x bound to a string y = 23 # y bound to an integer. print x + y # Python will complain!

Calling a Function  The syntax for a function call is: >>> def myfun(x, y): return x * y >>> myfun(3, 4) 12  Parameters in Python are Call by Assignment Old values for the variables that are parameter names are hidden, and these variables are simply made to refer to the new values All assignment in Python, including binding function parameters, uses reference semantics.

Functions without returns  All functions in Python have a return value, even if no return line inside the code  Functions without a return return the special value None None is a special constant in the language None is used like NULL, void, or nil in other languages None is also logically equivalent to False The interpreter’s REPL doesn’t print None

Function overloading? No.  There is no function overloading in Python Unlike C++, a Python function is specified by its name alone The number, order, names, or types of arguments cannot be used to distinguish between two functions with the same name Two different functions can’t have the same name, even if they have different arguments  But: see operator overloading in later slides (Note: van Rossum playing with function overloading for the future )

Default Values for Arguments  You can provide default values for a function’s arguments  These arguments are optional when the function is called >>> def myfun(b, c=3, d=“hello”): return b + c >>> myfun(5,3,”hello”) >>> myfun(5,3) >>> myfun(5) All of the above function calls return 8

Keyword Arguments  Can call a function with some/all of its arguments out of order as long as you specify their names >>> def foo(x,y,z): return(2*x,4*y,8*z) >>> foo(2,3,4) (4, 12, 32) >>> foo(z=4, y=2, x=3) (6, 8, 32) >>> foo(-2, z=-4, y=-3) (-4, -12, -32)  Can be combined with defaults, too >>> def foo(x=1,y=2,z=3): return(2*x,4*y,8*z) >>> foo() (2, 8, 24) >>> foo(z=100) (2, 8, 800)

Functions are first-class objects Functions can be used as any other datatype, eg: Arguments to function Return values of functions Assigned to variables Parts of tuples, lists, etc >>> def square(x): return x*x >>> def applier(q, x): return q(x) >>> applier(square, 7) 49

Lambda Notation  Python’s lambda creates anonymous functions >>> applier(lambda z: z * 42, 7) 14  Note: only one expression in the lambda body; its value is always returned  Python supports functional programming idioms: map, filter, closures, continuations, etc.

Lambda Notation Be careful with the syntax >>> f = lambda x,y : 2 * x + y >>> f at 0x87d30> >>> f(3, 4) 10 >>> v = lambda x: x*x(100) >>> v at 0x87df0> >>> v = (lambda x: x*x)(100) >>> v 10000

Example: composition >>> def square(x): return x*x >>> def twice(f): return lambda x: f(f(x)) >>> twice >>> quad = twice(square) >>> quad at 0x87d30> >>> quad(5) 625

Example: closure >>> def counter(start=0, step=1): x = [start] def _inc(): x[0] += step return x[0] return _inc >>> c1 = counter() >>> c2 = counter(100, -10) >>> c1() 1 >>> c2() 90

map, filter, reduce >>> def add1(x): return x+1 >>> def odd(x): return x%2 == 1 >>> def add(x,y): return x + y >>> map(add1, [1,2,3,4]) [2, 3, 4, 5] >>> map(+,[1,2,3,4],[100,200,300,400]) map(+,[1,2,3,4],[100,200,300,400]) ^ SyntaxError: invalid syntax >>> map(add,[1,2,3,4],[100,200,300,400]) [101, 202, 303, 404] >>> reduce(add, [1,2,3,4]) 10 >>> filter(odd, [1,2,3,4]) [1, 3]

Python functional programming

Functions are first-class objects Functions can be used as any other datatype, eg: Arguments to function Return values of functions Assigned to variables Parts of tuples, lists, etc >>> def square(x): return x*x >>> def applier(q, x): return q(x) >>> applier(square, 7) 49

Lambda Notation Python’s lambda creates anonymous functions >>> lambda x: x + 1 at 0x1004e6ed8> >>> f = lambda x: x + 1 >>> f at 0x1004e6f50> >>> f(100) 101

Lambda Notation Be careful with the syntax >>> f = lambda x,y: 2 * x + y >>> f at 0x87d30> >>> f(3, 4) 10 >>> v = lambda x: x*x(100) >>> v at 0x87df0> >>> v = (lambda x: x*x)(100) >>> v 10000

Lambda Notation Limitations  Note: only one expression in the lambda body; Its value is always returned  The lambda expression must fit on one line!  Lambda will probably be deprecated in future versions of python Guido is not a lambda fanboy

Functional programming  Python supports functional programming idioms  Builtins for map, reduce, filter, closures, continuations, etc.  These are often used with lambda

Example: composition >>> def square(x): return x*x >>> def twice(f): return lambda x: f(f(x)) >>> twice >>> quad = twice(square) >>> quad at 0x87d30> >>> quad(5) 625

Example: closure >>> def counter(start=0, step=1): x = [start] def _inc(): x[0] += step return x[0] return _inc >>> c1 = counter() >>> c2 = counter(100, -10) >>> c1() 1 >>> c2() 90

map >>> def add1(x): return x+1 >>> map(add1, [1,2,3,4]) [2, 3, 4, 5] >>> map(lambda x: x+1, [1,2,3,4]) [2, 3, 4, 5] >>> map(+, [1,2,3,4], [100,200,300,400]) map(+,[1,2,3,4],[100,200,300,400]) ^ SyntaxError: invalid syntax

map  + is an operator, not a function  We can define a corresponding add function >>> def add(x, y): return x+y >>> map(add,[1,2,3,4],[100,200,300,400]) [101, 202, 303, 404]  Or import the operator moduleoperator >>> from operator import * >>> map(add, [1,2,3,4], [100,200,300,400]) [101, 202, 303, 404] >>> map(sub, [1,2,3,4], [100,200,300,400]) [-99, -198, -297, -396]

filter, reduce  Python has buiting for reduce and filter >>> reduce(add, [1,2,3,4]) 10 >>> filter(odd, [1,2,3,4]) [1, 3]  The map, filter and reduce functions are also at risk 