What is a function? "The Practice of Computing Using Python", Punch & Enbody, Copyright 2013 Pearson Education, Inc.

Similar documents
Introduction to Functions. Intro to Computer Science CS1510 Dr. Sarah Diesburg

What is a class? Responding to messages. Short answer 7/19/2017. Code Listing 11.1 First Class. chapter 11. Introduction to Classes

Functions. CSE 231, Rich Enbody. From Mathematics we know that functions perform some operation and return one value.

Working with Strings. Husni. "The Practice of Computing Using Python", Punch & Enbody, Copyright 2013 Pearson Education, Inc.

Functions. Rich Enbody. From Mathematics we know that functions perform some operation and return one value.

Chapter 6. Files and Exceptions I

First cut, scope. Defining scope. Find the namespace. Passing argument to parameter. A function s namespace 6/13/2017. chapter 8.

The Three Rules. Program. What is a Computer Program? 5/30/2018. Interpreted. Your First Program QuickStart 1. Chapter 1

Sequence of Characters. Non-printing Characters. And Then There Is """ """ Subset of UTF-8. String Representation 6/5/2018.

The Practice of Computing Using PYTHON. Chapter 4. Working with Strings. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Python allows variables to hold string values, just like any other type (Boolean, int, float). So, the following assignment statements are valid:

What is a Class? Short Answer. Responding to Messages. Everything in Python is an Object 11/8/2010

Control, Quick Overview. Selection. Selection 7/6/2017. Chapter 2. Control

Introducing Python Modules

Getting Started. Office Hours. CSE 231, Rich Enbody. After class By appointment send an . Michigan State University CSE 231, Fall 2013

The Practice of Computing Using PYTHON

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG

Lecture 7: Functions. CS1068+ Introductory Programming in Python. Dr Kieran T. Herley 2018/19. Department of Computer Science University College Cork

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

A A B U n i v e r s i t y

2. Numbers In, Numbers Out

ENGG1811 Computing for Engineers Week 1 Introduction to Programming and Python

Objects and Classes. Chapter 8

LAB: INTRODUCTION TO FUNCTIONS IN C++

Scripting Languages. Python basics

Implementing an Algorithm for Boomerang Fraction Sequences in Python

CS 31: Intro to Systems C Programming. Kevin Webb Swarthmore College September 13, 2018

Dr. Scheme evaluates expressions so we will start by using the interactions window and asking Dr. Scheme to evaluate some expressions.

Can you think of a situation where this would occur?

>>> * *(25**0.16) *10*(25**0.16)

Programming in ROBOTC ROBOTC Rules

Chapter Five: Functions

2. Numbers In, Numbers Out

Object Oriented Programming #10

MITOCW watch?v=kz7jjltq9r4

Hello, World and Variables

Functions and abstraction. Ruth Anderson UW CSE 160 Winter 2017

Lecture 4. Defining Functions

Chapter 2 Writing Simple Programs

Programming. Functions and File I/O

A Beginner s Guide to Programming Logic, Introductory. Chapter 2 Working with Data, Creating Modules, and Designing High-Quality Programs

CHAPTER 2: Introduction to Python COMPUTER PROGRAMMING SKILLS

Python lab session 1

Introduction to Python Code Quality

SI Networked Computing: Storage, Communication, and Processing, Winter 2009

COMP10001 Foundations of Computing Testing and Debugging

Expressions. Eric Roberts Handout #3 CSCI 121 January 30, 2019 Expressions. Grace Murray Hopper. Arithmetic Expressions.

Reminders. Lecture Outline. Lecture Agenda. Lecture Outline. Remember This? COMP10001 Foundations of Computing Testing and Debugging

Programming Logic and Design Seventh Edition Chapter 2 Elements of High-Quality Programs

Chapter 2, Part I Introduction to C Programming

What is an algorithm?

CSC102 INTRO TO PROGRAMMING WITH PYTHON LECTURE 9 PYTHON BEATS YOUR STINKY LANGUAGE: YOU CAN QUOTE ME MICHAEL GROSSBERG

Functions: Decomposition And Code Reuse

Announcements For This Lecture

