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

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

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

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

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

Introducing Python Modules

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

Introduction to Computer Programming CSCI-UA 2. Review Midterm Exam 1

Lecture 4. Defining Functions

Scripting Languages. Python basics

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

CHAPTER 2: Introduction to Python COMPUTER PROGRAMMING SKILLS

ENGG1811 Computing for Engineers Week 1 Introduction to Programming and Python

Lecture 4: Simple Input-Calculate-Output Programs

MITOCW watch?v=kz7jjltq9r4

Chapter 2 Writing Simple Programs

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

FUNCTION PARAMETER AND ARGUMENT

! A program is a set of instructions that the. ! It must be translated. ! Variable: portion of memory that stores a value. char

Lecture #2: Programming Structures: Loops and Functions

Lecture 4: Basic I/O

Defining Functions. Chapter 6. Wednesday, January 23, Why functions?

Spring CS Homework 3 p. 1. CS Homework 3

Fundamentals of Programming Session 4

Python review. 1 Python basics. References. CS 234 Naomi Nishimura

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

Strings are actually 'objects' Strings

Variable and Data Type I

Intro. to Computing. Lecture 7 Page1

LISTS WITH PYTHON. José M. Garrido Department of Computer Science. May College of Computing and Software Engineering Kennesaw State University

2.1 Indefinite Loops. while <condition>: <body> rabbits = 3 while rabbits > 0: print rabbits rabbits -= 1

Variable and Data Type I

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

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

LAB: INTRODUCTION TO FUNCTIONS IN C++

Copied from: on 3/20/2017

Python lab session 1

Functions: Decomposition And Code Reuse

Fundamentals of Python: First Programs. Chapter 4: Strings and Text Files

Implementing an Algorithm for Boomerang Fraction Sequences in Python

Introduction to Computer Programming for Non-Majors

CSc 10200! Introduction to Computing. Lecture 1 Edgardo Molina Fall 2013 City College of New York

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

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

STRINGS. We ve already introduced the string data type a few lectures ago. Strings are subtypes of the sequence data type.

2. Modules, Scripts, and I/O. Quick Note on print. The Windchill Calculation. Script Mode. Motivating Script Mode 1/22/2016

CS 11 python track: lecture 3. n Today: Useful coding idioms

CS112 Spring 2012 Dr. Kinga Dobolyi. Exam 2. Do not open this exam until you are told. Read these instructions:

2. Modules, Scripts, and I/O

CSC148 Fall 2017 Ramp Up Session Reference

About Python. Python Duration. Training Objectives. Training Pre - Requisites & Who Should Learn Python

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

Objects and Classes. Chapter 8

Digital Media. Seasons Assignment. 1. Copy and open the file seasonsbegin.fla from the Read folder.

Functions and abstraction. Ruth Anderson UW CSE 160 Winter 2017

Homework 3: Recursion Due: 11:59 PM, Sep 25, 2018

Lecture 4. Defining Functions

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad

ENGR 102 Engineering Lab I - Computation

Control Flow, Functions and Basic Linkage

Lecture 5. Defining Functions

Introduction to: Computers & Programming Defining Identifiers: Objects with Names

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad

CS 105 Lab As a review of what we did last week a. What are two ways in which the Python shell is useful to us?

Functions!!! Why functions? Functions provide good way to design systems!

Module 3: Strings and Input/Output

CS1 Lecture 3 Jan. 18, 2019

Lecture 04 FUNCTIONS AND ARRAYS

Programming for Engineers Introduction to C

CS 150 Lab 3 Arithmetic and the Debugger. Lab 3.0 We are going to begin using the Visual Studio 2017 debugger to aid with debugging programs.

Lecture 1: Preliminaries

CEN 414 Java Programming

Introduction to Computers and Java

