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

Similar documents
Lecture 3: Functions & Modules

Lecture 3. Functions & Modules

Lecture 3. Functions & Modules

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

Lecture 4. Defining Functions

Lecture 4: Defining Functions

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

Lecture 3. Strings, Functions, & Modules

Lecture 6: Specifications & Testing

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 2: Variables & Assignments

CS 1110, LAB 2: ASSIGNMENTS AND STRINGS

Lecture 5: Strings

ENGR (Socolofsky) Week 02 Python scripts

Lecture 17: Classes (Chapter 15)

Lecture 9: Memory in Python

CS 1110, LAB 2: FUNCTIONS AND ASSIGNMENTS

Lecture 9. Memory and Call Stacks

Conditionals & Control Flow

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

Lecture 7. Memory in Python

Modules and Programs 1 / 14

Python for Non-programmers

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

Lecture 10: Lists and Sequences

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

Python Programming Exercises 1

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

4. Modules and Functions

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

Lecture 4. Defining Functions

Fundamentals: Expressions and Assignment

IE 555 Programming for Analytics

CSCI 121: Anatomy of a Python Script

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

Introduction to Python

Downloaded from Chapter 2. Functions

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

Iteration and For Loops

Module 01: Introduction to Programming in Python

Lecture 19: Subclasses & Inheritance (Chapter 18)

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.

Modules and scoping rules

Lecture 20: While Loops (Sections 7.3, 7.4)

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

Lecture 11: Iteration and For-Loops

Computer Lab 1: Introduction to Python

CS 102 Lab 3 Fall 2012

Lecture 26: Sorting CS 1110 Introduction to Computing Using Python

CS 1110: Introduction to Computing Using Python Lists and Sequences

Python 1: Introduction to Python 1 / 19

Lecture 1. Types, Expressions, & Variables

CS 115 Lecture 4. More Python; testing software. Neil Moore

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

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

CS1110 Lab 1 (Jan 27-28, 2015)

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

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

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

Programming for Engineers in Python. Recitation 1

Lecture 24: Loop Invariants

2. Modules, Scripts, and I/O

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

Operating System Interaction via bash

Starting. Read: Chapter 1, Appendix B from textbook.

Fun with functions! Built-in and user-defined functions

Lecture 3. Input, Output and Data Types

7. MODULES. Rocky K. C. Chang October 17, (Based on Dierbach)

CS 1110: Introduction to Computing Using Python Loop Invariants

Using IDLE for

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration

CS 115 Data Types and Arithmetic; Testing. Taken from notes by Dr. Neil Moore

Lecture 18: Using Classes Effectively (Chapter 16)

Course Overview, Python Basics

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

Programming for Engineers in Python. Autumn

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

Algorithms and Programming I. Lecture#12 Spring 2015

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

Python for Astronomers. Week 1- Basic Python

Python 1: Intro! Max Dougherty Andrew Schmitt

Com S 127x - Lab 6 1. READING FLOWCHARTS WITH CONDITIONAL ACTIONS!

Object-Based Programming. Programming with Objects

CSI31 Lecture 5. Topics: 3.1 Numeric Data Types 3.2 Using the Math Library 3.3 Accumulating Results: Factorial

Laboratory Exercise #0

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

Copied from: on 3/20/2017

CS1 Lecture 3 Jan. 22, 2018

ENGR 102 Engineering Lab I - Computation

The Math Class. Using various math class methods. Formatting the values.

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

cs3157: another C lecture (mon-21-feb-2005) C pre-processor (3).

Using Type Annotations in Python. by Philippe Fremy / IDEMIA

Lecture 4. Defining Functions

A Little Python Part 1. Introducing Programming with Python

from scratch A primer for scientists working with Next-Generation- Sequencing data Chapter 1 Text output and manipulation

Introduction to Python Code Quality

Transcription:

http://www.cs.cornell.edu/courses/cs1110/2019sp 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]

Function Calls Function expressions have the form: fun(x,y, ) function name argument Some math functions built into Python: >>> x = 5 >>> y = 4 >>> bigger = max(x, y) >>> bigger 5 >>> a = round(3.14159265) >>> a 3 Arguments can be any expression 2

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 3

Modules Many more functions available via built-in 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 >>> p = math.ceil(3.14159265) >>> p 4 4

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

Visualizing functions & variables So far just built-ins C:\> python >>> int() float() str() type() print() 6

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

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

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

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

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 11

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 12

Making your Own Module Write in a text editor We recommend Atom but any editor will work 13

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 14

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

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

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 17

On import. Module Text Python Command Shell # my_module.py Python does not execute (because of #) >>> import my_module """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. my_module Python executes this. x 3 9 x variable x stays within the module 18

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. 19

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. 20

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 variable we want to access module name x = 1+2 x = 3*x my_module x x3 9 21

You must import Windows command line (Mac looks different) C:\> python >>> import math >>> p = math.ceil(3.14159) >>> p 4 math p 4 With import ceil() sqrt() e pi 2.718281 3.14159 C:\> python Without import >>> math.ceil(3.14159) Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'math' is not defined Python unaware of what math is 22

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 my_module my_module x x3 9 x x3 9 23

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 24

from command You can also import like this: from <module> import <function name> Example: >>> from math import pi >>> pi no longer need the module name 3.141592653589793 pi 3.141592653589793 25

from command You can also import everything from a module: from <module> import * Example: >>> from math import * >>> pi 3.141592653589793 >>> ceil(pi) 4 ceil() sqrt() e pi 2.718281828459045 3.141592653589793 Module functions now behave like built-in functions 26

Dangers of Importing Everything >>> e = 12345 >>> from math import * >>> e 2.718281828459045 e 12345 2.718281828459045 e was overwritten! ceil() sqrt() pi 3.141592653589793 27

Avoiding from Keeps Variables Separate >>> e = 12345 >>> import math >>> math.e 2.718281828459045 >>> e 12345 e 12345 math ceil() sqrt() e pi 2.718281 3.14159 28

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

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 30

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. 31

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

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. 33

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. 34

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

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) 36

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) 37

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 38

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. 39