Lecture 3. Strings, Functions, & Modules

Similar documents
Lecture 3. Functions & Modules

Announcements For This Lecture

Lecture 3. Functions & Modules

Announcements For This Lecture

Lecture 5: Strings

Lecture 4. Defining Functions

Lecture 3: Functions & Modules

CS 1110, LAB 2: ASSIGNMENTS AND STRINGS

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

Python 1: Intro! Max Dougherty Andrew Schmitt

Built-in Types of Data

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

Lecture 7. Memory in Python

Scripting Languages. Python basics

CSCA20 Worksheet Strings

Lecture 1. Types, Expressions, & Variables

PREPARING FOR PRELIM 1

Announcements for this Lecture

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

Lecture 2: Variables & Assignments

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

Python Intro GIS Week 1. Jake K. Carr

Downloaded from Chapter 2. Functions

Strings. Genome 373 Genomic Informatics Elhanan Borenstein

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

CMSC201 Computer Science I for Majors

Python for Non-programmers

Lecture 1. Course Overview Types & Expressions

Midterm 1 Review. Important control structures. Important things to review. Functions Loops Conditionals

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

Student Number: Instructor: Brian Harrington

ECE 364 Software Engineering Tools Lab. Lecture 3 Python: Introduction

Python Day 3 11/28/16

Copied from: on 3/20/2017

CSE 115. Introduction to Computer Science I

Lecture 2. Variables & Assignment

CIS192 Python Programming. Robert Rand. August 27, 2015

MEIN 50010: Python Strings

Python Tutorial. Day 1

Lecture 1. Course Overview, Python Basics

Visual C# Instructor s Manual Table of Contents

The Practice of Computing Using PYTHON. Chapter 4. Working with Strings. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Language Reference Manual

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

CMSC201 Computer Science I for Majors

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

Getting Started Values, Expressions, and Statements CS GMU

Python I. Some material adapted from Upenn cmpe391 slides and other sources

Lecture 9. Memory and Call Stacks

SAMS Programming A/B. Lecture #1 Introductions July 3, Mark Stehlik

Lab 1: Course Intro, Getting Started with Python IDLE. Ling 1330/2330 Computational Linguistics Na-Rae Han

Programming for Engineers in Python. Recitation 1

CS 1110 Prelim 1 October 15th, 2015

Variables, Functions and String Formatting

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

CIS192: Python Programming

1 Strings (Review) CS151: Problem Solving and Programming

6. Data Types and Dynamic Typing (Cont.)

Strings are actually 'objects' Strings

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

'...' "..." escaping \u hhhh hhhh '''...''' """...""" raw string Example: r"abc\txyz\n" in code;

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

Getting Started. Office Hours. CSE 231, Rich Enbody. After class By appointment send an . Michigan State University CSE 231, Fall 2013

Module 3: Strings and Input/Output

Sequence of Characters. Non-printing Characters. And Then There Is """ """ Subset of UTF-8. String Representation 6/5/2018.

Introduction to Python

[301] Strings. Tyler Caraza-Harter

Lecture 4: Defining Functions

Lecture 12. Lists (& Sequences)

Python 1: Introduction to Python 1 / 19

Week 6: Review. Java is Case Sensitive

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

Lecture 2 Tao Wang 1

CSC 108H: Introduction to Computer Programming. Summer Marek Janicki

Python The way of a program. Srinidhi H Asst Professor Dept of CSE, MSRIT

CSc Introduction to Computing

CS 1110, LAB 2: FUNCTIONS AND ASSIGNMENTS

Programming for Engineers in Python. Autumn

Python Strings. Stéphane Vialette. LIGM, Université Paris-Est Marne-la-Vallée. September 25, 2012

CS1110 Lab 1 (Jan 27-28, 2015)

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

Types, lists & functions

Lecture 1. Course Overview, Python Basics

Python. Karin Lagesen.

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

Working with Strings. Husni. "The Practice of Computing Using Python", Punch & Enbody, Copyright 2013 Pearson Education, Inc.

Algorithms and Programming I. Lecture#12 Spring 2015

Python for ArcGIS. Lab 1.

Accelerating Information Technology Innovation

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

