More on Functions; Some File I/O UW CSE 190p Summer 2012.

Slides:



Advertisements
Similar presentations
Python Basics: Statements Expressions Loops Strings Functions.
Advertisements

UW CSE 190p Section 6/21, Summer 2012 Dun-Yu Hsiao.
Adapted from John Zelle’s Book Slides
Python Programming: An Introduction to Computer Science
Vahé Karamian Python Programming CS-110 CHAPTER 2 Writing Simple Programs.
File input and output if-then-else Genome 559: Introduction to Statistical and Computational Genomics Prof. William Stafford Noble.
1 Loops. 2 Often we want to execute a block of code multiple times. Something is always different each time through the block. Typically a variable is.
Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types.
Chapter 2 Writing Simple Programs
Recitation 1 Programming for Engineers in Python.
Functions.
Exceptions COMPSCI 105 S Principles of Computer Science.
Python.
Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language.
Python Programming, 2/e1 Python Programming: An Introduction to Computer Science Chapter 2.
Builtins, namespaces, functions. There are objects that are predefined in Python Python built-ins When you use something without defining it, it means.
ICAPRG301A Week 4Buggy Programming ICAPRG301A Apply introductory programming techniques Program Bugs US Navy Admiral Grace Hopper is often credited with.
COMP 171: Functions, for loops and range John Barr Section 03 Slides by Toby Dragon.
CS 127 Writing Simple Programs.  Stages involved  Analyze the problem  Understand as much as possible what is trying to be solved  Determine Specifications.
Module 3 Fraser High School. Module 3 – Loops and Booleans import statements - random use the random.randint() function use while loop write conditional.
The Development Process Problem Solving. Problem Solving - Dr. Struble 2 What Is Asked of Computer Programmers? Input Transformation Output Write a computer.
C463 / B551 Artificial Intelligence Dana Vrajitoru Python.
File I/O Michael Ernst UW CSE 140 Winter File Input and Output As a programmer, when would one use a file? As a programmer, what does one do with.
Functions and abstraction Michael Ernst UW CSE 140 Winter 2013.
File I/O Ruth Anderson UW CSE 160 Spring File Input and Output As a programmer, when would one use a file? As a programmer, what does one do with.
CS2021 Week 2 Off and Running with Python. Two ways to run Python The Python interpreter – You type one expression at a time – The interpreter evaluates.
Copyright Curt Hill The C/C++ switch Statement A multi-path decision statement.
Chapter Functions 6. Modular Programming 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules.
2. WRITING SIMPLE PROGRAMS Rocky K. C. Chang September 10, 2015 (Adapted from John Zelle’s slides)
Fall 2014 (both sections) Assignment #1 Feedback Elapsed time (How long): –Ranged from 45 minutes to 10 days –About 1/4 said less than 1 day –About 1/2.
Midterm Review Important control structures Functions Loops Conditionals Important things to review Binary Boolean operators (and, or, not) Libraries (import.
Introduction to Functions CSIS 1595: Fundamentals of Programming and Problem Solving 1.
Exceptions Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See
Lecture 4 Python Basics Part 3.
Control flow Ruth Anderson UW CSE 160 Spring
File I/O Ruth Anderson UW CSE 140 Winter File Input and Output As a programmer, when would one use a file? As a programmer, what does one do with.
9. ITERATIONS AND LOOP STRUCTURES Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)
Introduction to Computing Using Python Repetition: the for loop  Execution control structures  for loop – iterating over a sequence  range() function.
Control flow Ruth Anderson UW CSE 160 Winter
While loops. Iteration We’ve seen many places where repetition is necessary in a problem. We’ve been using the for loop for that purpose For loops are.
Interpreting Exceptions UW CSE 160 Spring 2015 download examples from the calendar 1.
PYTHON FUNCTIONS. What you should already know Example: f(x) = 2 * x f(3) = 6 f(3)  using f() 3 is the x input parameter 6 is the output of f(3)
Python Programming, 2/e1 Python Programming: An Introduction to Computer Science Chapter 2.
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.
Python Programming Module 3 Functions Python Programming, 2/e1.
Chapter 2 Writing Simple Programs
CS170 – Week 1 Lecture 3: Foundation Ismail abumuhfouz.
University of Washington Computer Programming I
Functions and abstraction
Think What will be the output?
Ruth Anderson UW CSE 160 Winter 2016
CMSC201 Computer Science I for Majors Lecture 10 – Functions (cont)
CS 240 – Lecture 11 Pseudocode.
Ruth Anderson UW CSE 160 Spring 2018
Ruth Anderson UW CSE 160 Winter 2017
Functions and abstraction
Ruth Anderson UW CSE 160 Winter 2017
Teaching London Computing
Ruth Anderson UW CSE 160 Spring 2018
Ruth Anderson UW CSE 140 Winter 2014
What does this do? def revList(L): if len(L) < = 1: return L x = L[0] LR = revList(L[1:]) return LR + x.
Bryan Burlingame 13 February 2019
Loops and Simple Functions
Chopin’s Nocturne.
Topic: Loops Loops Idea While Loop Introduction to ranges For Loop
Michael Ernst UW CSE 190p Summer 2012
def-ining a function A function as an execution control structure
UW CSE 190p Section 7/19, Summer 2012 Dun-Yu Hsiao.
 A function is a named sequence of statement(s) that performs a computation. It contains  line of code(s) that are executed sequentially from top.
