Lecture 3: Functions & Modules

Similar documents
Lecture 3: Functions & Modules (Sections ) CS 1110 Introduction to Computing Using Python

Lecture 3. Functions & Modules

Lecture 3. Functions & Modules

Not-So-Mini-Lecture 6. Modules & Scripts

Lecture 4. Defining Functions

Lecture 4: Defining Functions

Lecture 3. Strings, Functions, & Modules

Lecture 4: Defining Functions (Ch ) CS 1110 Introduction to Computing Using Python

Lecture 2: Variables & Assignments

CS 1110 SPRING 2016: GETTING STARTED (Jan 27-28) First Name: Last Name: NetID:

CS 1110, LAB 1: EXPRESSIONS AND ASSIGNMENTS First Name: Last Name: NetID:

Lecture 17: Classes (Chapter 15)

Lecture 6: Specifications & Testing

Lecture 9. Memory and Call Stacks

Lecture 7. Memory in Python

Lecture 17: Classes (Chapter 15)

Lecture 5: Strings

Lecture 9: Memory in Python

Lecture 4. Defining Functions

Lecture 4. Defining Functions

CS 1110, LAB 2: FUNCTIONS AND ASSIGNMENTS

CSC 120 Computer Science for the Sciences. Week 1 Lecture 2. UofT St. George January 11, 2016

Conditionals & Control Flow

ENGR (Socolofsky) Week 02 Python scripts

Iteration and For Loops

Python for Non-programmers

Python Programming Exercises 1

Lecture 10: Lists and Sequences

Modules and Programs 1 / 14

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

CS 1110, LAB 2: ASSIGNMENTS AND STRINGS

CS 1110, LAB 10: ASSERTIONS AND WHILE-LOOPS 1. Preliminaries

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

CS 1110, LAB 3: STRINGS; TESTING

2. Modules, Scripts, and I/O

Lecture 7: Objects (Chapter 15) CS 1110 Introduction to Computing Using Python

Lecture 18: Using Classes Effectively (Chapter 16)

Introduction to Python. Genome 559: Introduction to Statistical and Computational Genomics Prof. James H. Thomas

Lecture 1. Course Overview Types & Expressions

Lecture 8: Conditionals & Control Flow (Sections ) CS 1110 Introduction to Computing Using Python

Copied from: on 3/20/2017

Introduction to Python. Genome 559: Introduction to Statistical and Computational Genomics Prof. James H. Thomas

Lecture 11: Iteration and For-Loops

Lecture 19: Subclasses & Inheritance (Chapter 18)

CS 1110, LAB 3: MODULES AND TESTING First Name: Last Name: NetID:

CS1110 Lab 1 (Jan 27-28, 2015)

Course Overview, Python Basics

Lecture 26: Sorting CS 1110 Introduction to Computing Using Python

CSE 115. Introduction to Computer Science I

CS 102 Lab 3 Fall 2012

Lecture 1: Introduction, Types & Expressions

Introduction to Python

Module 01: Introduction to Programming in Python

CSCI 121: Anatomy of a Python Script

Introduction to Computer Programming in Python Dr. William C. Bulko. Data Types

CS 1110: Introduction to Computing Using Python Lists and Sequences

Lecture 24: Loop Invariants

Lecture 3. Input, Output and Data Types

Programming for Engineers in Python. Recitation 1

Com S 127 Lab 2. For the first two parts of the lab, start up Wing 101 and use the Python shell window to try everything out.

CS 1110: Introduction to Computing Using Python Loop Invariants

Fundamentals: Expressions and Assignment

A Little Python Part 1. Introducing Programming with Python

Lecture 2. Variables & Assignment

Modules and scoping rules

IE 555 Programming for Analytics

CS1 Lecture 4 Jan. 24, 2018

PREPARING FOR PRELIM 1

Hello World! Computer Programming for Kids and Other Beginners. Chapter 1. by Warren Sande and Carter Sande. Copyright 2009 Manning Publications

Laboratory Exercise #0

CS 1110 SPRING 2016: LAB 3: PRACTICE FOR A2 (Feb 23-24)

Lecture 5. Defining Functions

What you get When you install Python for your computer, you get a number of features:

Lecture 1. Course Overview, Python Basics

Lecture 20: While Loops (Sections 7.3, 7.4)

CMSC 201 Spring 2018 Lab 01 Hello World

Computer Lab 1: Introduction to Python

Programming for Engineers in Python. Autumn

Chris Simpkins (Georgia Tech) CS 2316 Data Manipulation for Engineers Python Overview 1 / 9

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

Get It Interpreter Scripts Arrays. Basic Python. K. Cooper 1. 1 Department of Mathematics. Washington State University. Basics

Lecture 1. Course Overview, Python Basics

CMSC 201 Spring 2017 Lab 01 Hello World

CS Lecture 18: Card Tricks. Announcements. Slides by D. Gries, L. Lee, S. Marschner, W. White

Python Input, output and variables. Lecture 23 COMPSCI111/111G SS 2018

