NLTK chapter 2, 4 (approximately) NLTK programming course Peter Ljunglöf

Size: px
Start display at page:

Download "NLTK chapter 2, 4 (approximately) NLTK programming course Peter Ljunglöf"

Transcription

1 NLTK chapter 2, 4 (approximately) NLTK programming course Peter Ljunglöf

2 Basic Python types (repetition) create search inspect modify str/ unicode s = abcd u = u abcd u = s.decode( utf-8 ) s = u.encode( utf-8 ) bc in s s.index( c ) == 2 s.index( bc ) == 1 s.startswith( ab ) s[2] == c s[ 1] == d s[:2] == ab s[1:-1] == bc s = s + efg s = s.replace( 34, # ) s = s.strip() s.join(list-or-tuple) tuple t = ( a, b, c, d ) t = tuple( abcd ) t = tuple(s) c in t bc not in t t.index( c ) == 2 t[2] == c t[ 1] == d t[:2] == ( a, b ) t[1:-1] == ( b, c ) t = t + ( e,) t = t + ( e, f, g ) c in w bc not in w w.index( c ) == 2 w[2] == c w[ 1] == d w[:2] == [ a, b ] w[1:-1] == [ b, c ] w.append( e ) w.extend(( e, f, g )) w.insert(1, x ) w[2] = q w.pop() list w = [ a, b, c, d ] w = list( abcd ) w = list(t) set e = set( abcd ) e = set(w) c in e bc not in e dict d = { a :9, b :8, c :7, d :6} d2 = dict((k, 33) for k in t) d2 = dict.fromkeys(t, 33) c in d bc not in d 2 e.add( e ) e.update(( e, f, g )) e.pop() e.remove( c ) d[ a ] == 12 d[ c ] == 1 sorted(d.keys()) == w d[ e ] = 999 d.pop( c )

3 Division in Python (repetition) Dividing two integers returns an int: >>> 3 / 2 1 Coerce to float first: >>> float(3) / or use Python 3 division: >>> from future import division >>> 3 /

4 Mutable / immutable (rep.) list, set, dict, nltk.freqdist, are mutable: (they have methods that modify themselves) >>> m = w = [ a, b, c, d ] >>> w[2] = # >>> m [ a, b, #, d ] tuple, str, unicode, int, float, are immutable: (you have to create a copy) >>> m = w = ( a, b, c, d ) >>> w[2]="#" TypeError: 'tuple' object does not support item assignment >>> w = w[:2] + ( #,) + w[3:] >>> m ( a, b, c, d ) 4

5 Reading and writing (rep.) Use Unicode strings: decode( utf-8 ) when reading from file encode( utf-8 ) when writing to file or use the codecs module Use the with statement for reading: with codecs.open( inputfile, r, encoding= utf-8 ) as F: content = F.read() or writing: with codecs.open( outputfile, w, encoding= utf-8 ) as F: F.write(content) 5

6 Python files and modules Standard file structure Importing modules Standard modules 6

7 Python file structure if you use non-ascii strings/comments # -*- coding: utf-8 -*- import before everything constant declarations: don t change them later the main function(s) before the helper(s) module docstring try to use docstrings instead of comments import sys import nltk module_constant = 42 another_constant = u non-ascii letters: åäö ÅÄÖ def main_function(input_file, another_arg): description of main function, and its arguments with open(input_file, r ) as F: another_function(x, y) def another_function(arg_1, arg_2): another function, its arguments and the return value return some_result if name == main : main_function(*sys.argv[1:]) 7 if the file is run as a script, call main function

8 Importing modules Never use this: from os.path import * from nltk.tag.tnt import * But it s okay to assign short names: import os.path as P import nltk.tag.tnt as tnt And sometimes this is okay: from glob import glob from os.path import basename, dirname from nltk.tag.tnt import TnT 8

9 Useful Python modules strings, unicode: re, codecs, unicodedata objects, data types: copy, pprint collections, heapq, bisect numbers: math, random iterators, higher-order functions: itertools, operator 9

10 More Python modules file system, operating system: os.path, glob time, os, sys, subprocess reading/writing special files: pickle, cpickle zlib, gzip, bz2, zipfile, tarfile html, cgi: urllib, HTMLParser, htmlentitydefs cgi, cgitb testing efficiency and correctness: timeit, doctest 10

11 Modules for strings re last lecture codecs: codecs.open(filename, mode, encoding) unicodedata: >>> unicodedata.name(u'\u00e4') 'LATIN SMALL LETTER A WITH DIAERESIS' >>> unicodedata.lookup('latin SMALL LETTER A WITH DIAER u'\xe4' >>> unicodedata.category(u'\xe4') 'Lu' # Letter Uppercase >>> unicodedata.category(u'2') 'Nd' # Number Decimal 11

12 Objects, data types deep copying of nested objects: copy.deepcopy(obj) pretty-printing of nested objects: pprint.pprint(object, [stream], [indent], [width], [depth]) default dictionaries: ctr = collections.defaultdict(int) ctr[ a ] # returns 0 ctr[ b ] += 3 # ctr[ b ] is now 3 priority queues; fast searching in sorted lists: heapq.heappush, heapq.heappop, heapq.heapify bisect.bisect_left, bisect.bisect_right 12

13 Numbers math functions: math.exp(x) math.pow(x, y) math.sin(x) math.pi == == == == ex xy sin x π math.log(x) math.sqrt(x) math.cos(x) math.e == == == == ln x x cos x e random numbers and sequences: random.random() random.randrange(10) random.randrange(100, 110) random.choice( abcdef ) random.sample( abcdef, 3) ==> ==> ==> ==> ==> xs = [1,2,3,4,5] random.shuffle(xs) # result: xs == [5, 1, 4, 2, 3] c [ d, a, c ]

14 File system, OS utilities pathname manipulation & expansion os.path.basename( /test/a/path.xml ) ==> path.xml os.path.dirname( /test/a/path.xml ) ==> /test/a glob.glob( test/ /.xml ) ==> [ test/a/path.xml, test/b/zip.xml ] time time.time() ==> nr seconds since the epoch (1970 on unix) time.strftime(format, [time]) ==> pretty-formatted time string os, sys, subprocess os.getcwd(), os.chdir(path), os.listdir(path), os.mkdir(path) os.environ, sys.argv, sys.platform sys.stdin, sys.stdout, sys.stderr subprocess.popen( ), subprocess.call( ) 14

15 And the rest pickle, cpickle: for reading/writing Python objects from/to files zlib, gzip, bz2, zipfile, tarfile: for reading/writing compressed data urllib, HTMLParser, htmlentitydefs: for reading/parsing html cgi, cgitb: for writing cgi scripts timeit, doctest: for testing efficiency and correctness of your code 15

16 NLTK Frequency distributions Conditional frequency distributions 16

17 NLTK frequency distribution FreqDist is a dictionary with counters initialize by giving a sequence of elements e.g., a string, a list of words, a list of bigrams a lot of useful methods compare (<, <=, ==, >=, >), add (+) statistics (B, N, Nr, freq, d[x]) get elements (hapaxes, max, samples, items) change (inc, update, d[x]=n) display (tabulate, plot) 17

18 ConditionalFreqDist a dictionary of FreqDist s initialize by a sequence of (cond, sample) pairs useful methods: ==, <, >, N, conditions, plot, tabulate however: keys, values, in, for in are missing examples: figure 2.1: words america vs citizen figure 2.2: word length in different languages figure 2.10: last letter of male/female names example 2.5: random text generation 18

19 Example cond. freq. dist modals in different text types (2.1 Brown) cfd = nltk.conditionalfreqdist( (genre, word) for genre in brown.categories() for word in brown.words(categories=genre)) genres = ['hobbies', 'lore', 'news', 'romance'] modals = ['can', 'could', 'may', 'might', 'must', 'will'] cfd.tabulate(conditions=genres, samples=modals) hobbies lore news romance can could may might must will

20 Python coding tips Coding style Procedural vs declarative Looping Named function arguments Defensive programming 20

21 Python coding style (sect. 4.3) Indent with 4 spaces; not tabs Don t write long lines; line break instead either use parentheses: if ( len(syllables) > 4 and len(syllables[2]) == 3 and syllables[2][2] in aeiou and syllables[2][3] == syllables[1][3] ): or add a backslash at the end of the line: if len(syllables) > 4 and len(syllables[2]) == 3 and \ syllables[2][2] in aeiou and \ syllables[2][3] == syllables[1][3]: With the risk of being repetitive: write docstrings! 21

22 Procedural vs declarative (4.3) Procedural: count = 0; total = 0 for token in tokens: count += 1 total += len(token) print float(total) / count Declarative: count = len(tokens) total = sum(len(t) for t in tokens) print float(total) / count The declarative style needs more infrastructure higher-order functions, generic classes 22

23 Sorted word list (1st attempt) A very procedural version: word_list = [] len_word_list = 0 i=0 while i < len(tokens): j=0 while j < len_word_list and word_list[j] < tokens[i]: j += 1 if j == 0 or tokens[i]!= word_list[j]: word_list.insert(j, tokens[i]) len_word_list += 1 i += 1 Note: we only use len, insert and lookup 23

24 Sorted word list (2nd) Using a for loop instead: word_list = [] for token in tokens: j=0 while j < len(word_list) and word_list[j] < token: j += 1 if j == 0 or token!= word_list[j]: word_list.insert(j, token) Note: we didn t need the i, just the token the for loop takes care of i and increasing it but, we do need j we rely on the fact that len() is efficient for lists 24

25 Sorted word list (3rd attempt) A very declarative version: word_list = sorted(set(tokens)) Note: we re not only using sorted and set since they rely on a lot of underlying methods 25

26 Looping in Python Other languages often use a counter: C: Pascal: for (i = 0; i < mylist_length; i++) { token = mylist[i] // do something with token } for i := 0 to mylist_length do begin token := mylist[i] {do something with token } end In Python we just loop over the elements: for token in tokens: # do something with token 26

27 Getting the index Sometimes we really want the list index too then we use the function enumerate: for i, token in enumerate(tokens): # now this holds: token == tokens[i] And sometimes we don t have list to loop over then we use the range function: for i in range(10): # i will be 0, 1, 2,, 9 range can take a start value: for i in range(1, 11): # i will be 1, 2, 3,, 10 27

28 Looping over two lists Sometimes we want to loop in parallel e.g., part-of-speech tagging def postag(word): if word in ( a, the, all ): return det else: return noun getting a list of postags: postaglist = [postag(w) for w in corpus_words] loop over each word and postag: for word, postag in zip(corpus_words, postaglist): # do something with the word and its postag 28

29 Loops vs comprehensions Getting all words that starts with a string: def prefix_search(prefix, words): result = set() for word in words: if word.startswith(prefix): result.add(word) return result The same thing using a set comprehension: def prefix_search(prefix, words): return set(word for word in words if word.startswith(prefix)) More declarative = shorter = more readable 29

30 Named arguments You can always call a function with named args: prefix_search( engl, brown.words()) vs prefix_search(prefix= engl, words=brown.words()) Often it is more readable: codecs.open( inputfile, wb, gbk ) vs codecs.open( inputfile, mode= wb, encoding= gbk ) But sometimes it doesn t give us anything: nltk.bigrams(brown.words()) vs nltk.bigrams(sequence=brown.words()) 30

31 Named arguments Since you can always use named args, it is especially important with good names: def prefix_search(prefix, words): vs def prefix_search(x, y): 31

32 Defensive programming use assert to check input arguments: def prefix_search(prefix, words): assert isinstance(prefix, (str, unicode)), prefix must be a string assert isinstance(words, (list, tuple, set)), words must be a sequ # the rest to check return values: def prefix_search(prefix, words): # the rest assert isinstance(result, set), result should be a set return result to check return values: search_result = prefix_search( engl, brown.words()) assert isinstance(search_result, set), search result should be a set assert search_result, search result should be non-empty 32

CS Programming Languages: Python

CS Programming Languages: Python CS 3101-1 - Programming Languages: Python Lecture 5: Exceptions / Daniel Bauer (bauer@cs.columbia.edu) October 08 2014 Daniel Bauer CS3101-1 Python - 05 - Exceptions / 1/35 Contents Exceptions Daniel Bauer

More information

Programming in Python Advanced

Programming in Python Advanced Programming in Python Advanced Duration: 3 days, 8 hours a day Pre-requisites: * Participants should be comfortable with the following technologies: Basic and working knowledge of the Pyton If new to the

More information

Introduction to Python

Introduction to Python Introduction to Python Version 1.1.5 (12/29/2008) [CG] Page 1 of 243 Introduction...6 About Python...7 The Python Interpreter...9 Exercises...11 Python Compilation...12 Python Scripts in Linux/Unix & Windows...14

More information

Python 3 Quick Reference Card

Python 3 Quick Reference Card Python 3 Quick Reference Card Data types Strings: s = "foo bar" s = 'foo bar' s = r"c:\dir\new" # raw (== 'c:\\dir\\new') s = """Hello world""" s.join(" baz") n = len(s) "Ala ma {} psy i {} koty".format(2,3)

More information

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

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming Intro to Programming Unit 7 Intro to Programming 1 What is Programming? 1. Programming Languages 2. Markup vs. Programming 1. Introduction 2. Print Statement 3. Strings 4. Types and Values 5. Math Externals

More information

STSCI Python Introduction. Class URL

STSCI Python Introduction. Class URL STSCI Python Introduction Class 2 Jim Hare Class URL www.pst.stsci.edu/~hare Each Class Presentation Homework suggestions Example files to download Links to sites by each class and in general I will try

More information

STA141C: Big Data & High Performance Statistical Computing

STA141C: Big Data & High Performance Statistical Computing STA141C: Big Data & High Performance Statistical Computing Lecture 1: Python programming (1) Cho-Jui Hsieh UC Davis April 4, 2017 Python Python is a scripting language: Non-scripting language (C++. java):

More information

Abstract Data Types. CS 234, Fall Types, Data Types Abstraction Abstract Data Types Preconditions, Postconditions ADT Examples

Abstract Data Types. CS 234, Fall Types, Data Types Abstraction Abstract Data Types Preconditions, Postconditions ADT Examples Abstract Data Types CS 234, Fall 2017 Types, Data Types Abstraction Abstract Data Types Preconditions, Postconditions ADT Examples Data Types Data is stored in a computer as a sequence of binary digits:

More information

1. BASICS OF PYTHON. JHU Physics & Astronomy Python Workshop Lecturer: Mubdi Rahman

1. BASICS OF PYTHON. JHU Physics & Astronomy Python Workshop Lecturer: Mubdi Rahman 1. BASICS OF PYTHON JHU Physics & Astronomy Python Workshop 2017 Lecturer: Mubdi Rahman HOW IS THIS WORKSHOP GOING TO WORK? We will be going over all the basics you need to get started and get productive

More information

PTN-105 Python programming. Course Outline. Prerequisite: basic Linux/UNIX and programming skills. Delivery Method: Instructor-led training (ILT)

PTN-105 Python programming. Course Outline. Prerequisite: basic Linux/UNIX and programming skills. Delivery Method: Instructor-led training (ILT) PTN-105 Python programming Prerequisite: basic Linux/UNIX and programming skills. Delivery Method: Instructor-led training (ILT) Course Length: 5 days Course Outline Module 1. Introduction Why python?

More information

CIS192: Python Programming Data Types & Comprehensions Harry Smith University of Pennsylvania September 6, 2017 Harry Smith (University of Pennsylvani

CIS192: Python Programming Data Types & Comprehensions Harry Smith University of Pennsylvania September 6, 2017 Harry Smith (University of Pennsylvani CIS192: Python Programming Data Types & Comprehensions Harry Smith University of Pennsylvania September 6, 2017 Harry Smith (University of Pennsylvania) CIS 192 Fall Lecture 2 September 6, 2017 1 / 34

More information

Python. Karin Lagesen.

Python. Karin Lagesen. Python Karin Lagesen karin.lagesen@bio.uio.no Plan for the day Basic data types data manipulation Flow control and file handling Functions Biopython package What is programming? Programming: ordered set

More information

Part IV. More on Python. Tobias Neckel: Scripting with Bash and Python Compact Max-Planck, February 16-26,

Part IV. More on Python. Tobias Neckel: Scripting with Bash and Python Compact Max-Planck, February 16-26, Part IV More on Python Compact Course @ Max-Planck, February 16-26, 2015 36 More on Strings Special string methods (excerpt) s = " Frodo and Sam and Bilbo " s. islower () s. isupper () s. startswith ("

More information

Course Title: Python + Django for Web Application

Course Title: Python + Django for Web Application Course Title: Python + Django for Web Application Duration: 6 days Introduction This course offer Python + Django framework ( MTV ) training with hands on session using Eclipse+Pydev Environment. Python

More information

Introduction to Python

Introduction to Python Introduction to Python Efstratios RAPPOS efstratios.rappos@heig-vd.ch Slide 1 2016 HEIG-VD SNU Summer School Background Easy and popular programming language Interpreted: must have python installed to

More information

An Introduction to Python

An Introduction to Python An Introduction to Python Day 2 Renaud Dessalles dessalles@ucla.edu Python s Data Structures - Lists * Lists can store lots of information. * The data doesn t have to all be the same type! (unlike many

More information

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes GIS 4653/5653: Spatial Programming and GIS More Python: Statements, Types, Functions, Modules, Classes Statement Syntax The if-elif-else statement Indentation and and colons are important Parentheses and

More information

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming 2017 Table of contents 1 2 Integers and floats Integer int and float float are elementary numeric types in. integer >>> a=1 >>> a 1 >>> type (a) Integers and floats Integer int and float

More information

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

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines. Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

Worksheet 6: Basic Methods Methods The Format Method Formatting Floats Formatting Different Types Formatting Keywords

Worksheet 6: Basic Methods Methods The Format Method Formatting Floats Formatting Different Types Formatting Keywords Worksheet 1: Introductory Exercises Turtle Programming Calculations The Print Function Comments Syntax Semantics Strings Concatenation Quotation Marks Types Variables Restrictions on Variable Names Long

More information

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

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

Large-Scale Networks

Large-Scale Networks Large-Scale Networks 3b Python for large-scale networks Dr Vincent Gramoli Senior lecturer School of Information Technologies The University of Sydney Page 1 Introduction Why Python? What to do with Python?

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Regular Expressions and Other Modules Raymond Yin University of Pennsylvania October 5, 2016 Raymond Yin (University of Pennsylvania) CIS 192 October 5, 2016 1 / 49 Outline 1

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Data Types Joseph Cappadona University of Pennsylvania September 03, 2015 Joseph Cappadona (University of Pennsylvania) CIS 192 September 03, 2015 1 / 32 Outline 1 Data Types

More information

SCHEME 10 COMPUTER SCIENCE 61A. July 26, Warm Up: Conditional Expressions. 1. What does Scheme print? scm> (if (or #t (/ 1 0)) 1 (/ 1 0))

SCHEME 10 COMPUTER SCIENCE 61A. July 26, Warm Up: Conditional Expressions. 1. What does Scheme print? scm> (if (or #t (/ 1 0)) 1 (/ 1 0)) SCHEME 0 COMPUTER SCIENCE 6A July 26, 206 0. Warm Up: Conditional Expressions. What does Scheme print? scm> (if (or #t (/ 0 (/ 0 scm> (if (> 4 3 (+ 2 3 4 (+ 3 4 (* 3 2 scm> ((if (< 4 3 + - 4 00 scm> (if

More information

Data type built into Python. Dictionaries are sometimes found in other languages as associative memories or associative arrays.

Data type built into Python. Dictionaries are sometimes found in other languages as associative memories or associative arrays. NETB 329 Lecture 4 Data Structures in Python Dictionaries Data type built into Python. Dictionaries are sometimes found in other languages as associative memories or associative arrays. 1 of 70 Unlike

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Probability and Simulations (With Other Modules) Harry Smith University of Pennsylvania October 11, 2017 Harry Smith (University of Pennsylvania) CIS 192 Lecture 7 October 11,

More information

Outline. Simple types in Python Collections Processing collections Strings Tips. 1 On Python language. 2 How to use Python. 3 Syntax of Python

Outline. Simple types in Python Collections Processing collections Strings Tips. 1 On Python language. 2 How to use Python. 3 Syntax of Python Outline 1 On Python language 2 3 4 Marcin Młotkowski Object oriented programming 1 / 52 On Python language The beginnings of Pythons 90 CWI Amsterdam, Guido van Rossum Marcin Młotkowski Object oriented

More information

Basic Python Revision Notes With help from Nitish Mittal

Basic Python Revision Notes With help from Nitish Mittal Basic Python Revision Notes With help from Nitish Mittal HELP from Documentation dir(module) help() Important Characters and Sets of Characters tab \t new line \n backslash \\ string " " or ' ' docstring

More information

PTN-102 Python programming

PTN-102 Python programming PTN-102 Python programming COURSE DESCRIPTION Prerequisite: basic Linux/UNIX and programming skills. Delivery Method Instructor-led training (ILT) Duration Four days Course outline Chapter 1: Introduction

More information

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

06/11/2014. Subjects. CS Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / ) Beginning with Python CS95003 - Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / 2014 Subjects 1) Beginning with Python 2) Variables 3) Strings 4) Basic arithmetic operators 5) Flow control 6) Comparison

More information

Downloaded from Chapter 2. Functions

Downloaded from   Chapter 2. Functions Chapter 2 Functions After studying this lesson, students will be able to: Understand and apply the concept of module programming Write functions Identify and invoke appropriate predefined functions Create

More information

Beyond Blocks: Python Session #1

Beyond Blocks: Python Session #1 Beyond Blocks: Session #1 CS10 Spring 2013 Thursday, April 30, 2013 Michael Ball Beyond Blocks : : Session #1 by Michael Ball adapted from Glenn Sugden is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike

More information

An Introduction to Python. Presented to OCPUG,

An Introduction to Python. Presented to OCPUG, An Introduction to Python Presented to OCPUG, 2010-11-30 Why Learn Python: Part 1 of 3 Easy to learn yet powerful Concise syntax: few words per idea expressed Usable for web, scripts, full blown standalone

More information

LECTURE 8 The Standard Library Part 2

LECTURE 8 The Standard Library Part 2 LECTURE 8 The Standard Library Part 2 SPECIALIZED DATA TYPES We continue our tour of the Python Standard Library with Specialized Data Types. These are data types that are not part of the core language,

More information

Language Basics. /* The NUMBER GAME - User tries to guess a number between 1 and 10 */ /* Generate a random number between 1 and 10 */

Language Basics. /* The NUMBER GAME - User tries to guess a number between 1 and 10 */ /* Generate a random number between 1 and 10 */ Overview Language Basics This chapter describes the basic elements of Rexx. It discusses the simple components that make up the language. These include script structure, elements of the language, operators,

More information

Introduction to Python! Lecture 2

Introduction to Python! Lecture 2 .. Introduction to Python Lecture 2 Summary Summary: Lists Sets Tuples Variables while loop for loop Functions Names and values Passing parameters to functions Lists Characteristics of the Python lists

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Regular Expressions and Other Modules Eric Kutschera University of Pennsylvania February 20, 2015 Eric Kutschera (University of Pennsylvania) CIS 192 February 20, 2015 1 / 32

More information

Lecture 4. Defining Functions

Lecture 4. Defining Functions Lecture 4 Defining Functions Academic Integrity Quiz Reading quiz about the course AI policy Go to http://www.cs.cornell.edu/courses/cs11110/ Click Academic Integrity in side bar Read and take quiz in

More information

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

Getting Started. Office Hours. CSE 231, Rich Enbody. After class By appointment send an  . Michigan State University CSE 231, Fall 2013 CSE 231, Rich Enbody Office Hours After class By appointment send an email 2 1 Project 1 Python arithmetic Do with pencil, paper and calculator first Idle Handin Help room 3 What is a Computer Program?

More information

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals:

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals: Numeric Types There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals: 1-123 +456 2. Long integers, of unlimited

More information

DaMPL. Language Reference Manual. Henrique Grando

DaMPL. Language Reference Manual. Henrique Grando DaMPL Language Reference Manual Bernardo Abreu Felipe Rocha Henrique Grando Hugo Sousa bd2440 flt2107 hp2409 ha2398 Contents 1. Getting Started... 4 2. Syntax Notations... 4 3. Lexical Conventions... 4

More information

A Little Python Part 1. Introducing Programming with Python

A Little Python Part 1. Introducing Programming with Python A Little Python Part 1 Introducing Programming with Python Preface Not a complete course in a programming language Many details can t be covered Need to learn as you go My programming style is not considered

More information

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

Python I. Some material adapted from Upenn cmpe391 slides and other sources Python I Some material adapted from Upenn cmpe391 slides and other sources Overview Names & Assignment Data types Sequences types: Lists, Tuples, and Strings Mutability Understanding Reference Semantics

More information

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017 SCHEME 8 COMPUTER SCIENCE 61A March 2, 2017 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

More information

JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1)

JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1) Technology & Information Management Instructor: Michael Kremer, Ph.D. Class 1 Professional Program: Data Administration and Management JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1) WHO

More information

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

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D 1/60 Interactive use $ python Python 2.7.5 (default, Mar 9 2014, 22:15:05) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin Type "help", "copyright", "credits" or "license" for more information.

More information

COMP519 Web Programming Lecture 20: Python (Part 4) Handouts

COMP519 Web Programming Lecture 20: Python (Part 4) Handouts COMP519 Web Programming Lecture 20: Python (Part 4) Handouts Ullrich Hustadt Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University of Liverpool Contents

More information

Part III Appendices 165

Part III Appendices 165 Part III Appendices 165 Appendix A Technical Instructions Learning Outcomes This material will help you learn how to use the software you need to do your work in this course. You won t be tested on it.

More information

Introduction to Python Part I

Introduction to Python Part I Introduction to Python Part I BaRC Hot Topics Bioinformatics and Research Computing Whitehead Institute Nov 29th 2018 http://barc.wi.mit.edu/hot_topics/ 1 About Python Object oriented language; easy to

More information

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators Objectives Chapter 4: Control Structures I (Selection) In this chapter, you will: Learn about control structures Examine relational and logical operators Explore how to form and evaluate logical (Boolean)

More information

CS S-02 Python 1. Most python references use examples involving spam, parrots (deceased), silly walks, and the like

CS S-02 Python 1. Most python references use examples involving spam, parrots (deceased), silly walks, and the like CS662-2013S-02 Python 1 02-0: Python Name python comes from Monte Python s Flying Circus Most python references use examples involving spam, parrots (deceased), silly walks, and the like Interpreted language

More information

GE PROBLEM SOVING AND PYTHON PROGRAMMING. Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING

GE PROBLEM SOVING AND PYTHON PROGRAMMING. Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING GE8151 - PROBLEM SOVING AND PYTHON PROGRAMMING Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING 1) Define Computer 2) Define algorithm 3) What are the two phases in algorithmic problem solving? 4) Why

