Programming for Linguists An Introduction to Python 24/11/2011.

Slides:



Advertisements
Similar presentations
Introduction to Computing Science and Programming I
Advertisements

String and Lists Dr. Benito Mendoza. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list List.
CS0004: Introduction to Programming Repetition – Do Loops.
Basic Control Structures Control order of execution of statements sequential selection iteration - Repeat some action while a certain condition is true.
Iteration This week we will learn how to use iteration in C++ Iteration is the repetition of a statement or block of statements in a program. C++ has three.
Loops – While, Do, For Repetition Statements Introduction to Arrays
Python November 18, Unit 7. So Far We can get user input We can create variables We can convert values from one type to another using functions We can.
Intro to Robots Conditionals and Recursion. Intro to Robots Modulus Two integer division operators - / and %. When dividing an integer by an integer we.
The switch Statement, DecimalFormat, and Introduction to Looping
Fundamentals of Python: From First Programs Through Data Structures
Lilian Blot CORE ELEMENTS COLLECTIONS & REPETITION Lecture 4 Autumn 2014 TPOP 1.
Programming for Linguists An Introduction to Python 17/11/2011.
CC0002NI – Computer Programming Computer Programming Er. Saroj Sharan Regmi Week 7.
Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language.
REPETITION STRUCTURES. Topics Introduction to Repetition Structures The while Loop: a Condition- Controlled Loop The for Loop: a Count-Controlled Loop.
Fundamentals of Python: First Programs
Python – Part 4 Conditionals and Recursion. Modulus Operator Yields the remainder when first operand is divided by the second. >>>remainder=7%3 >>>print.
More Looping Structures
Agenda Control Flow Statements Purpose test statement if / elif / else Statements for loops while vs. until statements case statement break vs. continue.
Python Programming Chapter 8: Lists Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.
Programming for Engineers in Python Sawa 2015 Lecture 2: Lists and Loops 1.
Strings The Basics. Strings can refer to a string variable as one variable or as many different components (characters) string values are delimited by.
CIT 590 Intro to Programming Lecture 4. Agenda Doubts from HW1 and HW2 Main function Break, quit, exit Function argument names, scope What is modularity!
Programming in Python Part III Dr. Fatma Cemile Serçe Atılım University
If statements while loop for loop
Chapter 8 Iteration Dept of Computer Engineering Khon Kaen University.
Logic Our programs will have to make decisions in terms of what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if.
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
Math 15 Introduction to Scientific Data Analysis Lecture 8 Python Programming – Part 2 University of California, Merced.
JavaScript, Fourth Edition
1 Lecture 9 Shell Programming – Command substitution Regular expressions and grep Use of exit, for loop and expr commands COP 3353 Introduction to UNIX.
Loops & List Intro2CS – week 3 1. Loops -- Motivation Sometimes we want to repeat a certain set of instructions more than once. The number of repetitions.
By Austin Laudenslager AN INTRODUCTION TO PYTHON.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 5 Repetition Structures.
CSC 1010 Programming for All Lecture 4 Loops Some material based on material from Marty Stepp, Instructor, University of Washington.
Python Mini-Course University of Oklahoma Department of Psychology Day 3 – Lesson 11 Using strings and sequences 5/02/09 Python Mini-Course: Day 3 – Lesson.
Python Basics  Functions  Loops  Recursion. Built-in functions >>> type (32) >>> int(‘32’) 32  From math >>>import math >>> degrees = 45 >>> radians.
ITERATION. Iteration Computers are often used to automate repetitive tasks. Repeating identical or similar tasks without making errors is something that.
CS190/295 Programming in Python for Life Sciences: Lecture 6 Instructor: Xiaohui Xie University of California, Irvine.
Exception Handling and String Manipulation. Exceptions An exception is an error that causes a program to halt while it’s running In other words, it something.
Regular expressions Day 11 LING Computational Linguistics Harry Howard Tulane University.
9. ITERATIONS AND LOOP STRUCTURES Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)
Control Flow (Python) Dr. José M. Reyes Álamo. 2 Control Flow Sequential statements Decision statements Repetition statements (loops)
While loops. Iteration We’ve seen many places where repetition is necessary in a problem. We’ve been using the for loop for that purpose For loops are.
Loops (While and For) CSE 1310 – Introduction to Computers and Programming 1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
Python Files and Lists. Files  Chapter 9 actually introduces you to opening up files for reading  Chapter 14 has more on file I/O  Python can read.
 Python for-statements can be treated the same as for-each loops in Java Syntax: for variable in listOrstring: body statements Example) x = "string"
