How To Understand The Details Of A Function In Python 2.5.2 (For Beginners)



Similar documents
Python Programming: An Introduction To Computer Science

Python Programming: An Introduction to Computer Science

Unit testing using Python nose

Exercise 1: Python Language Basics

Programming by Contract. Programming by Contract: Motivation. Programming by Contract: Preconditions and Postconditions

Online EFFECTIVE AS OF JANUARY 2013

ESPResSo Summer School 2012

Factoring Guidelines. Greatest Common Factor Two Terms Three Terms Four Terms Shirley Radai

Modeling, Computers, and Error Analysis Mathematical Modeling and Engineering Problem-Solving

Scientific Programming in Python

Computer Science 1 CSci 1100 Lecture 3 Python Functions

Python Programming: An Introduction to Computer Science

Introduction to Python

Python Programming: An Introduction to Computer Science

Self-review 9.3 What is PyUnit? PyUnit is the unit testing framework that comes as standard issue with the Python system.

CS420: Operating Systems OS Services & System Calls

Lab 2.1 Tracking Down the Bugs

Objectives. Chapter 2: Operating-System Structures. Operating System Services (Cont.) Operating System Services. Operating System Services (Cont.

6.170 Tutorial 3 - Ruby Basics

MS-EXCEL: ANALYSIS OF EXPERIMENTAL DATA

SOLVING QUADRATIC EQUATIONS - COMPARE THE FACTORING ac METHOD AND THE NEW DIAGONAL SUM METHOD By Nghi H. Nguyen

Objectives. Python Programming: An Introduction to Computer Science. Lab 01. What we ll learn in this class

ReproLite : A Lightweight Tool to Quickly Reproduce Hard System Bugs

Debugging Multi-threaded Applications in Windows

Sorting. Lists have a sort method Strings are sorted alphabetically, except... Uppercase is sorted before lowercase (yes, strange)

High-Level Programming Languages. Nell Dale & John Lewis (adaptation by Michael Goldwasser)

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

Database Programming with PL/SQL: Learning Objectives

FOPR-I1O23 - Fundamentals of Programming

Factoring Polynomials and Solving Quadratic Equations

PHP Debugging. Draft: March 19, Christopher Vickery

Interactive Applications (CLI) and Math

Custom Calling Features and how they work

PERFECT SQUARES AND FACTORING EXAMPLES

LABORATORY 117. Intorduction to VoiceXML (2)

Chapter 13: Program Development and Programming Languages

Chapter 5 Functions. Introducing Functions

Introduction to Functional Verification. Niels Burkhardt

A Systematic Approach to Factoring

Documentum Developer Program

ALGORITHMS AND FLOWCHARTS. By Miss Reham Tufail

Chapter 13: Program Development and Programming Languages

Engineering Problem Solving and Excel. EGN 1006 Introduction to Engineering

ALGORITHMS AND FLOWCHARTS

Software Construction

6.6 Factoring Strategy

The Clean programming language. Group 25, Jingui Li, Daren Tuzi

Excel 2010: Create your first spreadsheet

LabVIEW Advanced Programming Techniques

Appendix: Tutorial Introduction to MATLAB

JavaScript. JavaScript: fundamentals, concepts, object model. Document Object Model. The Web Page. The window object (1/2) The document object

Chapter 8 Detailed Modeling

Calculator. Introduction. Requirements. Design. The calculator control system. F. Wagner August 2009

Tool 1. Greatest Common Factor (GCF)

Answer Key for California State Standards: Algebra I

Exercise 4 Learning Python language fundamentals

Invitation to Ezhil : A Tamil Programming Language for Early Computer-Science Education 07/10/13

Debugging Prolog Programs. Contents The basic Prolog debugger Tracing program execution Spying on problem predicates

CS 1133, LAB 2: FUNCTIONS AND TESTING

Some programming experience in a high-level structured programming language is recommended.

SOLVING QUADRATIC EQUATIONS - COMPARE THE FACTORING AC METHOD AND THE NEW TRANSFORMING METHOD (By Nghi H. Nguyen - Jan 18, 2015)

Welcome to Introduction to programming in Python

How to test and debug an ASP.NET application

Chapter 5 Programming Statements. Chapter Table of Contents

IT Application Controls Questionnaire

Teaching an Introductory Computer Science Sequence with Python

CS3600 SYSTEMS AND NETWORKS

Data Analysis Tools. Tools for Summarizing Data

Multiplying and Dividing Radicals

Rake Task Management Essentials

LAB 2 SPARK / D-STREAM PROGRAMMING SCIENTIFIC APPLICATIONS FOR IOT WORKSHOP

I don t intend to cover Python installation, please visit the Python web site for details.

QUIZ-II QUIZ-II. Chapter 5: Control Structures II (Repetition) Objectives. Objectives (cont d.) 20/11/2015. EEE 117 Computer Programming Fall

Automatic Telephone Dialer TD-101(W)

A couple of things involving environments

Data Intensive Computing Handout 6 Hadoop

Factoring Polynomials

Factoring - Solve by Factoring

Formulas & Functions in Microsoft Excel

Outline. multiple choice quiz bottom-up design. the modules main program: quiz.py namespaces in Python

Computers. An Introduction to Programming with Python. Programming Languages. Programs and Programming. CCHSG Visit June Dr.-Ing.

Definitions 1. A factor of integer is an integer that will divide the given integer evenly (with no remainder).

IT Services. Service Level Agreement

GUJARAT TECHNOLOGICAL UNIVERSITY, AHMEDABAD, GUJARAT COURSE CURRICULUM. Course Title: Advanced Computer Programming (Code: )

Collinear Points in Permutations

Introduction to Programming with Python Session 3 Notes

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

CS 758: Cryptography / Network Security

Program Number. 1 System Parameters SYS800 Defines system-wide parameters. 2 Chart of Accounts GLD103 Defines chart of accounts

Algorithms, Flowcharts & Program Design. ComPro

Intro to scientific programming (with Python) Pietro Berkes, Brandeis University

Mathematics for Computer Science/Software Engineering. Notes for the course MSM1F3 Dr. R. A. Wilson

6.5 Factoring Special Forms

TEST AUTOMATION FRAMEWORK

Operating System Structures

Transcription:

Python Programming: An Introduction to Computer Science Chapter 6 Defining Functions Python Programming, 2/e 1

Objectives To understand why programmers divide programs up into sets of cooperating functions. To be able to define new functions in Python. To understand the details of function calls and parameter passing in Python. Python Programming, 2/e 2

Objectives (cont.) To write programs that use functions to reduce code duplication and increase program modularity. Python Programming, 2/e 3

The Function of Functions So far, we ve seen three different types of functions: Our programs comprise a single function called main(). Built-in Python functions (round, abs) Functions from the standard libraries (math.sqrt, math.sin) Python Programming, 2/e 4

The Function of Functions Having similar or identical code in more than one place has some drawbacks. Issue one: writing the same code twice or more. Issue two: This same code must be maintained in two separate places. Functions can be used to reduce code duplication and make programs more easily understood and maintained. Python Programming, 2/e 5

Functions, Informally A function is like a subprogram, a small program inside of a program. The basic idea we write a sequence of statements and then give that sequence a name. We can then execute this sequence at any time by referring to the name. Python Programming, 2/e 6

Functions, Informally The part of the program that creates a function is called a function definition. When the function is used in a program, we say the definition is called or invoked. Python Programming, 2/e 7

Functions, Informally Example of function (intentional bug) # Using a main method like the book # This code has an intentional bug def main(): a, b, c = eval(input("enter 3 numbers: ")) if(a >= b >= c): max = a; if(b >= a >= c): max = b; if(c >= b >= a): max = a; print('max: ', max) main() Python Programming, 2/e 8

Functions, Informally Let's put the buggy ifs in a new function def maxof3(a, b, c): if(a >= b >= c): max = a; if(b >= a >= c): max = b; if(c >= b >= a): max = a; return max def main(): a, b, c = eval(input("enter 3 numbers: ")) print('max: ', maxof3(a, b, c)) main() Python Programming, 2/e 9

Functions, Informally Change main to test the new function def main(): # All permutations of three unique numbers print('3? ', maxof3(1, 2, 3)) print('3? ', maxof3(1, 3, 2)) print('3? ', maxof3(2, 3, 1)) print('3? ', maxof3(2, 1, 3)) # The other two? Python Programming, 2/e 10

Functions, Informally Creating this function captured the logic If we can get this function working, it would be nice. Debug and test it now. Python Programming, 2/e 11

Functions and Parameters: The Details Each function is its own little subprogram. The variables used inside of a function are local to that function, even if they happen to have the same name as variables that appear inside of another function. The only way for a function to see a variable or to get a value from another place is for that variable to be passed as a parameter. Python Programming, 2/e 12

Functions and Parameters: The Details A function definition looks like this: def <name>(<formal-parameters>): <body> The name of the function must be an identifier Formal-parameters is a possibly empty list of variable names Python Programming, 2/e 13

Functions and Parameters: The Details Formal parameters, like all variables used in the function, are only accessible in the body of the function. Variables with identical names elsewhere in the program are distinct from the formal parameters and variables inside of the function body. Python Programming, 2/e 14

Functions and Parameters: The Details A function is called by using its name followed by a list of actual parameters or arguments 1. <name>(<arguments>) When Python comes to a function call, it initiates a four-step process. 1 Rick will use the term arguments, John uses the term actual parameters Python Programming, 2/e 15

Functions and Parameters: The Details The calling program suspends execution at the point of the call. The formal parameters of the function get assigned the values supplied by the actual parameters in the call. The body of the function is executed. Control returns to the point just after where the function was called. Python Programming, 2/e 16

Functions and Parameters: The Details Trace through the current program with a main method that tests maxof3 Then move maxof3 into another file named myfunctions.py Leave the main method to test, but we need to now import that function from myfunctions import maxof3 Python Programming, 2/e 17

Functions and Paramters: The Details One thing not addressed in this example was multiple parameters. In this case the formal and actual parameters are matched up based on position, e.g. the first actual parameter is assigned to the first formal parameter, the second actual parameter is assigned to the second formal parameter, etc. Python Programming, 2/e 18

Getting Results from a Function Passing parameters provides a mechanism for initializing the variables in a function. Parameters act as inputs to a function. We can call a function many times and get different results by changing its parameters. Python Programming, 2/e 19

Functions That Return Values We ve already seen numerous examples of functions that return values to the caller. discrt = math.sqrt(b*b 4*a*c) The value b*b 4*a*c is the actual parameter of math.sqrt. We say sqrt returns the square root of its argument. Python Programming, 2/e 20

Functions That Return Values This function returns the square of a number: def square(x): return x*x When Python encounters return, it exits the function and returns control to the point where the function was called. In addition, the value(s) provided in the return statement are sent back to the caller as an expression result. Python Programming, 2/e 21

Functions That Return Values >>> square(3) 9 >>> print(square(4)) 16 >>> x = 5 >>> y = square(x) >>> print(y) 25 >>> print(square(x) + square(3)) 34 Python Programming, 2/e 22

Consider CodingBats http://codingbat.com/python In class, write the answers to those shown Python Programming, 2/e 23