More information

Python Basics. Lecture and Lab 5 Day Course. Python Basics

Python Basics. Lecture and Lab 5 Day Course. Python Basics Python Basics Lecture and Lab 5 Day Course Course Overview Python, is an interpreted, object-oriented, high-level language that can get work done in a hurry. A tool that can improve all professionals ability

More information

Privacy and Security in Online Social Networks Department of Computer Science and Engineering Indian Institute of Technology, Madras

Privacy and Security in Online Social Networks Department of Computer Science and Engineering Indian Institute of Technology, Madras Privacy and Security in Online Social Networks Department of Computer Science and Engineering Indian Institute of Technology, Madras Lecture - 25 Tutorial 5: Analyzing text using Python NLTK Hi everyone,

More information

APIs and API Design with Python

APIs and API Design with Python APIs and API Design with Python Lecture and Lab 5 Day Course Course Overview Application Programming Interfaces (APIs) have become increasingly important as they provide developers with connectivity to

More information

A Second Look At ML. Chapter Seven Modern Programming Languages, 2nd ed. 1

A Second Look At ML. Chapter Seven Modern Programming Languages, 2nd ed. 1 A Second Look At ML Chapter Seven Modern Programming Languages, 2nd ed. 1 Outline Patterns Local variable definitions A sorting example Chapter Seven Modern Programming Languages, 2nd ed. 2 Two Patterns