06/11/2014. Subjects. CS Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / ) Beginning with Python

Functions & Variables !

Professor: Sana Odeh Lecture 3 Python 3.1 Variables, Primitive Data Types & arithmetic operators

CS1 Lecture 3 Jan. 18, 2019

CS 102 Lab 3 Fall 2012

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

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

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

CS 320: Concepts of Programming Languages

Transcription:

Lecture 3 Strings, Functions, & Modules

Labs this Week Lab 1 is due at the beginning of your lab If it is not yet by then, you cannot get credit Only exception is for students who added late (Those students should talk to me) Should spend time entirely on Lab 2 Similar format to last week Next weeks lab is substantially longer 9/2/14 Strings & Functions 2

Readings for Next Two Lectures This Lecture Sections 3.1-3.4 Sections 8.1, 8.2, 8.4, 8.5 Browse the Python API Do not need to read all of it Look over built-in functions PLive: Activities 3-3.1, 3-3.2, 3-3.4 (not 3-3.3), 3-4.1, 3-4.2. (Old) Lecture on VideoNote Thursday Complete Chapter 3 [xkcd.com] 9/2/14 Strings & Functions 3

String: Text as a Value String are quoted characters 'abc d' (Python prefers) "abc d" (most languages) How to write quotes in quotes? Delineate with other quote Example: " ' " or ' " ' What if need both " and '? Solution: escape characters Format: \ + letter Special or invisible chars Type: str Char Meaning \' single quote \" double quote \n new line \t tab \\ backslash 9/2/14 Strings & Functions 4

String are Indexed s = 'abc d' s = 'Hello all' 0 1 2 3 4 a b c d 0 1 2 3 4 5 H e l l o 6 a 7 l 8 l Access characters with [] s[0] is 'a' s[4] is 'd' s[5] causes an error s[0:2] is 'ab' (excludes c) s[2:] is 'c d' Called string slicing What is s[3:6]? A: 'lo a' B: 'lo' C: 'lo ' D: 'o ' E: I do not know 9/2/14 Strings & Functions 5

String are Indexed s = 'abc d' s = 'Hello all' 0 1 2 3 4 a b c d 0 1 2 3 4 5 H e l l o 6 a 7 l 8 l Access characters with [] s[0] is 'a' s[4] is 'd' s[5] causes an error s[0:2] is 'ab' (excludes c) s[2:] is 'c d' Called string slicing What is s[3:6]? A: 'lo a' B: 'lo' C: 'lo ' CORRECT D: 'o ' E: I do not know 9/2/14 Strings & Functions 6

String are Indexed s = 'abc d' s = 'Hello all' 0 1 2 3 4 a b c d 0 1 2 3 4 5 H e l l o 6 a 7 l 8 l Access characters with [] s[0] is 'a' s[4] is 'd' s[5] causes an error s[0:2] is 'ab' (excludes c) s[2:] is 'c d' Called string slicing What is s[:4]? A: 'o all' B: 'Hello' C: 'Hell' D: Error! E: I do not know 9/2/14 Strings & Functions 7

String are Indexed s = 'abc d' s = 'Hello all' 0 1 2 3 4 a b c d 0 1 2 3 4 5 H e l l o 6 a 7 l 8 l Access characters with [] s[0] is 'a' s[4] is 'd' s[5] causes an error s[0:2] is 'ab' (excludes c) s[2:] is 'c d' Called string slicing What is s[:4]? A: 'o all' B: 'Hello' C: 'Hell' CORRECT D: Error! E: I do not know 9/2/14 Strings & Functions 8

Other Things We Can Do With Strings Operation in: s 1 in s 2 Tests if s 1 a part of s 2 Say s 1 a substring of s 2 Function len: len(s) Value is # of chars in s Evaluates to an int Evaluates to a bool Examples: s = 'abracadabra' 'a' in s == True 'cad' in s == True 'foo' in s == False Examples: s = 'abracadabra len(s) == 11 len(s[1:5]) == 4 s[1:len(s)-1] == 'bracadabr' 9/2/14 Strings & Functions 9

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, ) Examples (math functions that work in Python): round(2.34) max(a+3,24) Arguments can be any expression function name argument 9/2/14 Strings & Functions 10

