Function Basics. Function In this chapter, we will move on to explore a set of additional statements that create functions of our own function (subroutine,

Slides:



Advertisements
Similar presentations
Lilian Blot PART V: FUNCTIONS Core elements Autumn 2013 TPOP 1.
Advertisements

Lilian Blot CORE ELEMENTS PART V: FUNCTIONS PARAMETERS & VARIABLES SCOPE Lecture 5 Autumn 2014 TPOP 1.
Chapter Modules CSC1310 Fall Modules Modules Modules are the highest level program organization unit, usually correspond to source files and.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
Chapter 5 Functions.
Chapter 7 - Functions. Functions u Code group that performs single task u Specification refers to what goes into and out of function u Design refers to.
An Introduction to Python – Part IV Dr. Nancy Warter-Perez.
Practical Python Richard P. Muller May 18, Fundamentals.
Chapter 6: User-Defined Functions I
Guide To UNIX Using Linux Third Edition
CHAPTER 6 Functions. Function Overview We’ve used built-in functions:  Examples:  print(“ABC”, x+10, sep=“:”)  round(x * 5, 2)  pygame.draw.circle(screen,
Chapter 6: Function. Scope of Variable A scope is a region of the program and broadly speaking there are three places, where variables can be declared:
Builtins, namespaces, functions. There are objects that are predefined in Python Python built-ins When you use something without defining it, it means.
Prof. Alfred J Bird, Ph.D., NBCT Office – McCormack 3rd floor 607.
Introduction to Python 2 Dr. Bernard Chen University of Central Arkansas PyArkansas 2011.
C Functions Programmer-defined functions – Functions written by the programmer to define specific tasks. Functions are invoked by a function call. The.
18-2 Understand “Scope” of an Identifier Know the Storage Classes of variables and functions Related Chapter: ABC 5.10, 5.11.
Chapter 6 Functions 1. Opening Problem 2 Find the sum of integers from 1 to 10, from 20 to 37, and from 35 to 49, respectively.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 3 Simple.
Chapter 06 (Part I) Functions and an Introduction to Recursion.
Chapter 6: User-Defined Functions
Chapter 9: MuPAD Programming II Procedures MATLAB for Scientist and Engineers Using Symbolic Toolbox.
 2005 Pearson Education, Inc. All rights reserved. 1 Methods Called functions or procedures in other languages Modularize programs by separating its tasks.
Web Database Programming Week 3 PHP (2). Functions Group related statements together to serve “a” specific purpose –Avoid duplicated code –Easy maintenance.
Chapter Function Basics CSC1310 Fall Function function (subroutine, procedure)a set of statements different inputs (parameters) outputs In.
Chapter 8 More On Functions. "The Practice of Computing Using Python", Punch & Enbody, Copyright © 2013 Pearson Education, Inc. First cut, scope.
Functions Chapter 6. Function Overview We’ve used built-in functions: – Examples: print(“ABC”, x+10, sep=“:”) round(x * 5, 2) pygame.draw.circle(screen,
With Python.  One of the most useful abilities of programming is the ability to manipulate files.  Python’s operations for file management are relatively.
Overview Intro to functions What are functions? Why use functions? Defining functions Calling functions Documenting functions Top-down design Variable.
Chapter 3 Functions, Events, and Control Structures JavaScript, Third Edition.
COMPUTER PROGRAMMING. Functions’ review What is a function? A function is a group of statements that is executed when it is called from some point of.
Chapter 14 Advanced Function Topics CSC1310 Fall 2009.
Python Functions.
Exam 1 Review Instructor – Gokcen Cilingir Cpt S 111, Sections 6-7 (Sept 19, 2011) Washington State University.
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
1 Computer Science of Graphics and Games MONT 105S, Spring 2009 Lecture 17 Parameters, Scope, Return values.
Structure Programming Lecture 8 Chapter 5&6 - Function – part I 12 December 2015.
Jim Havrilla. Invoking Python Just type “python –m script.py [arg]” or “python –c command [arg]” To exit, quit() or Control-D is used To just use the.
INLS 560 – F UNCTIONS Instructor: Jason Carter.
Chapter Functions 6. Modular Programming 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules.
Exceptions in C++. Exceptions  Exceptions provide a way to handle the errors generated by our programs by transferring control to functions called handlers.
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
Passing Parameters. 2 home back first prev next last What Will I Learn? List the types of parameter modes Create a procedure that passes parameters Identify.
Guide to Programming with Python Chapter Six Functions: The Tic-Tac-Toe Game.
12. MODULES Rocky K. C. Chang November 6, 2015 (Based on from Charles Dierbach. Introduction to Computer Science Using Python and William F. Punch and.
Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions Local Variables Global Variables Default Parameters.
Chapter 7 - Functions. Functions u Code group that performs single task u Specification refers to what goes into and out of function u Design refers to.
6. FUNCTIONS Rocky K. C. Chang October 4, 2015 (Adapted from John Zelle’s slides)
1 Chapter 8 Scope, Lifetime, and More on Functions CS185/09 - Introduction to Programming Caldwell College.
ITM 3521 ITM 352 Functions. ITM 3522 Functions  A function is a named block of code (i.e. within {}'s) that performs a specific set of statements  It.
Functions. What is a Function?  We have already used a few functions. Can you give some examples?  Some functions take a comma-separated list of arguments.
Lecture III Syntax ● Statements ● Output ● Variables ● Conditions ● Loops ● List Comprehension ● Function Calls ● Modules.
Friend Class Friend Class A friend class can access private and protected members of other class in which it is declared as friend. It is sometimes useful.
Organization of Programming Languages
Functions.
Python Functions Part I Presented by : Sharmin Abdullah
Rocky K. C. Chang 15 November 2018 (Based on Dierbach)
G. Pullaiah College of Engineering and Technology
Topics Introduction to Functions Defining and Calling a Function
1-6 Midterm Review.
COMPUTER PROGRAMMING SKILLS
Functions So far we've been using functions from the builtin module, which is automatically loaded in most cases. Occasionally we've accessed functions.
The Three Attributes of an Identifier
ITM 352 Functions.
Corresponds with Chapter 5
Learning Python 5th Edition
Presentation transcript:

Function Basics

Function In this chapter, we will move on to explore a set of additional statements that create functions of our own function (subroutine, procedure)a set of statements different inputs (parameters)outputs In simple terms, a function (subroutine, procedure) is a package of code (a set of statements) that can be called repeatedly with different inputs (parameters) and outputs each time.

Why Function? Functions serve two primary development roles: Code Reuse: Functions allows us to group and generalize code to be used arbitrarily many times after it is defined Procedure decomposition: Functions also provide a tool for splitting systems into pieces--- one function for each subtask

“def” statement The def statement creates a function object and assigns it to a name. the def general format: def ( ): the statement block becomes the function’s body-- -the code Python executes each time the function is called

Function Example def star(): num=int(raw_input("please input a number")) for i in range(num+1): print '*' * i star() # we call “star” function once

Function Example def star(): num=int(raw_input("please input a number")) for i in range(num+1): print '*' * i for i in range(3): star() # we call “star” function 3 times here

“def” statement Now we try to see the def format with arguments: def (arg1, arg2, …, argN):

Function Example with one Argument def star(num): for i in range(num+1): print '*' * i for i in range(3): num = num=int(raw_input("please input a number")) star(num) # we call “star” function 3 times here

Function Example with 2 arguments def multiply(x,y): value=x*y print value multiply(4,10) multiply(3,6) multiply(2,18)

Function Example with 3 arguments def multiply(x,y,z): value=x*y*z print value multiply(4,10,1) #generate result 40 multiply(4,10) #error message: multiply() takes exactly 3 arguments (2 given)

“def” statement Now we try to see the def format with arguments and return function: def (arg1, arg2, …, argN): … return

Function Example def times(x,y): value=x*y return value aa = times(2,4) #aa=8 aa = times(3.14,4)#aa=12.56 aa = times(“ha”,4)#aa=“hahahaha” list=[1,2,3,4] aa = times(list,2) #aa=[1,2,3,4,1,2,3,4]

Function Example def times(x,y): for i in range(len(x)): x[i]=x[i]*y aa=[1,2,3,4] times(aa, 2)

Scope Rules Namespace Namespace is the place where names live scope The location of name’s assignment defines the scope of the name visibility def def Names defined inside a def can be seen only by the code inside the def def def Names defined inside a def not clash with variables outside the def, even if the same name is used elsewhere

Scope Basics The enclosing module is a global scope. The global scope spans a single file only. Each call to a function is a new local scope. Assigned names are local, unless declared global. All names are either local, or global, or built-ins. LEGB Rule: Name resolution: the LEGB Rule: name references search at most at fours scopes: Local Enclosing functions (if any) Global Built-in.

Global Statement Global names must be declared only if the assigned in a function. Global names may be referenced in a function without being declared. global global >>>X=88 >>>def func(): global X X=99 >>>func() >>>print X

Passing Arguments Arguments are passed by automatically assigning objects to a local names. (“by value”) Assigning to arguments names inside a function doesn’t affect the caller (“by value”). (“by pointer”) Changing a mutable object argument in a function may impact a caller (“by pointer”). >>>def change(x, y): x=2; y[0]=‘hi’ >>>x=1;L=[1,’a’] >>>change(x,L) >>>print x,L

Simulate Output Parameters return return sends back any sort of object It could return multiple valus, by packaging them in tuple. >>>def swap(x,y): y=x+y x=y-x y=y-x return x,y >>>a,b=swap(3,5) >>>print a,b

Arguments Matching Modes Positional: Positional: matched left to right. Keywords: name=value Keywords: matched by the argument name. Callers can specify which argument is to receive a value by specifying the argument’s name in the call with a name=value syntax. Varargs: * Varargs: catch unmatched positional or keyword arguments. Function can use special arguments preceded with a * characters to collect arbitrarily extra arguments. Defaults: name=value Defaults: specify values for arguments that are not passed using a name=value syntax.

Arguments Matching Modes Positional: Positional: matched left to right def func(name) func(value) Keywords: Keywords: matched by the argument name def func(name) func(name=value) Varargs: Varargs: catch unmatched arguments. def func(*name) # match remaining positional # args(in a tuple) # args(in a tuple) def func(**name) # match remaining keyword # args(in a dictionary) # args(in a dictionary) Defaults: Defaults: specify values for arguments that are not passed def func(name=value)

Keyword Examples >>> def f(a,b,c): print a,b,c >>>f(1,2,3) # by position >>>f(c=3,b=2,a=1) # keyword args >>>f(1,c=3,b=2) #mix positional and keyword args

Keyword and Default Examples Keywords Keywords: Self-documenting In conjunction with defaults >>>def f(a,b=2,c=1):print a,b,c >>>f(1) >>>f(a=1) >>>f(2,4) >>>f(2,4,5) >>>f(2,c=6)

Arbitrary Arguments Examples positional tuple Collect unmatched positional arguments into a tuple: >>>def f(*args): print args >>>f() >>>f(1) >>>f(1,2,3,4) keyword dictionary Collect unmatched keyword arguments into a dictionary: >>>def f(**args): print args >>>f() >>>f(a=1,b=2) >>>f(b=1,c=2,a=3,d=4 )

Flexible Signature >>>def f(a,*pargs,**krags): print a,pargs,krags >>>f(1,2,3,x=1,y=‘234’)