More information

DM550/DM857 Introduction to Programming. Peter Schneider-Kamp

DM550/DM857 Introduction to Programming. Peter Schneider-Kamp DM550/DM857 Introduction to Programming Peter Schneider-Kamp petersk@imada.sdu.dk http://imada.sdu.dk/~petersk/dm550/ http://imada.sdu.dk/~petersk/dm857/ TUPLES 2 Tuples as Immutable Sequences tuple =

More information

Lecture 4. Defining Functions

Lecture 4. Defining Functions Lecture 4 Defining Functions Academic Integrity Quiz Remember: quiz about the course AI policy Have posted grades for completed quizes Right now, missing ~130 enrolled students If did not receive at least

More information

ENGR 102 Engineering Lab I - Computation

ENGR 102 Engineering Lab I - Computation ENGR 102 Engineering Lab I - Computation Learning Objectives by Week 1 ENGR 102 Engineering Lab I Computation 2 Credits 2. Introduction to the design and development of computer applications for engineers;

More information

Introduction to Python

Introduction to Python May 25, 2010 Basic Operators Logicals Types Tuples, Lists, & Dictionaries and or Building Functions Labs From a non-lab computer visit: http://www.csuglab.cornell.edu/userinfo Running your own python setup,

More information

Lecture 3. Strings, Functions, & Modules

