I. Making Problem Solutions General: Defining Functions ------------------------------------------ FUNCTION DEFINTIONS IN PYTHON Syntax: ::= def ( ) : ::= | , | ... ::= return ------------------------------------------ ------------------------------------------ FUNCTION DEFINITION EXAMPLES >>> def roomarea(width, length): return width * length >>> roomarea(6,7) 42 # in a file circlearea.py import math # calculate the area of a circle with the # given radius def circlearea(radius): return math.pi * radius**2 # back to the interpreter... >>> from circlearea import circlearea >>> circlearea(1) 3.141592653589793 >>> circlearea(2) 12.566370614359172 ------------------------------------------ ------------------------------------------ FUNCTION DEFINITIONS IN C /* in roomarea.c file */ /* Return the area of a room. */ double roomarea(double width, double length) { return width * length; } /* in circlearea.c file */ #include double circlearea(double radius) { return M_PI * radius * radius; } ------------------------------------------ ------------------------------------------ C FUNCTION SYNTAX ::= ::= | ::= ::= | int | short | long | float | double | void | .. ::= ( ) ::= | ::= | , ::= { } ------------------------------------------ A. testing in Python ------------------------------------------ TESTING WITH PYTEST IN PYTHON >>> import pytest >>> pytest.main(["test_circlearea.py", "--capture=sys"]) ------------------------------------------ II. Statements A. vs. expressions and declarations ------------------------------------------ BROAD CLASSIFICATION OF COMPUTATIONS Expressions like 2+3, or square(7) Statements like t = t+1, or print("hi!") (in C end with a semicolon, ;) Declarations like from math import isclose , or global total (in C gives type of names) ------------------------------------------ B. primitive statements in Python 1. assignment ------------------------------------------ ASSIGNMENT STATEMENT Purpose: give a (computed) value a name, name a constant (for readability) Syntax: ::= | ... ::= = | ... Examples: DAYS_IN_YEAR = 365.25 t = 1 t = t + 1 c = sqrt(a**2 + b**2) Semantics: ------------------------------------------ Does an assignment statment do too many different kinds of things? ------------------------------------------ ASSIGNMENT EXAMPLES >>> isum Traceback (most recent call last): File "", line 1, in isum NameError: name 'isum' is not defined >>> isum = 1 + 2 + 3 + 4 + 5 >>> print(isum) >>> isum = isum + 6 + 7 + 8 + 9 + 10 >>> print(isum) >>> isum += 11 + 12 + 13 + 14 + 15 >>> print(isum) >>> avg15 = isum/15 >>> print(avg15) ------------------------------------------ C. assert statements ------------------------------------------ ASSERT STATEMENTS Purpose: To state a property that must hold, to abort the computation otherwise Syntax: ::= assert | ... Examples: assert square(2) == 4 assert math.isclose(square(5), 25) Semantics: ------------------------------------------ If we know some property should be true, why assert it? D. pass statment ------------------------------------------ PASS STATEMENT Purpose: To tell the interpreter to do nothing Syntax: ::= pass | ... Example: pass Semantics: does nothing (has no effect) ------------------------------------------ Why would you want to have pass in your language? E. return statement ------------------------------------------ RETURN STATEMENT Purpose: To return a value from a function, To end execution of a function Syntax: ::= return | return | ... Static Semantics: A return statement may only occur inside a function definition's body Examples: def multiply(a, b): """Return the product of a and b.""" return a*b return a // (b-b) # never executed! Now the expression multiply(3,4)+5 has value 12+5 and the error from a // (b-b) never is executed def print_product(a,b): """Prints the product of a and b.""" print(a*b) return print("you'll never see this output!") Semantics: ------------------------------------------ Why have a way to explicitly stop processing in a function? F. calls ------------------------------------------ PROCEDURE CALLS Purpose: To perform some variation of a named task, to make code more understandable by chunking some statements together to allow abstraction (by specification and parameterization) Syntax: ::= ( ) | ( ) | ... ::= | , Guidance: you should only use functions that do not return a value (i.e., return None) as statements Examples: print("done") Semantics: ------------------------------------------ What would guess is the C syntax for these? 1. semantics is call-by-value ------------------------------------------ PYTHON USES CALL-BY-VALUE I.e., actual argument expressions are evaluated, in the calling context, and their values are passed to the function # second ignores its first argument >>> def second(a,b): return b >>> second(7//0, 3) Traceback (most recent call last): File "", line 1, in second(7//0, 3) ZeroDivisionError: integer division or modulo by zero # the error above shows Python doesn't use # call by name or lazy evaluation # assignarg assigns its argument >>> def assignarg(a): a = 3 >>> myarg = 5 >>> assignarg(myarg) >>> myarg 5 >>> # since myarg stays 5, assignarg >>> # only affected its local copy of a >>> # thus Python does not use >>> # either call by reference or value-result ------------------------------------------ 2. the DRY principle ------------------------------------------ ZEN FOR PROGRAMMERS, PART I Never write the same thing twice, instead put it in a procedure/fuction Example: To call pytest on a tst file test_f.py from IDLE you type import pytest pytest.main(["test_f.py", "--capture=sys"]) To avoid writing that twice, make a function: def run_pytest(filename): """Run pytest on filename (a string).""" import pytest pytest.main([filename, "--capture=sys"]) Use: >>> run_pytest("test_circlearea.py") >>> run_pytest("test_multiply.py") ------------------------------------------ G. sequencing ------------------------------------------ SUITES: STATEMENT LISTS Purpose: To execute actions in order (sequentially), to do several things describe a compound action, as in the body of a function Syntax: ::= ::= | Static Semantics: The list of statments must end with a newline (or a semicolon), and must all have the same indentation A is ended by a line with less indentation. Examples: print("Hello") print("World!") t = 7 print("t is", t) t = t +1 print("t is", t) Semantics: A such as S1 S2 is executed by ------------------------------------------ Why not run all statements in a statement-list in parallel instead of sequentially? III. Input and Output (I/O) in Python A. input/output devices/streams ------------------------------------------ STANDARD INPUT AND OUTPUT DEVICES In most operating systems (POSIX, Unix,...): stdin stdout ------> [ Program ] ------> \ stderr \-------> these are conventional names for I/O streams of characters stdin: standard input (often from a user) could be the terminal/console could be a file (prog file) stderr: standard error (usually to a user) usually a terminal/console/shell could be a file In Unix (POSIX) system shells: prog < in > out 2>errs runs the program with input from file "in" output going into file "out" and errors going into file "errs" prog1 out3 sets up a "pipeline" where prog1, prog2, and prog3 run in parallel, prog1's stdin is file in1 prog2's stdin is prog1's stdout prog3's stdin is prog2's stdout prog3's stdout is out3 ------------------------------------------ B. the problem, abstractly ------------------------------------------ THE PROBLEM OF INPUT AND OUTPUT Input Output ------------------------------------------ Have you ever interacted with a program that was hard to talk to in a way that was understandable? C. output 1. printing ------------------------------------------ OUTPUT IN PYTHON print() function handles simple output (by default to sys.stdout) this is like printf in C Examples: >>> print("hi") >>> t = 7 >>> print("The value of t is:", t) >>> t = t + 1 >>> print("Now t", t, sep='==') >>> t = t+1 >>> print("And now t is", t) ------------------------------------------ How did that space get in the output before 7? What does the sep keyword parameter do? ------------------------------------------ OPTIONAL KEYWORD ARGUMENTS TO PRINT NAME= Explanation ========================================= sep=' ' separator printed between the arguments end='\n' terminator printed after all the arguments file=sys.stdout output device flush=False forcibly flush the output device? Examples: print("Error!", file=sys.stderr, flush=True) ------------------------------------------ 2. other ways to print ------------------------------------------ THERE ARE OTHER WAYS TO PRINT We may see later: - write method on file objects - format strings - str.format() - printf style % operator formatting ------------------------------------------ D. character-based input in Python ------------------------------------------ READING A LINE OF INPUT WITH THE INPUT FUNCTION Reading a line from sys.stdin: >>> text = input("what number? ") >>> text >>> text + 3 # error! ------------------------------------------ 1. reading and parsing ------------------------------------------ PARSING READ INPUT To convert a string into a number or some other type, input is parsed. Parsing an int: myint = int(input("number? ")) Parsing a float: myint = float(input("number? ")) ------------------------------------------ ------------------------------------------ FOR YOU TO DO Write a Python program that reads 3 ints from standard input and prints their sum. ------------------------------------------ 2. input from files ------------------------------------------ READING FROM A FILE f = open(filename) # prepares to read from filename f_contents = f.read() # reads entire contents of f See modules file and fileinput... ------------------------------------------ IV. Interactive Programming A. two basic kinds of programs 1. batch programs ------------------------------------------ BATCH PROGRAMS input --> [ Processing ] --> output A general architecture for batch programs: def main(): data = get_input() result = process(data) print(make_report(result)) ------------------------------------------ What can batch programs be used for? 2. interactive programs ------------------------------------------ INTERACTIVE PROGRAMS User starts the program with the OS, then [ Program ] --> prompt0 | state0 v input1 --> [ Program ] --> output1, | state1 prompt1 v input2 --> [ Program ] --> output2, | state2 prompt2 v ... | state(N-1) v inputN --> [ Program ] --> outputN, promptN ------------------------------------------ What kinds of programs are interactive? V. Friday problems on Python I/O A. Output of repetative song lyrics ------------------------------------------ FOR YOU TO DO 1. Write a procedure to output the lyrics of the civil rights song "We Shall Overcome" with a minimum amount of repeated code. The lyrics are: We shall overcome We shall overcome We shall overcome Some day... (Oh,) deep in my heart I do believe We shall overcome Some day. We'll walk hand in hand We'll walk hand in hand We'll walk hand in hand Some day... (Oh,) deep in my heart I do believe We'll walk hand in hand Some day We shall live in peace We shall live in peace We shall live in peace Some day... (Oh,) deep in my heart I do believe We shall live in peace Some day We are not afraid We are not afraid We are not afraid Some day... (Oh,) deep in my heart I do believe We are not afraid Some day ------------------------------------------ Do you see the pattern? ------------------------------------------ ANOTHER SONG 2. Write a procedure to print the lyrics of the song "The wheels on the bus", i.e., The wheels on the bus go round and round round and round round and round The wheels on the bus go round and round All 'round the town. The whipers on the bus go swish, swish, swish swish, swish, swish swish, swish, swish The whipers on the bus go swish, swish, swish All 'round the town. The people on the bus go up and down up and down up and down The people on the bus go up and down All 'round the town. ------------------------------------------ What's the pattern of this one? ------------------------------------------ 99 BOTTLES OF BEER ON THE WALL 3. Write a procedure bottlesofbeer(n) to print the nth lyric of the song "99 Bottles of Beer on the Wall", i.e., for n == 99: 99 bottles of beer on the wall, 99 bottles of beer! You take one down, pass it around, 98 bottles of beer on the wall! ------------------------------------------ ------------------------------------------ SALES TOTAL 4. Write a procedure sales_total() to prompt for and read the prices of 3 pairs of shoes, and print the sum of the prices with a 6% sales tax added. Example (with user inputs to right of '?' on lines 1-3): 1st price? 64.99 2nd price? 73.95 3rd price? 102.00 Sales tax: $14.46 Total price: $138.94 ------------------------------------------