7. (2 pts) str( str( b ) ) str '4' will not compile (single, double, or triple quotes

Chapter 3 : Informatics Practices. Class XI ( As per CBSE Board) Python Fundamentals. Visit : python.mykvs.in for regular updates

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

Chapter Five: Functions

Subroutines I Computers and Programming

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015

Data Types & Variables

Introduction to Computers and Java. Objectives. Outline. Harald Gall, Prof. Dr. Institut für Informatik Universität Zürich.

Introduction to Computers and Java

Faculty of Engineering Computer Engineering Department Islamic University of Gaza C++ Programming Language Lab # 6 Functions

Python Tutorial. Day 1

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

Lecture 4. Defining Functions

Introduction to Computers and Java

CSC 015: FUNDAMENTALS OF COMPUTER SCIENCE I

Programming I. Course 9 Introduction to programming

Introduction to Computers and Java

Functions: Decomposition And Code Reuse

CMPT 120 Basics of Python. Summer 2012 Instructor: Hassan Khosravi

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

Files on disk are organized hierarchically in directories (folders). We will first review some basics about working with them.

Functions with Parameters and Return Values

} Evaluate the following expressions: 1. int x = 5 / 2 + 2; 2. int x = / 2; 3. int x = 5 / ; 4. double x = 5 / 2.

9/11/08 (c) 2008 Matthew J. Rutherford Class (c) 2008 Matthew J. Rutherford Class

Full file at

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

Introduction to Computers and Java. Objectives. Outline. Harald Gall, Prof. Dr. Institut für Informatik Universität Zürich.

Week 9: Constraints. d = F L/(A E) A = F L/(d E), etc

Transcription:

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

Review So far, most of our programs have retrieved data from the keyboard and written data to the screen Data must be entered on every program run Programs have no way to write permanent output Text files provide convenient input/output storage e.g. programs can read configuration data or input files to process, and can write output to files

Question #1 A program is designed to retrieve some data from a file, process it, and output the revised data to another file. Which of the following functions/methods will not be called in the program? A. open B. A loop or method for reading (e.g. read) C. write D. close E. All should be called

Review Several methods for reading text from files: readline: reads and returns next line; returns empty string at end-of-file read: reads the entire file into one string readlines: reads the entire file into a list of strings All of these leave a trailing '\n' character at the end of each line.

Review A file is a sequence of lines. Can be read with a for-loop f = open( data.txt, r ) for line in f: print(line.strip()) or using a while-loop: f = open( data.txt, r ) line = f.readline() while line: print(line.strip()) line = f.readline()

Question #2 What is the last thing printed? data.txt Reading Assignments #Each line lists the reading #assignment for that date Sep, 17, Section 1.1-1.3 Sep, 19, Section 1.4-1.8 Sep, 21, Section 2.1-2.4 program line = f.readline() line = f.readline() while line.startswith('#'): line = f.readline() print(f.readline())

Question #3 What is the last thing printed? data.txt Reading Assignments #Each line lists the reading #assignment for that date Sep, 17, Section 1.1-1.3 Sep, 19, Section 1.4-1.8 Sep, 21, Section 2.1-2.4 program line = f.readline() line = f.readline() while line.startswith('#'): line = f.readline() print( line )

What is a Function?

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 len() function).

Why Have Them? Abstraction of an operation Reuse: once written, use again Sharing: if tested, others can use Security: if well tested, then secure for reuse Simplify code: more readable Support divide-and-conquer strategy

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

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

Function Definition Math: g(c) = C*1.8 + 32.0 Python def celsius2fahrenheit (C): return C*1.8 + 32.0 Terminology: parameter C

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, the function is often called a procedure.

Code Listing 6.1 Temp Convert

Code Listing 6.1 # Temperature conversion def celsius2fahrenheit(celsius): """ Convert Celsius to Fahrenheit.""" return celsius*1.8 + 32

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.

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

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

Code Listing 6.3 Implement len

Code Listing 6.3 def length(s): """Return the length of S.""" count = 0 for s in S: count += 1 return count

Code Listing 6.4 Count Letters in String

Check Membership in lowercase import string use string.lowercase, string of lowercase abcdefghijklmnopqrstuvwxyz check if each letter is a member (using the in operator) of string.lowercase

Code Listing 6.4 import string def lettercount(s): """Return the count of letters in S.""" count = 0 for s in S: if s.lower() in string.ascii_lowercase: count += 1 return count

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 does one thing. Use it as a measure of doing too much.

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.