Lecture 3. Strings, Functions, & Modules 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

More information

Chapter 4: Control Structures I (Selection) Objectives. Objectives (cont d.) Control Structures. Control Structures (cont d.

Chapter 4: Control Structures I (Selection) Objectives. Objectives (cont d.) Control Structures. Control Structures (cont d. Chapter 4: Control Structures I (Selection) In this chapter, you will: Objectives Learn about control structures Examine relational and logical operators Explore how to form and evaluate logical (Boolean)

More information

Python INTRODUCTION: Understanding the Open source Installation of python in Linux/windows. Understanding Interpreters * ipython.

Python INTRODUCTION: Understanding the Open source Installation of python in Linux/windows. Understanding Interpreters * ipython. INTRODUCTION: Understanding the Open source Installation of python in Linux/windows. Understanding Interpreters * ipython * bpython Getting started with. Setting up the IDE and various IDEs. Setting up

More information

Introduction to Python Code Quality

Introduction to Python Code Quality Introduction to Python Code Quality Clarity and readability are important (easter egg: type import this at the Python prompt), as well as extensibility, meaning code that can be easily enhanced and extended.

More information

Intro. Scheme Basics. scm> 5 5. scm>

Intro. Scheme Basics. scm> 5 5. scm> Intro Let s take some time to talk about LISP. It stands for LISt Processing a way of coding using only lists! It sounds pretty radical, and it is. There are lots of cool things to know about LISP; if

More information

COMP1730/COMP6730 Programming for Scientists. Functions

COMP1730/COMP6730 Programming for Scientists. Functions COMP1730/COMP6730 Programming for Scientists Functions Lecture outline * Function definition. * Function calls & order of evaluation. * Assignments in functions; local variables. * Function testing. Functions

More information

Reading and Writing Files on Your Computer

Reading and Writing Files on Your Computer Reading and Writing Files on Your Computer Code Snippets HW2-3, HW2-4 Function Recap #!/usr/bin/env python3 Though it s called sentence in main, in replace_hello() that value is called text def replace_hello(text):

More information

CIS192: Python Programming

CIS192: Python Programming CIS192: Python Programming Introduction Harry Smith University of Pennsylvania January 18, 2017 Harry Smith (University of Pennsylvania) CIS 192 Lecture 1 January 18, 2017 1 / 34 Outline 1 Logistics Rooms

More information

CS 320: Concepts of Programming Languages

CS 320: Concepts of Programming Languages CS 320: Concepts of Programming Languages Wayne Snyder Computer Science Department Boston University Lecture 04: Basic Haskell Continued o Polymorphic Types o Type Inference with Polymorphism o Standard

More information

python 01 September 16, 2016

python 01 September 16, 2016 python 01 September 16, 2016 1 Introduction to Python adapted from Steve Phelps lectures - (http://sphelps.net) 2 Python is interpreted Python is an interpreted language (Java and C are not). In [1]: 7

More information

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define CS 6A Scheme Summer 207 Discussion 0: July 25, 207 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

More information

Introduction to programming Lecture 4: processing les and counting words

Introduction to programming Lecture 4: processing les and counting words Introduction to programming Lecture 4: processing les and counting words UNIVERSITY OF Richard Johansson September 22, 2015 overview of today's lecture le processing splitting into sentences and words

More information

Haskell: Lists. CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Friday, February 24, Glenn G.

Haskell: Lists. CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Friday, February 24, Glenn G. Haskell: Lists CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Friday, February 24, 2017 Glenn G. Chappell Department of Computer Science University of Alaska Fairbanks

More information

Introduction to Python: Data types. HORT Lecture 8 Instructor: Kranthi Varala

Introduction to Python: Data types. HORT Lecture 8 Instructor: Kranthi Varala Introduction to Python: Data types HORT 59000 Lecture 8 Instructor: Kranthi Varala Why Python? Readability and ease-of-maintenance Python focuses on well-structured easy to read code Easier to understand

More information

Script language: Python Data structures

Script language: Python Data structures Script language: Python Data structures Cédric Saule Technische Fakultät Universität Bielefeld 3. Februar 2015 Immutable vs. Mutable Previously known types: int and string. Both are Immutable but what

More information

Senthil Kumaran S

Senthil Kumaran S Senthil Kumaran S http://www.stylesen.org/ Agenda History Basics Control Flow Functions Modules History What is Python? Python is a general purpose, object-oriented, high level, interpreted language Created

More information

Be careful when deciding whether to represent data as integers or floats, and be sure that you consider all possible behaviors in computation.

Be careful when deciding whether to represent data as integers or floats, and be sure that you consider all possible behaviors in computation. Table of Contents: 1. Integers and floats 2. for vs. while loops 3. Checking boolean conditions with if/else 4. Docstrings 5. Changing collections while iterating over them 6. Directly Accessing Instance

More information

Python Tutorial. CSE 3461: Computer Networking

Python Tutorial. CSE 3461: Computer Networking Python Tutorial CSE 3461: Computer Networking 1 Outline Introduction to Python CSE Environment Tips for Python Primitive Types Tips for Encoding/Decoding an IP Address 2 Intro to Python Dynamically typed,

More information

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled Interpreted vs Compiled Python 1 Java Interpreted Easy to run and test Quicker prototyping Program runs slower Compiled Execution time faster Virtual Machine compiled code portable Java Compile > javac

More information

PYTHON FOR MEDICAL PHYSICISTS. Radiation Oncology Medical Physics Cancer Care Services, Royal Brisbane & Women s Hospital

PYTHON FOR MEDICAL PHYSICISTS. Radiation Oncology Medical Physics Cancer Care Services, Royal Brisbane & Women s Hospital PYTHON FOR MEDICAL PHYSICISTS Radiation Oncology Medical Physics Cancer Care Services, Royal Brisbane & Women s Hospital TUTORIAL 1: INTRODUCTION Thursday 1 st October, 2015 AGENDA 1. Reference list 2.

More information

Python Reference (The Right Way) Documentation

Python Reference (The Right Way) Documentation Python Reference (The Right Way) Documentation Release 0.1 Jakub Przywóski Sep 30, 2017 Contents 1 Contents 1 1.1 Introduction............................................... 1 1.2 Definitions................................................

More information

Webgurukul Programming Language Course

Webgurukul Programming Language Course Webgurukul Programming Language Course Take One step towards IT profession with us Python Syllabus Python Training Overview > What are the Python Course Pre-requisites > Objectives of the Course > Who

More information

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

How To Think Like A Computer Scientist, chapter 3; chapter 6, sections 6.189 Day 3 Today there are no written exercises. Turn in your code tomorrow, stapled together, with your name and the file name in comments at the top as detailed in the Day 1 exercises. Readings How

More information

Lecture 5. Defining Functions

Lecture 5. Defining Functions Lecture 5 Defining Functions Announcements for this Lecture Last Call Quiz: About the Course Take it by tomorrow Also remember the survey Readings Sections 3.5 3.3 today Also 6.-6.4 See online readings

More information

CS Summer 2013

CS Summer 2013 CS 1110 - Summer 2013 intro to programming -- how to think like a robot :) we use the Python* language (www.python.org) programming environments (many choices): Eclipse (free from www.eclipse.org), or

More information

Course May 18, Advanced Computational Physics. Course Hartmut Ruhl, LMU, Munich. People involved. SP in Python: 3 basic points

Course May 18, Advanced Computational Physics. Course Hartmut Ruhl, LMU, Munich. People involved. SP in Python: 3 basic points May 18, 2017 3 I/O 3 I/O 3 I/O 3 ASC, room A 238, phone 089-21804210, email hartmut.ruhl@lmu.de Patrick Böhl, ASC, room A205, phone 089-21804640, email patrick.boehl@physik.uni-muenchen.de. I/O Scientific

More information

c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords.

c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords. Chapter 1 File Extensions: Source code (cpp), Object code (obj), and Executable code (exe). Preprocessor processes directives and produces modified source Compiler takes modified source and produces object

More information

Python. Jae-Gil Lee Based on the slides by K. Naik, M. Raju, and S. Bhatkar. December 28, Outline

Python. Jae-Gil Lee Based on the slides by K. Naik, M. Raju, and S. Bhatkar. December 28, Outline Python Jae-Gil Lee Based on the slides by K. Naik, M. Raju, and S. Bhatkar December 28, 2011 1 Outline Introduction Installation and Use Distinct Features Python Basics Functional Example Comparisons with

More information

Programming in Python

Programming in Python 3. Sequences: Strings, Tuples, Lists 15.10.2009 Comments and hello.py hello.py # Our code examples are starting to get larger. # I will display "real" programs like this, not as a # dialog with the Python

More information

AI Programming CS S-02 Python

AI Programming CS S-02 Python AI Programming CS662-2013S-02 Python David Galles Department of Computer Science University of San Francisco 02-0: Python Name python comes from Monte Python s Flying Circus Most python references use

More information

COMP1730/COMP6730 Programming for Scientists. Strings

COMP1730/COMP6730 Programming for Scientists. Strings COMP1730/COMP6730 Programming for Scientists Strings Lecture outline * Sequence Data Types * Character encoding & strings * Indexing & slicing * Iteration over sequences Sequences * A sequence contains

More information

Table of Contents. Dive Into Python...1

Table of Contents. Dive Into Python...1 ...1 Chapter 1. Installing Python...2 1.1. Which Python is right for you?...2 1.2. Python on Windows...2 1.3. Python on Mac OS X...3 1.4. Python on Mac OS 9...5 1.5. Python on RedHat Linux...5 1.6. Python

More information

ECE 364 Software Engineering Tools Laboratory. Lecture 4 Python: Collections I

ECE 364 Software Engineering Tools Laboratory. Lecture 4 Python: Collections I ECE 364 Software Engineering Tools Laboratory Lecture 4 Python: Collections I 1 Lecture Summary Lists Tuples Sets Dictionaries Printing, More I/O Bitwise Operations 2 Lists list is a built-in Python data

More information

Python Tutorial. CS/CME/BioE/Biophys/BMI 279 Oct. 17, 2017 Rishi Bedi

Python Tutorial. CS/CME/BioE/Biophys/BMI 279 Oct. 17, 2017 Rishi Bedi Python Tutorial CS/CME/BioE/Biophys/BMI 279 Oct. 17, 2017 Rishi Bedi 1 Python2 vs Python3 Python syntax Data structures Functions Debugging Classes The NumPy Library Outline 2 Many examples adapted from

More information

Announcements for this Lecture

Announcements for this Lecture Lecture 6 Objects Announcements for this Lecture Last Call Quiz: About the Course Take it by tomorrow Also remember survey Assignment 1 Assignment 1 is live Posted on web page Due Thur, Sep. 18 th Due

More information

ENGR 101 Engineering Design Workshop

ENGR 101 Engineering Design Workshop ENGR 101 Engineering Design Workshop Lecture 2: Variables, Statements/Expressions, if-else Edgardo Molina City College of New York Literals, Variables, Data Types, Statements and Expressions Python as

More information

Python Programming Exercises 1

Python Programming Exercises 1 Python Programming Exercises 1 Notes: throughout these exercises >>> preceeds code that should be typed directly into the Python interpreter. To get the most out of these exercises, don t just follow them

More information

Lecture 4. while and for loops if else test Tuples Functions. Let us start Python Ssh (putty) to UNIX/Linux computer puccini.che.pitt.

Lecture 4. while and for loops if else test Tuples Functions. Let us start Python Ssh (putty) to UNIX/Linux computer puccini.che.pitt. Lecture 4 while and for loops if else test Tuples Functions Let us start Python Ssh (putty) to UNIX/Linux computer puccini.che.pitt.edu Launching Python > python Quick Reminder: while Loop Example >>>

More information

Lecture 4. Defining Functions

Lecture 4. Defining Functions Lecture 4 Defining Functions Academic Integrity Quiz Remember: quiz about the course AI policy Have posted grades for completed quizes Right now, missing ~90 enrolled students If did not receive perfect,

More information