Introduction to Computation for the Humanities and Social Sciences. CS 3 Chris Tanner

ECS Baruch Lab 5 Spring 2019 Name NetID (login, like , not your SUID)

Python for Finance. Introduction and Basics of Python. Andras Niedermayer

Getting Started. Excerpted from Hello World! Computer Programming for Kids and Other Beginners

nostarch.com/pfk For bulk orders, please contact us at

6.S189 Homework 1. What to turn in. Exercise 1.1 Installing Python. Exercise 1.2 Hello, world!

Algorithms and Programming I. Lecture#12 Spring 2015

CS1110. Lecture 6: Function calls

CS1 Lecture 3 Jan. 22, 2018

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

Using IDLE for

4. Modules and Functions

CS 1110, LAB 03: STRINGS; TESTING First Name: Last Name: NetID:

CS Introduction to Computational and Data Science. Instructor: Renzhi Cao Computer Science Department Pacific Lutheran University Spring 2017

Lecture 10. Memory in Python

Transcription:

http://www.cs.cornell.edu/courses/cs1110/2018sp Lecture 3: Functions & Modules (Sections 3.1-3.3) CS 1110 Introduction to Computing Using Python [E. Andersen, A. Bracy, D. Gries, L. Lee, S. Marschner, C. Van Loan, W. White]

CS1110 Spring 2018 Announcements Check course page for announcements! http://www.cs.cornell.edu/courses/cs1110/2018sp ENGRG 1010. AEW workshops still space - can enroll through Student Center 1-credit S/U course 2-hour weekly workshop work on related problem sets Full? Or need a different time? https://tinyurl.com/aew-request 2

Things to Do Before Next Class Read Sections 3.4-3.11 If you haven t already: install Anaconda Python & Komodo on your machine play around with python a bit! 3

Function Calls Python supports expressions with math-like functions A function in an expression is a function call Will explain the meaning of this later Function expressions have the form: fun(x,y, ) Some math functions built into Python: round(2.34) max(a+3,24) function name argument Arguments can be any expression 4

Always-available Built-in Functions You have seen many functions already Type casting functions: int(), float(), bool() Get type of a value: type() Exit function: exit() Longer list: Arguments go in (), but name() refers to function in general http://docs.python.org/3/library/functions.html 5

The Lack of Built-in Functions Python contains few built-in functions Missing many functions you would expect Example: cos(), sqrt() Many more functions are available through built-in modules 6

Modules Libraries of functions and variables To access a module, use the import command: import <module name> Can then access functions like this: <module name>.<function name>(<arguments>) Example: >>> import math >>> math.cos(2.0) -0.4161468365471424 7

Necessity of import C:\> python With import This is the Windows command line (Mac looks different) >>> import math >>> math.cos(2.0) -0.4161468365471424 C:\> python Without import >>> math.cos(2.0) Python is unaware of what math is Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'math' is not defined 8

Module Variables Modules can have variables, too Can access them like this: <module name>.<variable name> Example: >>> import math >>> math.pi 3.141592653589793 9

Visualizing functions & variables So far just built-ins > python >>> int() float() str() type() print() 10

Visualizing functions & variables So far just built-ins Now we ve defined a new variable > python >>> x = 7 >>> int() float() str() type() print() x 7 11

Visualizing functions & variables So far just built-ins Now we ve defined a new variable Now we ve imported a module > python >>> x = 7 >>> import math >>> int() float() str() type() print() x 7 math cos() sqrt() e pi 12

module help After importing a module, see what functions and variables are available: >>> help(<module name>) 13

Reading the Python Documentation https://docs.python.org/3/library/math.html 14

A Closer Reading of the Python Documentation https://docs.python.org/3/library/math.html Function name Possible arguments Module What the function evaluates to 15

Other Useful Modules io Read/write from files random Generate random numbers Can pick any distribution string Useful string functions sys Information about your OS 16

Making your Own Module Write in a text editor We use Komodo Edit but any editor will work 17

Interactive Shell vs. Modules Python Interactive Shell Module Type python at command line Type commands after >>> Python executes as you type Written in text editor Loaded through import Python executes statements when import is called Section 2.4 in your textbook discusses a few differences 18

Module Text It shows how modules work""" x = 1+2 x = 3*x my_module.py Single line # my_module.py comment (not executed) """This is a simple module. Commands Executed on import Docstring (note the Triple Quotes) Acts as a multi-line comment Useful for code documentation 19

Modules Must be in Working Directory! Must run python from same folder as the module 20

Using a Module (my_module.py) # my_module.py Module Text Python Command Shell >>> """This is a simple module. It shows how modules work""" x = 1+2 x = 3*x 21

Using a Module (my_module.py) # my_module.py Module Text Python Command Shell >>> import my_module """This is a simple module. It shows how modules work""" Needs to be the same name as the file without the.py x = 1+2 x = 3*x 22