Presentation transcript:

More on Functions; Some File I/O UW CSE 190p Summer 2012

Review def myfunc(n): total = 0 for i in range(n): total = total + i return total print myfunc(4) What is the result?

Exercise: Control Flow def c_to_f(c): print “c_to_f” return c / 5.0 * def make_message(temp): print “make_message” return “The temperature is “+str(temp) for tempc in [19,22,21]: tempf = c_to_f(tempc) message = make_message(tempf) print message c_to_f make_message The temperature is 66.2 c_to_f make_message The temperature is 71.6 c_to_f make_message The temperature is 69.8

Loop Gotcha: Indentation def c_to_f(c): print “c_to_f” return c / 5.0 * def make_message(temp): print “make_message” return “The temperature is “+str(temp) for tempc in [19,22,21]: tempf = c_to_f(tempc) message = make_message(tempf) print message c_to_f make_message c_to_f make_message c_to_f make_message The temperature is 69.8

Problem 5: Indentation for i in range(1, 10+1): fac = 1 for j in range(1,i+1): fac = fac * j print fac

Problem 5: Indentation for i in range(1, 10+1): fac = 1 for j in range(1,i+1): fac = fac * j print fac

Function Gotcha: Local Variables def c_to_f(c): result = c / 5.0 * return result tempf = c_to_f(19) print result See examples in the book: A mistake! What happens here?

Local variables Local scope English definition: scope (n): extent or range of view, outlook, application, operation, effectiveness, etc.: Global scope def c_to_f(c): result = c / 5.0 * return result tempf = c_to_f(19) print result

Local Scope and Global Scope def normal_pressure(pressure): result = pressure – pressure_at_sea_level return result pressure_at_sea_level = 7 print normal_pressure(16) Does this work? How?

Local Scope and Global Scope When Python encounters a variable, it – first checks to see if the variable is defined in the local scope – then checks to see if the variable is defined in the global scope But: try to avoid this feature. Keep global variables global, and local variables local

Local Scope and Global Scope def normal_pressure(pressure): pressure_at_sea_level = 7 result = pressure – pressure_at_sea_level return result print normal_pressure(16) Better

Confusing Variables def atm_to_mbar(pressure): return pressure * def mbar_to_mmHg(pressure): return pressure * pressure = 1.2 # in atmospheres pressure = atm_to_mbar(pressure) pressure = mbar_to_mmHg(pressure) print pressure

A Better Way def atm_to_mbar(pressure): return pressure * def mbar_to_mmHg(pressure): return pressure * in_atm = 1.2 in_mbar = atm_to_mbar(in_atm) in_mmHg = mbar_to_mmHg(in_mbar) print in_mmHg Much more clear!!

Function Gotcha: Return Value def c_to_f(c): print c / 5.0 * print c_to_f(19) Anything wrong here? No return value!?! Good practice: Always include a return statement!

Review: functions calling functions def atm_to_mbar(pressure): return pressure * def mbar_to_mmHg(pressure): return pressure * def atm_to_mmHg(pressure): in_mbar = atm_to_mbar(pressure) in_mmHg = mbar_to_mmHg(in_mbar) return in_mmHg print atm_to_mmHg(5)

Local Scope and Global Scope revisited When Python encounters a variable, it – first checks to see if the variable is defined in the local scope – then checks to see if the variable is defined in the next most outer scope – … – then checks to see if the variable is defined in the global scope

Function Engineering Breaking down a program into functions is the fundamental activity of programming! How do you decide when to use a function? – One rule from the last lecture: DRY – Whenever you are tempted to copy and paste code, don’t! Now, how do you design a function?

Function Engineering How do you design a function? Step 1: Write the program as if the function you want already existed print “This is the temperature in Farenheit: ”, tempf tempc = f_to_c(tempf) print “This is the temperature in Celsius: ”, tempc Always start this way!

Function Engineering How do you design a function? Step 2: Describe the inputs and output. Refer to their type. # Inputs: a number representing degrees farenheit # Return value: a number representing degrees celsius

Function Engineering How do you design a function? Step 3: Implement the function def f_to_c(num): result = (f – 32) / 9.0 * 5 return result

File Input and Output As a programmer, when would one use a file? As a programmer, what does one do with a file?

Important operations open a file close a file read data write data

Read a file in python myfile = open(“datafile.dat”, “r”) for line_of_text in myfile: print line_of_text File Gotcha: where does Python expect to find this file? Assumption: file is a sequence of lines historical convention

“Current Working Directory”

“Current Working Directory” in Python >>> import os # “os” stands for “operating system” >>> os.getcwd() '/Users/billhowe/Documents' This point is minor, but can be the source of confusion and bugs. A reasonable practice is just to work from the default location. On my systems: Windows: 'C:\\Python27' Mac: ‘/Users/billhowe/Documents’

Read a file in python myfile = open(“datafile.dat”, “r”) all_data_as_a_big_string = myfile.read() Another way to read data

Write to a file in python myfile = open(“output.dat”, “w”) myfile.write(“a bunch of data”) historical convention

Write to a file in python myfile = open(“output.dat”, “w”) myfile.write(4) historical convention Traceback (most recent call last): File "writefile.py", line 3, in myfile.write(4) TypeError: expected a character buffer object myfile.write(str(4))

Write to a file in python myfile = open(“output.dat”, “w”) myfile.write(“a line of text\n”) Use “\n” to indicate the end of a line