Overview Intro to functions What are functions? Why use functions? Defining functions Calling functions Documenting functions Top-down design Variable.

Slides:



Advertisements
Similar presentations
Chapter Modules CSC1310 Fall Modules Modules Modules are the highest level program organization unit, usually correspond to source files and.
Advertisements

Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
An Introduction to Python – Part IV Dr. Nancy Warter-Perez May 19, 2005.
Working with JavaScript. 2 Objectives Introducing JavaScript Inserting JavaScript into a Web Page File Writing Output to the Web Page Working with Variables.
An Introduction to Python – Part IV Dr. Nancy Warter-Perez.
Guide To UNIX Using Linux Third Edition
Guide To UNIX Using Linux Third Edition
Introduction to Unix (CA263) Introduction to Shell Script Programming By Tariq Ibn Aziz.
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
Python Programming Fundamentals
CIS Computer Programming Logic
Functions Part I (Syntax). What is a function? A function is a set of statements which is split off into a separate entity that can be used like a “new.
Builtins, namespaces, functions. There are objects that are predefined in Python Python built-ins When you use something without defining it, it means.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Python Modules An Introduction. Introduction A module is a file containing Python definitions and statements. The file name is the module name with the.
1 CSC 221: Introduction to Programming Fall 2012 Functions & Modules  standard modules: math, random  Python documentation, help  user-defined functions,
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 5 Functions.
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.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design First Edition by Tony Gaddis.
Input, Output, and Processing
Chapter 6: User-Defined Functions
Oct 15, 2007Sprenkle - CS1111 Objectives Creating your own functions.
Chapter Function Basics CSC1310 Fall Function function (subroutine, procedure)a set of statements different inputs (parameters) outputs In.
CPS120: Introduction to Computer Science Functions.
CPS120: Introduction to Computer Science Lecture 14 Functions.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Introducing Python CS 4320, SPRING Resources We will be following the Python tutorialPython tutorial These notes will cover the following sections.
Chapter 3 Functions, Events, and Control Structures JavaScript, Third Edition.
CSC 110 Using Python [Reading: chapter 1] CSC 110 B 1.
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
C++ / G4MICE Course Session 2 Basic C++ types. Control and Looping Functions in C Function/method signatures and scope.
FUNCTIONS. Topics Introduction to Functions Defining and Calling a Void Function Designing a Program to Use Functions Local Variables Passing Arguments.
INLS 560 – F UNCTIONS Instructor: Jason Carter.
Python Let’s get started!.
Functions Chapter 6. Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules Function: a collection.
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 Basics. Function In this chapter, we will move on to explore a set of additional statements that create functions of our own function (subroutine,
General Computer Science for Engineers CISC 106 Lecture 12 James Atlas Computer and Information Sciences 08/03/2009.
Functions Part I (Syntax). What is a function? A function is a set of statements which is split off into a separate entity that can be used like a “new.
Review Expressions and operators Iteration – while-loop – for-loop.
1. COMPUTERS AND PROGRAMS Rocky K. C. Chang September 6, 2015 (Adapted from John Zelle’s slides)
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.
Modules. Modules Modules are the highest level program organization unit, usually correspond to source files and serve as libraries of tools. Each file.
Functions in C++ Top Down Design with Functions. Top-down Design Big picture first broken down into smaller pieces.
Programming Fundamentals Enumerations and Functions.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
STRUCTURED PROGRAMMING Complete C++ Program. Content 2  Main Function  Preprocessor directives  User comments  Escape characters  cout statement.
Python’s Modules Noah Black.
Topics Introduction to Functions Defining and Calling a Void Function
Variables A variable is a placeholder for a value. It is a named memory location where that value is stored. Use the name of a variable to access or update.
Functions CIS 40 – Introduction to Programming in Python
Functions.
User-Defined Functions
CHAPTER FOUR Functions.
Starting Out with Programming Logic & Design
Chapter 3 Simple Functions
Chapter 3 Introduction to Classes, Objects Methods and Strings
Topics Introduction to File Input and Output
Chapter 4 void Functions
Topics Introduction to Functions Defining and Calling a Void Function
Rocky K. C. Chang 15 November 2018 (Based on Dierbach)
Topics Introduction to Functions Defining and Calling a Function
Starting Out with Programming Logic & Design
Python Modules.
Programming Languages and Paradigms
Topics Introduction to File Input and Output
SPL – PS1 Introduction to C++.
Presentation transcript:

Overview Intro to functions What are functions? Why use functions? Defining functions Calling functions Documenting functions Top-down design Variable scope and functions Parameters and arguments Global variables and constants Intro to Modules What are modules? Why use modules? Importing and reloading Scope re-visited (Namespaces) Useful modules sys module and sys.argv Module name and __main__

What is a Function? A function is a named sequence of statements that exists within a program to perform a specific task Some are built-in to Python – dir(), help(), str(), int(), float(), input(), raw_input(), etc.built-in to Python dir()help()str() int()float()input()raw_input() Some are provided in other modules (e.g. math)math Others you will code yourself …

Why use functions? DRY – Don’t Repeat Yourself Breaks long sequence of statements into function calls with names that convey what the group of statements do Code is easier (faster) to: Read Reuse Test Facilitates teamwork vs.

Defining functions Function definitions are composed of a function header (first line – including “:” !) and indented function block (body) with one or more statements Function names cannot Be a Python keyword Contain spaces Begin with a number or special character (except _ ) Be called before they are defined Function names are camelCase in Python (PascalCase in C#) Verb clauses describing task (e.g. getPopulationData) CaSE SenSItIve Syntax: def functionName([params]): # Function Header pass # Function [return someObject] # body

Calling functions Functions are called by name followed by parentheses (That may or may not contain arguments depending on whether or not the function definition contains parameters – more later)

Parameters and arguments A parameter is a variable that receives an argument passed to a function. A parameter is local variable to the function definition An argument is data passed to a function when it is called. messageText = parameter “I love spam” = argument

Multiple parameters and arguments

Variable scope and functions Variable scope = the parts of a program that can access (“see”) the variable. Local = accessible inside a function = can reuse variable names in different functions

Global variables and constants Global = accessible to all functions in a program file Limit the use of global variables !!!! They make debugging difficult and life miserable Use global constants where possible (UPPERCASE names).

Function with return

Return as short-circuit for function If return statement is executed in a function, the interpreter returns to statement that made the function call. No other lines in the function are executed.

Use clear function and variable names Most function names should be verb phrases not noun phrases. Variable names should convey what their value is. Boolean functions (return bool) should ask a yes/no question.

Documenting a Function Single-line string (single or double quoted) or multi-line string (triple quoted) immediately following the function definition statement.

Top-down design Break overall task into sub-tasks Break sub-tasks into sub-tasks if possible When complete, write “leaf” functions and work back to trunk (testing as you go) Call list

Incremental development Start with a simple test and function skeleton. Run test repeatedly as you debug function under test.

Overview Intro to functions What are functions? Why use functions? Defining functions Calling functions Documenting functions Top-down design Variable scope and functions Parameters and arguments Global variables and constants Intro to Modules What are modules? Why use modules? Importing and reloading Scope re-visited (Namespaces) Useful modules sys module and sys.argv Module name and __main__

What are Modules? Modules are most typically.py or pyc files but can be DLL, etc Many modules and packages (groups of modules) shipped with Python (e.g. sys, os, math, turtle, etc.) Local modules (in same folder as running.py) override other modules in folders. Example: arcgisscripting.py in local folder will override C:\Program Files\ArcGIS\bin\arcgisscripting.dll  this is NOT a good thing.

Why use Modules? Code reuse Saves code permanently to disk Can be referenced (imported) by multiple client modules Define data and methods that can be used in programs Namespace partitioning Seals up names to avoid name clashes … e.g. two modules can have functions with the same name

- If you run a module as a program, the built-in __name__ attribute contains __main__. - If you import, __name__ contains the name of the module (no.py extension). - Convention is to put this block at the end of the module. How: Module contents and structure Most modules have one or more of the attributes shown below

import / from import … Import is only run once / module / Python session If you edit the module file with external editor and save, and you are in the same Python session, then the updated file WILL NOT BE IMPORTED! Using from import means you do not have to qualify the names with the module name del () removes names from program B.py run twice …

reload(module) The reload() function forces a module to reload – run its code. In an active session, Python is not aware of updates in imported modules Really useful during program development Should not be used with stable modules

import steps Find the module’s file Search folders in following order: Folder containing the program PYTHONPATH directories (if it is set) Standard library directories Compile it to byte code (maybe) If.py newer than.pyc and if file is imported Run the module’s code to build the objects it defines }

Structuring a Python program a.py b.pyc.py Std Library modules Top-level module that controls program flow. Imports b. b and c import each other … not usually a good thing and may import 0 or more of the standard library modules and 0 or more “other” modules Other modules

Namespaces

Scope rules Python searches for names in LEGB order and stops at the first name it finds (i.e. Local x takes precedence over EGB Local: in a function and not declared global (e.g. global x ) Enclosing functions: nested functions Not covered in this course Global (module): names at top-level of module Built-in: names in Python built-in names module (e.g. open, range, etc.)

Built-in & Standard Python library modules Built-in functions can be called without importing any module Standard Python Library modules must be imported to gain access to functions, etc.

Some useful Python Modules glob math os os.path shutil sys zipfile

sys module & command line args (sys.argv) Command line args are stored in sys.argv

sys.exit([arg]) The exit function in stops execution of a Python program

os and os.path module Access to operating system properties / operations Get/Set environment variables, get current directory, creating/deleting directories, path/file info, split/join paths Three ways to specify paths in Python:

os.path module (splitting/joining paths)

glob - Filename globbing utility The glob module finds all the pathnames matching a specified pattern

shutil – file/dir tree copy/move/delete(rm) The shutil module offers a number of high-level operations on files and collections of files. In particular, functions are provided which support file copying and removal. Implementation of shutil.copytree

Other modules zipfile module – working with.zip files (read, write, get info, etc.) The urllib2 module defines functions and classes which help in opening URLs (mostly HTTP)

main() Most programs contain a function called main that has the a program’s mainline logic That is, standalone statements and calls to other functions in a logical order.

__main__ and main() In many Python scripts you will find the following at the bottom of modules In plain English … If the module is running as a program (i.e. not imported), then __name__ will be __main__ so call the main() function defined in the module. If the module was imported, __name__ will be the name of the module and main() will not be called.

Lib, Modules, function mind map