Control Flow (Python) Dr. José M. Reyes Álamo. 2 Control Flow Sequential statements Decision statements Repetition statements (loops)
Python – Part 4 Conditionals and Recursion. Conditional execution If statement if x>0:# CONDITION print (‘x is positive’) Same structure as function definition.
Loops ( while and for ) CSE 1310 – Introduction to Computers and Programming Alexandra Stefan 1.
String and Lists Dr. José M. Reyes Álamo. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list.
PH2150 Scientific Computing Skills Control Structures in Python In general, statements are executed sequentially, top to bottom. There are many instances.
Python Basics.
String and Lists Dr. José M. Reyes Álamo.
Control Flow (Python) Dr. José M. Reyes Álamo.
Chapter 6: Loops.
CSc 120 Introduction to Computer Programing II Adapted from slides by
Python: Control Structures
Warm-up Program Use the same method as your first fortune cookie project and write a program that reads in a string from the user and, at random, will.
Topics Introduction to Repetition Structures
Agenda Control Flow Statements Purpose test statement
While loops The while loop executes the statement over and over as long as the boolean expression is true. The expression is evaluated first, so the statement.
CS190/295 Programming in Python for Life Sciences: Lecture 6
3 Control Statements:.
Lists A list is an ordered set of values, where each value is identified by an index. The values that make up a list are called its elements. Lists are.
String and Lists Dr. José M. Reyes Álamo.
More Looping Structures
Based on slides created by Bjarne Stroustrup & Tony Gaddis
More Looping Structures
Presentation transcript:

Programming for Linguists An Introduction to Python 24/11/2011

From Last Week E x 1) def name( ): name = raw_input("what is your first name? ") length = len(name) last_letter = name[-1] print name," contains ", lenght, " letter(s) and ends with a(n) ”,last_letter name( )

Ex 2) def play( ): sentence = raw_input(“Sentence? ”) print sentence.upper( ) print sentence.lower( ) print sentence.title( ) print "The lowest index of the letter 'a' is”,sentence.index("a") if sentence.index("a")>3: print sentence.replace ("a","e") play( )

Ex 3) def tkofschip( ): verb=raw_input ("Please enter the root of a Dutch verb\n") if verb.endswith ("t") or verb.endswith("k") or verb.endswith ("f") or verb.endswith("s") or verb.endswith("c") or verb.endswith("h") or verb.endswith("p"): print verb+"te" else: print verb+"de" tkofschip( )

Fruitful Functions Functions which produce a result: calling the function generates a value >>>len(“python”) 6 Often contain a return statement: return immediately from the function and use the following expression as a return value

Try: def word_length1(word): return len(word) def word_length2(word): print len(word) a = word_length1(“hello”) b = word_length2(“hello”) type(a) type(b)

The return statement gives you a value which you can use in the rest of your script The print statement does not give you a value You can use multiple return statements, e.g.: def absolute_value(x): if x >= 0: return x else: return -x

You can return a value, a variable, a function, a boolean expression As soon as a return statement executes, the function terminates Code that appears after a return statement = dead code

Write a compare function that returns ‘1’ if x > y, ‘0’ if x == y, and ‘-1’ if x < y

def compare(x, y): if x == y: return 0 elif x > y: return 1 else: return -1

As we saw: one function can call another A function can also call itself A function that calls itself = recursive The process = recursion Recursion

Try this: def countdown(n): if n<=0: print ‘Happy Newyear!’ else: print n n = n - 1 countdown(n) countdown(10)

If a recursion never reaches a base case, it goes on making recursive calls forever  the program never terminates Generally not a good idea Python reports an error message when the maximum recursion depth is reached Infinite Recursion

e.g. def recurse( ): recurse( ) recurse( )

The while statement: used to perform identical or similar tasks def countdown(n): while n > 0: print n n = n – 1 print “Happy Newyear!”

3 steps: evaluate the condition, yielding True or False if the condition is True, execute the statements inside the body and return to step 1 ( = loop) if the condition is False, exit the while statement and continue with the execution of the next statement Mind the difference in indentation between the statements inside and outside the while statement !

The statements inside the body should change the value of one or more variables so that the condition becomes False at a certain point If a loop goes on forever = infinite loop You can use the break statement to jump out of the loop

This program will echo the keyboard input until the user types “done” while True: line = raw_input (“> ”) if line == “done”: break print line

Write a function that takes a string as an argument and prints the letters one by one using a while statement while index < len(fruit): letter = fruit[index] print letter index = index + 1

def print_letters(word): index = 0 while index < len(word): letter = word[index] print letter index = index + 1

Write a similar function that takes a string as an argument and prints the letters backward using a while statement