6.S189 Homework 2. What to turn in. Exercise 3.1 Defining A Function. Exercise 3.2 Math Module.

Spring CS Homework 3 p. 1. CS Homework 3

In this section we take an aside from the normal discussion in algebra.

Chapter 1: Foundations for Algebra

Functional Programming in Haskell Prof. Madhavan Mukund and S. P. Suresh Chennai Mathematical Institute

Scientific Computing: Lecture 3

Lecture 4. Defining Functions

and numbers and no spaces. Press after typing the name. You are now in the Program Editor. Each line of code begins with the colon character ( : ).

Downloaded from Chapter 2. Functions

Part II Composition of Functions

Chapter 8 SETS AND DICTIONARIES

Chapter 1. Introduction to Computers and Java Objects. Background information. » important regardless of programming language. Introduction to Java

Question 1. CSC A08 F Midterm Test Solutions Fall 2011

UNIT II Requirements Analysis and Specification & Software Design

Lecture 5: Strings

Semester 2, 2018: Lab 5

Module 3 SELECTION STRUCTURES 2/15/19 CSE 1321 MODULE 3 1

CSCA20 Worksheet Strings

CHAPTER 4 MATHEMATICAL FUNCTIONS, CHARACTERS, STRINGS

Lecture #2: Programming Structures: Loops and Functions

Lecture 04 FUNCTIONS AND ARRAYS

Programming Logic and Design Sixth Edition Chapter 2 Working with Data, Creating Modules, and Designing High-Quality Programs

Separate, Split & Remove Substring & Number from Text with Excel Functions & VBA

CS 115 Lecture 13. Strings. Neil Moore. Department of Computer Science University of Kentucky Lexington, Kentucky

Classes, part Deux. Three Groups. CSE 231, Rich Enbody. Users Programmers Class Designers 11/11/13. Michigan State University CSE 231, Fall 2013

Lecture 4. Defining Functions

SNS COLLEGE OF ENGINEERING

SKILL AREA 304: Review Programming Language Concept. Computer Programming (YPG)

How To Think Like A Computer Scientist, chapter 3; chapter 6, sections

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

Java Methods. Lecture 8 COP 3252 Summer May 23, 2017

CSC A20H3 S 2011 Test 1 Duration 90 minutes Aids allowed: none. Student Number:

Introduction to C# Applications Pearson Education, Inc. All rights reserved.

61A Lecture 19. Wednesday, October 12

Department of Electrical Engineering and Computer Science MASSACHUSETTS INSTITUTE OF TECHNOLOGY

CS 115 Exam 1, Fall 2015 Thu. 09/24/2015

Week - 01 Lecture - 04 Downloading and installing Python

Lecture 4: Simple Input-Calculate-Output Programs

Introduction to: Computers & Programming: Review prior to 1 st Midterm

COMP1730/COMP6730 Programming for Scientists. Strings

Python for Informatics

Booleans, Logical Expressions, and Predicates

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

Section Graphs and Lines

Introduction to Python Programming

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

Transcription:

Functions Husni

What is a function? "The Practice of Computing Using Python", Punch & Enbody, Copyright 2013 Pearson Education, Inc.

Functions From Mathematics we know that functions perform some operation and return one value. They "encapsulate" the performance of some particular operation, so it can be used by others (for example, the sqrt() function)

Why have them? Support divide-and-conquer strategy Abstraction of an operation Reuse. Once written, use again Sharing. If tested, others can use Security. Well tested, then secure for reuse Simplify code. More readable.

Mathematical Notation Consider a function which converts temperatures in Celsius to temperatures in Fahrenheit. Formula: F = C * 1.8 + 32.0 Functional notation: F ~ celsius_to_fahrenheit(c) where celsius_to_fahrenheit(c) = C * 1.8 + 32.0

Python Invocation Math: F = celsius_to_fahrenheit(c) Python, the invocation is much the same F = celsius_to_fahrenheit(cel_float) Terminology: cel_float is the argument

Function defintion Math: g(c) = C*1.8 + 32.0 Python def celsius_to_fahrenheit(param_float): return param_float * 1.8 + 32.0 Terminology: param_float is the parameter