On import. Module Text Python Command Shell # my_module.py Python does not >>> execute import module (because of #) """This is a simple module. It shows how modules work""" Python does not execute (because of """ and """) x = 1+2 x = 3*x Python executes this. x x3 9 Python executes this. variable x stays within the module 23

Clicker Question! # my_module.py Module Text Python Command Shell >>> import my_module """This is a simple module. It shows how modules work""" x = 1+2 x = 3*x After you hit Return here what will python print next? (A) >>> (B) 9 >>> (C) an error message (D) The text of my_module.py (E) Sorry, no clue. 24

Clicker Answer # my_module.py Module Text Python Command Shell >>> import my_module """This is a simple module. It shows how modules work""" x = 1+2 x = 3*x After you hit Return here what will python print next? (A) >>> (B) 9 >>> (C) an error message (D) The text of my_module.py (E) Sorry, no clue. 25

Using a Module (my_module.py) Module Text # my_module.py """This is a simple module. It shows how modules work""" Python Command Shell >>> import my_module >>> my_module.x module name x = 1+2 x = 3*x The variable we want to access 26

Using a Module (my_module.py) Module Text # my_module.py """This is a simple module. It shows how modules work""" Python Command Shell >>> import my_module >>> my_module.x 9 x = 1+2 x = 3*x 27

You Must import C:\> python >>> import my_module >>> my_module.x 9 C:\> python >>> my_module.x Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'my_module' is not defined 28

You Must Use the Module Name >>> import my_module >>> my_module.x 9 >>> import my_module >>> x Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'x' is not defined 29

What does the docstring do? Module Text Python Command Shell # my_module.py """This is a simple module. It shows how modules work""" x = 1+2 x = 3*x 30

from command You can also import like this: from <module> import <function name> Example: >>> from math import pi >>> pi 3.141592653589793 Note that you don t need the module name now 31

from command You can also import everything from a module: from <module> import * Example: >>> from math import * >>> pi 3.141592653589793 >>> cos(pi) -1.0 Module functions now behave like built-in functions 32

Dangers of Importing Everything >>> e = 12345 >>> from math import * >>> e 2.718281828459045 e was overwritten! 33

Avoiding from Keeps Variables Separate >>> e = 12345 >>> import math >>> math.e 2.718281828459045 >>> e 12345 34

Ways of Executing Python Code 1. running the Python Interactive Shell 2. importing a module 3. NEW: running a script 35

Running a Script From the command line, type: python <script filename> Example: C:\> python my_module.py C:\> looks like nothing happened Actually, something did happen Python executed all of my_module.py 36

Running my_module.py as a script my_module.py Command Line # my_module.py Python does not C:\> execute python (because module.py of #) """This is a simple module. It shows how modules work""" Python does not execute (because of """ and """) x = 1+2 x = 3*x Python executes this. x x3 9 Python executes this. 37

Running my_module.py as a script my_module.py # my_module.py """This is a simple my_module. It shows how modules work""" x = 1+2 x = 3*x Command Line C:\> python my_module.py C:\> when the script ends, all memory used by my_module.py is deleted thus, all variables get deleted (including x) so there is no evidence that the script ran 38

Clicker Question my_module.py Command Line # my_module.py """This is a simple my_module. It shows how modules work""" x = 1+2 x = 3*x C:\> python my_module.py C:\> my_module.x After you hit Return here what will be printed next? (A) >>> (B) 9 >>> (C) an error message (D) The text of my_module.py (E) Sorry, no clue. 39

Clicker Answer my_module.py Command Line # my_module.py """This is a simple my_module. It shows how modules work""" x = 1+2 x = 3*x C:\> python my_module.py C:\> my_module.x After you hit Return here what will be printed next? (A) >>> (B) 9 >>> (C) an error message (D) The text of my_module.py (E) Sorry, no clue. 40

Creating Evidence that the Script Ran New (very useful!) command: print print (<expression>) print evaluates the <expression> and writes the value to the console 41

my_module.py vs. script.py my_module.py script.py # my_module.py # script.py """ This is a simple module. It shows how modules work""" """ This is a simple script. It shows why we use print""" x = 1+2 x = 3*x Only difference x = 1+2 x = 3*x print(x) 42

Running script.py as a script Command Line C:\> python script.py 9 C:\> script.py # script.py """ This is a simple script. It shows why we use print""" x = 1+2 x = 3*x print(x) 43

Subtle difference about script mode Interactive mode script.py C:\> python >>> x = 1+2 >>> x = 3*x >>> x 9 >>> print(x) 9 >>> # script.py """ This is a simple script. It shows why we use print""" x = 1+2 x = 3*x print(x) # note: in script mode, you will # not get output if you just type x 44

Modules vs. Scripts Module Provides functions, variables import it into Python shell Script Behaves like an application Run it from command line Files look the same. Difference is how you use them. 45

Next Time: Defining Functions Today we created a module with a variable Have not discussed how to make a function Example: >>> import math >>> math.cos(2.0) -0.4161468365471424 we want to make functions like this 46

47