def print_backward(word): index = len(word) – 1 while index >= 0: letter = word[index] print letter index = index - 1

Lists A list is a sequence of values The values can be of any type The values = elements/items A list is always in between [ ] To create a new list: list = [10, “cheese”, 5.6, “this is a sentence”]

A list can contain another list (nested list): [‘hello’, 15, [‘my name is’, ‘Franky’]] to access them: index method list[:20] you can change existing lists numbers = [17, 21] numbers[1] = 10 print numbers [17, 10]

A list index works the same way as a string index: any integer expression can be used as an index if you try to read or write an element that does not exist, you get an IndexError if an index has a negative value, it counts backward from the end of the list the in operator also works on lists

Traversing a List For loop words = [‘work’, ‘run’, ‘play’, ‘jump’] for word in words: print word

if you need to update all elements: range function numbers = [1, 3, 5, 10] for elem in range(len(numbers)): numbers[elem] = numbers[elem] * 2 print numbers This loop traverses the list and updates each element

List Operations The + operator concatenates lists the * operator repeats a list a given number of times The slice operator [n:m] gives you a slice of the list

Try this: a = [1, 2, 3] b = [4, 5] print a + b print a*2 print a[1:2]

List Methods Python provides methods that operate on lists append method: a = [‘a’, ‘b’, ‘c’] a.append(‘d’) print a [‘a’, ‘b’, ‘c’, ‘d’]

deleting elements: using the index in the list: pop method  modifies the list and returns the element that was removed del method  modifies the list without returning the removed element remove method  if you do not know the index of the element

t = ['a', 'b', 'c’, ‘c’, ‘d’] x = t.pop(1) print t print x del t[0] print t t.remove(‘c’) print t

s = [2,1,4,3] s.count( )  4 s.sort( )  [1, 2, 3, 4] s.extend([5,6,7])  [1,2,3,4,5,6,7] s.insert(0,8)  [8,1,2,3,4,5,6,7] s.reverse( )  [7, 6, 5, 4, 3, 2, 1, 8]

From String to List From a word to a list of letters: list( ) s = “spam” print list(s) [‘s’, ‘p’, ‘a’, ‘m’] From a sentence to a list of words:.split( ) s = “This is a sentence” print s.split( ) [‘This’, ‘is’, ‘a’, ‘sentence’]

The split( ) function can also be used to split a string on other characters besides spaces s = “spam-spam-spam” print s.split(“-”) [‘spam’, ‘spam’, ‘spam’] “-” is called a delimiter in this case

From List to String Join( ) is the inverse of split( ) l = [‘this’, ‘is’, ‘a’, ‘sentence’] delimiter = “ ” delimiter.join(l) “this is a sentence”

List Arguments You can also pass a list into a function as argument def del_first(list1): del list1[0] return list1 del_first([1,2,3])

Many linguistic processing tasks involve pattern matching, e.g..startswith( ).endswith( ) To use regular expressions in Python we need to import the re library import re Regular Expressions for Detecting Word Patterns

.Wildcard, matches any character ^abcMatches some pattern abc at the start of a string abc$Matches some pattern abc at the end of a string [abc]Matches one of a set of characters [A-Z0-9] Matches one of a range of characters Some Basic Regular Expression Meta-characters

a|b|cMatches one of the specified strings (disjunction) *Zero or more of the previous item(s) +One or more of the previous item(s) ?Zero or one of the previous item(s) (i.e. optional) {n}Exactly n repeats where n is a non-negative integer {n,}At least n repeats

{,n}No more than n repeats {m,n}At least m and no more than n repeats a(b|c)+Parentheses that indicate the scope of the operators e.g. w(i|e|ai|oo)t matches wit, wet, wait and woot Matches any token In general, when using regular expressions it is best to use r'...' before the regular expressions

Counting all vowels in a given word: word='supercalifragilisticexpialidocious' vowels = re.findall(r'[aeiou]', word) nr_vowels = len(vowels) The re.findall( ) function finds all (non- overlapping) matches of the given regular expression

You can find a list of all regular expressions operations in Python on:

For Next Week Ex 1) Write a script that reads 5 words that are typed in by a user and tells the user which word is shortest and longest Ex 2) Write a function that takes a sentence as an argument and calculates the average word length of the words in that sentence

Ex 3) Take a short text of about 5 sentences. Write a script that will split up the text into sentences (tip: use the punctuation as boundaries) and calculates the average sentence length, the average word length and the standard deviation for both values How to calculate the standard deviation: tion

No lecture next week Some extra exercises will be posted on Blackboard instead.

Thank you!