return statement The return statement indicates the value that is returned by the function The statement is optional (the function can return nothing). If no return, function is often called a procedure.

Code Listing 6.1 Temp convert "The Practice of Computing Using Python", Punch & Enbody, Copyright 2013 Pearson Education, Inc.

Triple quoted string in function A triple quoted string just after the def is called a docstring docstring is documentation of the function's purpose, to be used by other tools to tell the user what the function is used for. More on that later

Operation F = celsius_to_fahrenheit(c) 1. Call copies argument C to parameter param 2. Control transfers to function def celsius_to_fahrenheit (param): return param * 1.8 + 32.0

Operation (con't) F = celsius_to_fahrenheit(c) 4. Value of expression is returned to the invoker 3. Expression in function is evaluated def celsius_to_fahrenheit (param): return param * 1.8 + 32.0

Code Listing 6.2 Full Temp Program "The Practice of Computing Using Python", Punch & Enbody, Copyright 2013 Pearson Education, Inc.

Code Listing 6.3 re-implement len "The Practice of Computing Using Python", Punch & Enbody, Copyright 2013 Pearson Education, Inc.

Code Listing 6.4 Count letters in string "The Practice of Computing Using Python", Punch & Enbody, Copyright 2013 Pearson Education, Inc.

check membership in lowercase import string use string.ascii_lowercase, string of lowercase english letters 'abcdefghijklmnopqrstuvwxyz' check if each char is a member (using in operator) of string.ascii_lowercase char.lower() before membership (catch Capital Letters that way)

Word Puzzle Find an English language word that has the vowels 'a', 'e', 'i', 'o', and 'u' in sequence

Reading a file of Text Remember how to work with text files The open function takes a string (a file name) and a mode ('r' for reading) and returns a file object. You can use a for loop on the file object to fetch one line of text at a time (a line ends with a carriage return)

Code Listing 6.5 Open a file to read "The Practice of Computing Using Python", Punch & Enbody, Copyright 2013 Pearson Education, Inc.

Need a list of words We use a dictionary file (easily found on the web) of english words, one word per line open the file process each line (a single word) this example just prints them all

Code Listing 6.6 Clean a word "The Practice of Computing Using Python", Punch & Enbody, Copyright 2013 Pearson Education, Inc.

clean the word strip method removes white space characters from the beginning and end of a string (can remove other chars as well) beginning and end only, not the middle all such characters from either end file line likely has returns or tabs of spaces which might hurt compares lower method so case won't matter

Code Listing 6.8 Extract Vowels "The Practice of Computing Using Python", Punch & Enbody, Copyright 2013 Pearson Education, Inc.

collect vowels collect only vowels as a string, in order from the word, and compare against the reference "aeiou" use in operator for membership use + operator to concat vowels together

Code Listion 6.9 Solution to word problem "The Practice of Computing Using Python", Punch & Enbody, Copyright 2013 Pearson Education, Inc.

Did functions help? Made our problem solving easier (solved smaller problems as functions) main program very readable (details hid in the functions)

How to write a function Does one thing. If it does too many things, it should be broken down into multiple functions (refactored) Readable. How often should we say this? If you write it, it should be readable Reusable. If it does one thing well, then when a similar situation (in another program) occurs, use it there as well.

More on functions Complete. A function should check for all the cases where it might be invoked. Check for potential errors. Not too long. Kind of synonymous with do one thing. Use it as a measure of doing too much.

Rule 8 A function should do one thing

Procedures Functions that have no return statements are often called procedures. Procedures are used to perform some duty (print output, store a file, etc.) Remember, return is not required.

Multiple returns in a function A function can have multiple return statements. Remember, the first return statement executed ends the function. Multiple returns can be confusing to the reader and should be used judiciously.

Reminder, rules so far 1. Think before you program! 2. A program is a human-readable essay on problem solving that also happens to execute on a computer. 3. The best way to imporve your programming and problem solving skills is to practice! 4. A foolish consistency is the hobgoblin of little minds 5. Test your code, often and thoroughly 6. If it was hard to write, it is probably hard to read. Add a comment. 7. All input is evil, unless proven otherwise. 8. A function should do one thing.