Built-In Functions You have seen many functions already Type casting functions: int(), float(), bool() Dynamically type an expression: type() Help function: help() Getting user input: raw_input() print <string> is not a function call It is simply a statement (like assignment) But it is in Python 3.x: print(<string>) Arguments go in (), but name() refers to function in general 9/2/14 Strings & Functions 11

Method: A Special Type of Function Methods are unique (right now) to strings Like a function call with a string in front Usage: string.method(x,y ) The string is an implicit argument Example: upper() s = 'Hello World' s.upper() == 'HELLO WORLD' s[1:5].upper() == 'ELLO' 'abc'.upper() == 'ABC' Will see why we do it this way later in course 9/2/14 Strings & Functions 12

Examples of String Methods s 1.index(s 2 ) Position of the first instance of s 2 in s 1 s 1.count(s 2 ) s = 'abracadabra' s.index('a') == 0 s.index('rac') == 2 s.count('a') == 5 Number of times s 2 appears inside of s 1 s.strip() A copy of s with whitespace removed at ends ' a b '.strip() == 'a b' See Python Docs for more 9/2/14 Strings & Functions 13

Built-in Functions vs Modules The number of built-in functions is small http://docs.python.org/2/library/functions.html Missing a lot of functions you would expect Example: cos(), sqrt() Module: file that contains Python code A way for Python to provide optional functions To access a module, the import command Access the functions using module as a prefix 9/2/14 Strings & Functions 14

>>> import math >>> math.cos(0) 1.0 >>> cos(0) Traceback (most recent call last): Example: Module math File "<stdin>", line 1, in <module> NameError: name 'cos' is not defined >>> math.pi 3.141592653589793 >>> math.cos(math.pi) -1.0 To access math functions Functions require math prefix! Module has variables too! 9/2/14 Strings & Functions 15

Example: Module math >>> import math >>> math.cos(0) 1.0 >>> cos(0) Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'cos' is not defined >>> math.pi 3.141592653589793 >>> math.cos(math.pi) -1.0 To access math functions Functions require math prefix! Module has variables too! io Read/write from files random Generate random numbers Can pick any distribution string Other Modules Useful string functions sys Information about your OS 9/2/14 Strings & Functions 16

Reading the Python Documentation Function name Possible arguments Module What the function evaluates to http://docs.python.org/library 9/2/14 Strings & Functions 17

Using the from Keyword >>> import math >>> math.pi 3.141592653589793 >>> from math import pi >>> pi 3.141592653589793 >>> from math import * >>> cos(pi) -1.0 Must prefix with module name No prefix needed for variable pi No prefix needed for anything in math Be careful using from! Using import is safer Modules might conflict (functions w/ same name) What if import both? Example: Turtles Older version of A4 2 modules: turtle, tkturtle Both have func. Turtle() 9/2/14 Strings & Functions 18

A String Puzzle (Extraction Practice) Given: a string with a parenthesis pair inside s = 'labs are (usually) every week' Goal: expression for substring inside parentheses Step 1: Find the open parenthesis start = s.index('(') Step 2: Store part of string after parenthesis in tail tail = s[start+1:] Step 3: Get the part of the tail before close parenthesis tail[:tail.index(')')] 9/2/14 Strings & Functions 19

Given: A string that is a list of words separated by commas, and spaces in between each comma: pets = 'cat, dog, mouse, lion Goal: Want second element with no spaces or commas. Put result inside of variable answer Where, in the following sequence of commands, is there a (conceptual) error that prevents our goal? A: startcomma = info.index(',') B: tail = info[startcomma+1:] C: endcomma = tail.index(',') D: df = tail[:endcomma] E: this sequence achieves the goal

Given: A string that is a list of words separated by commas, and spaces in between each comma: pets = 'cat, dog, mouse, lion Goal: Want second element with no spaces or commas. Put result inside of variable answer Where, in the following sequence of commands, is there a (conceptual) error that prevents our goal? A: startcomma = info.index(',') B: tail = info[startcomma+1:] +2 instead, or use C: endcomma = tail.index(',') D: df = tail[:endcomma] tail[:endcomma].strip() E: this sequence achieves the goal