Programming for Linguists An Introduction to Python 29/11/2012.

Slides:



Advertisements
Verwante presentaties
Let me tell you about... (De Voltooid Tegenwoordige Tijd)
Advertisements

The stock market will go up De beurswaarden zullen stijgen YESNO JA NEEN Is Jefken a good person ? Is Jefken een goed mens ? YES NO JA NEEN Is Lonny a.
HM-ES-th1 Les 9 Hardware/Software Codesign with SystemC.
Deltion College Engels C1 Spreken [Edu/003] thema “Oprah at Deltion” can-do : kan duidelijke, gedetailleerde beschrijving geven van complexe onderwerpen,
Order placed Should be Nederland Netherlands can be removed here, just Scancorner Instead of ‘undefined’ -> ‘geen’ New logo should be displayed here. COUNTS.
Requirements -People are able to make their own memorial page, called a memori -The website will be build first in Dutch for extension.nl, then copied.
Een alternatief voorstel Naar aanleiding van bestudering van de IAASB voorstellen denkt de NBA na over een alternatief. Dit alternatief zal 26 september.
Deltion College Engels C1 Gesprekken voeren [Edu/002]/ subvaardigheid lezen thema: Order, order…. can-do : kan een bijeenkomst voorzitten © Anne Beeker.
ETHOS PROJECT: PROGRESS Follow-up & feedback end of year 1.
Past Simple – Past Continuous
Teams on the frontline Geert Stroobant De Heide - Balans
Reading Test – answers explained Class 8A Chapter 6.
From: Julia larissa Ian and Maartje.. SCHOON WATER PROJECT Door Julia, larissa, Ian, en Maartje.
Virgielcollege Mede mogelijk gemaakt door uw Eerstejaarsch Commissie.
Accessible Instructional Materials. § Discussion: Timely access to appropriate and accessible instructional materials is an inherent component.
Nieuwe wegen in ontwerpen met CAD
WIJ ZIJN ZELFBEDRUIPEND IN ONS HOME WIJ KWEKEN ONZE GROENTEN EN FRUIT WIJ GEBRUIKEN REGENWATER VOOR KOKEN EN BADEN ZONNEPANELEN GEVEN ONS WARMTE EN LICHT.
zaterdag 19 juli 2014 Saturday, 19 July 2014 I see what you don’t see I come from another galaxy My earthal life was not the intention I was meant.
IST Status Gerrit van Nieuwenhuizen IST-MIT meeting BNL, July 24, 2008
Beyond Big Grid – Amsterdam 26 september 2012 Enquette 77 ingevulde enquettes, waarvan 60 met gebruikservaring = Mainly Computer Science.
PROJECTCOMPETENCE MANAGEMENT SCREENCompetenciesEdit1 DESCRIPTIONCompetencies in the “Competentie beheer” is a link to the editwizard for competencies.
AAHA (voor intern gebruik)
SQL injections en meer... PERU. web application vulnerabilities Cross Site Scripting (21.5%) SQL Injection (14%) PHP includes (9.5%) Buffer overflows.
Applets as didactical tools for the learning of algebra
In samenwerking met het Europees Sociaal Fonds en het Hefboomkrediet The role of APEL in career coaching and competence management Competence navigation.
ontwik idee - keling dag 3 goals today Develop “criteria” to help you evaluate & select your ideas Some tools from Tassouls book to help you do this.
Probleem P 1 is reduceerbaar tot P 2 als  afbeelding  :P 1  P 2 zo dat: I yes-instantie van P 1   (I) yes-instantie van P 2 als ook:  polytime-algoritme,
ERIC Combine search terms with Boolean operators Next = click.
Netwerk Algorithms: Shortest paths1 Shortest paths II Network Algorithms 2004.
ALBRECHT DÜRER'S MAGIC SQUARE ALBRECHT DÜRERS MAGISCH VIERKANT
Vrije Universiteit amsterdamPostacademische Cursus Informatie Technologie Universal Modeling Language … why you need models? Models are necessary to communicate,
Tussentoets Digitale Techniek. 1 november 2001, 11:00 tot 13:00 uur. Opmerkingen: 1. Als u een gemiddeld huiswerkcijfer hebt gehaald van zes (6) of hoger,
From computer power and human reason. Joseph Weizenbaum.
Organizing Organization is the deployment of resources to achieve strategic goals. It is reflected in Division of labor into specific departments & jobs.
Deltion College Engels B1 Gesprek voeren [Edu/001]
Deltion College Engels C1 Schrijven [Edu/002] thema: CV and letter of application can-do : kan complexe zakelijke teksten schrijven © Anne Beeker Alle.
Deltion College Engels B1 Gesprekken voeren [Edu/005] thema: applying for a job can-do : kan een eenvoudig sollicitatiegesprek voeren © Anne Beeker Alle.
Deltion College Engels B1 Gesprekken voeren [Edu/007] theme: Can I have my money back… can-do : kan minder routinematige situaties aan © Anne Beeker Alle.
Deltion College Engels C1 Gesprekken voeren [Edu/004]/ thema: There are lies, damned lies and statistics... can-do : kan complexe informatie en adviezen.
Deltion College Engels B2 Schrijven [Edu/004] thema: (No) skeleton in the cupboard can-do: kan een samenhangend verhaal schrijven © Anne Beeker Alle rechten.
Deltion College Engels C1 Luisteren [Edu/001] thema: It’s on tv can-do : kan zonder al te veel inspanning tv-programma’s begrijpen.
Deltion College Engels B2 Gesprekken voeren [Edu/006]/subvaardigheid schrijven notulen en kort voorstel thema: ‘What shall we do about non- active group.
Deltion College Engels B1 En Spreken/Presentaties [Edu/007] Thema: Soap(s) can-do : kan met enig detail verslag doen van ervaringen, in dit geval, rapporteren.
Deltion College Engels En Projectopdracht [Edu/001] thema: research without borders can-do/gesprekken voeren : 1. kan eenvoudige feitelijke informatie.
Deltion College Engels C1 Spreken/Presentaties [Edu/006] thema ‘I hope to convince you of… ‘ can-do : kan een standpunt uiteenzetten voor een publiek van.
Deltion College Engels B1 Schrijven [Edu/004]/ subvaardigheid lezen thema: reporting a theft can-do : kan formulieren waarin meer informatie gevraagd wordt,
Writing exercise This one goes into your language portfolio!!! You have until the end of the week to hand it in… (So you have a little longer than it says.
Future (toekomst) Je krijgt 2 verschillende vormen van Future.
Kenmerken van een persoonlijke brief
Rational Unified Process RUP Jef Bergsma. Iterations –Inception –Elaboration –Construction –Transition De kernbegrippen (Phases)
© Shopping 2020 TITLE Date Subtitle Logo Gastheer Logo Voorzitter.
Combining pattern-based and machine learning methods to detect definitions for eLearning purposes Eline Westerhout & Paola Monachesi.
Just as an introduction for SDP-partners, this is a theoretical ppt on properties of triangles in which first, 3 properties are formulated and visualised.
Deltion College Engels B1 Lezen [no. 001] can-do : 2 products compared.
Deltion College Engels B1 Gesprekken voeren [Edu/006] thema: Look, it says ‘No smoking’… can-do : kan minder routinematige zaken regelen © Anne Beeker.
Deltion College Engels B2 Lezen [Edu/003] thema: Topical News Lessons: The Onestop Magazine can-do: kan artikelen en rapporten begrijpen die gaan over.
Deltion College Engels B2 Spreken [Edu/001] thema: What’s in the news? can-do : kan verslag doen van een gebeurtenis en daarbij meningen met argumenten.
AWK A Pattern scanning and processing language made by Aho Weinberger Kernighan and explained by Albert Montijn.
Deltion College Engels B1 Spreken [Edu/001] thema: song texts can-do : kan een onderwerp dat mij interesseert op een redelijk vlotte manier beschrijven.
Deltion College Engels B1 Lezen [Edu/002] thema: But I ‘ve read it in… can-do : kan hoofdthema en belangrijkste argumenten begrijpen van eenvoudige teksten.
Deltion College Engels B2 Gesprekken voeren [Edu/007] thema: ‘With this mobile you can…’ can-do : kan op betrouwbare wijze gedetailleerde informatie doorgeven.
Mavo 4.  Goal(s)  Letter Puzzle  Write a letter  Check the letters  Do assignments 4A, 5A, 6A & 7 in Student Book page 50  Evaluation.
Skin by Roald Dahl What do you think this text will be about?
The Research Process: the first steps to start your reseach project. Graduation Preparation
Today: Chapter 2 Discuss SO 2 What to study for your test?
[Description – 160 Characters] [Location]  [Website]
Reading for Understanding Analysis and Evaluation (National 5)
The student will be able to:
Benevolence ENGLISH 12 – Quarter 1.
Member functions.
Transcript van de presentatie:

Programming for Linguists An Introduction to Python 29/11/2012

Today Exercises Conversion Functions Math Module String Methods For Loop In Operator Functions Keyboard Input

Ex. 1 Verzin een zin van minimum 5 woorden. Stop elk woord in een aparte variabele en print de zin op één regel d.m.v. een print statement.

word1 = “to” word2 = “be” word3 = “or” word4 = “not” print word1, word2, word3, word4, word1, word2

Ex. 2 Typ in interactieve modus “Mark + 4”. Waarom krijg je een foutmelding? Pas de code aan zodat je als resultaat van “Mark + 4” het cijfer 10.0 krijgt.

Mark = 6 print float(Mark + 4)

Ex. 3 Maak een nieuwe variabele aan met als value een integer getal. Schrijf een stukje code dat de computer laat checken of dit getal deelbaar is door twee. Zo ja, laat Python “(het getal) is een even getal” printen en in het andere geval “(het getal) is een oneven getal”.

nr = 10 quotient = nr/2 product = quotient*2 if product == nr: print nr,"is een even getal" else: print nr,"is een oneven getal"

OR with a simple google search “python + even number”: x = 10 if x % 2 == 0: print x,"is een even getal" else: print x,"is een oneven getal"

Ex. 4 In een lift kan maximum 150 kg. Maak 4 variabelen aan met een bepaald gewicht. Bereken het totale gewicht en als dit de maximum overschrijdt, print “De lift is te zwaar geladen.”. Als het gewicht precies 150 kg bedraagt, print “De lift heeft zijn maximum gewicht bereikt.”. Als het gewicht minder is dan 150 kg, print “De lift kan nog iemand meenemen.”

w1 = 35 w2 = 56 w3 = 84 w4 = 5 totaal = w1+w2+w3+w4 if totaal > 150: print "De lift is te zwaar geladen." elif totaal < 150: print "De lift kan nog iemand meenemen.” else: print "De lift heeft zijn maximum gewicht bereikt.”

Ex. 5 Maak 3 variabelen aan met als value een cijfer kleiner of gelijk aan 10. Schrijf een stukje code dat het gemiddelde berekent van die cijfers. Als dit cijfer niet kleiner is dan 5, print “Geslaagd.” Als het wel kleiner is, print “Niet geslaagd.”. Als het gelijk aan of groter is dan 7, print “Geslaagd met onderscheiding.” Als het gelijk aan of groter is dan 8, print “Geslaagd met grote onderscheiding.”.

from __future__ import division c1=6 c2=4 c3=12 gem = (c1+c2+c3)/3 if gem >= 8: print "Geslaagd met grote onderscheiding." elif 8 > gem >= 7 : print "Geslaagd met onderscheiding." elif 7 > gem >= 5: print "Geslaagd." else: print "Niet geslaagd."

Ex. 6 Met de functie len( ) kan je in Python de lengte van een argument weergeven. Om de lengte van bv. het woord “Nederlands” te bepalen, gebruik je de functie als volgt: len(“Nederlands”). Probeer deze functie eens uit op de zin “There’s no place like home” en probeer het resultaat te verklaren.

Ex. 7 Maak een nieuwe variabele aan met als value een naam. Laat Python met de len( ) functie uit de vorige oefening “ ‘(naam)’ heeft (aantal) letters.”.

naam = “Claudia” print “’”+naam+”’”, “heeft”, len(naam), “letters.”

Some General Remarks Always save your code in a script via the script mode in a new window after you tried it in interactive mode Please put all exercises in one script Do not give up  Google it!

Conversion Functions Python has a number of built-in functions To convert an argument into respectively an integer, a string and a floating-point number: int(20) str(20) float(20)

Python’s Math Module Module = a file that contains a collection of related functions If you want to use it, you have to import it first  import math  from __future__ import division Every import command is usually given at the beginning of a script

If you want to access one of the functions you have to use dot notation: e.g. use the square root function from the math module: import math math.sqrt(64) math.exp(8) math.pow(8, 2) # 8 raised to power 2 or import each function from the module: from math import sqrt, exp, pow sqrt(64)

Combinations are also possible  the argument of a function can also be a function e.g. math.sqrt(int(64.3)) note: the inside function is executed first See rary/math.html for a full overview of all math functions in Python rary/math.html

A string is a sequence of characters You can access the characters one at a time with the index in between square brackets  index always starts with zero! fruit = “bananas” first_letter = fruit[0] second_letter = fruit[1] last_letter = fruit[-1] Working with Strings

A segment of a string is called a slice Selecting a slice is similar to selecting a character e.g. s = “Monty Python” print s[0:5] print s[6:12] String Slices

The operator [n:m] returns the part of the string from the character with index n up to (but excludes) the character with index m Also possible: [:n]  from the beginning of the string up to the character with index n [n:]  from the character with index n till the end of the string

What is the result of the following? fruit = “bananas” fruit[3:3] fruit[:] fruit[1:] With which command can you replace fruit[1:2]

strings are immutable: you can’t change an existing string you can create a new string that is a variation on the original Starting from “Hello, world!”, make a new variable with the value “Jello, world!” using the bracket operator

Some String Methods in Python a = “this is a sentence.” a.capitalize( )  “This is a sentence.” a.lower( )  “this is a sentence.” a.upper( )  “THIS IS A SENTENCE.” a.title( )  “This Is A Sentence.” a.center(25)  “ this is a sentence. ” a.ljust(25)  “this is a sentence. ” a.rjust(25)  “ this is a sentence.”

a = “this is a sentence.” a.count(“this”)  1 a.startswith(“.”)  False a.endswith(“.”)  True a.replace(“a”, “no”)  “this is no sentence.” a.find(“i”)  2 (lowest index) a.index('i')  2 (lowest index) a.rfind('i')  5 (highest index) a.rindex('i')  5 (highest index)

greet = “Hello, world!” new_greet = “j” + greet[1:] print new_greet print new_greet.capitalize( ) This example concatenates a new first letter onto a slice of greet Which output would a new “print greet” give?

Relational operators work on strings ==, e.g. word1 == word2  is equal to word1 < word2  comes before (alphabetically) word1 > word2  comes after (alphabetically) String Comparison

In Python all the uppercase letters come before all the lowercase letters Tip: convert strings to a standard format, e.g. with the function.lower( ), before performing the comparison

a boolean operator that takes two elements and returns True if the first appears as a component of the second “a” in “banana” True “Python” in “Hello, hello” False The In Operator

When you need to process one character at a time: start at the beginning select each character in turn and do something with it continue to the end of the string This pattern of processing = traversal Traversal with a For Loop

fruit = “pear” for letter in fruit: print letter for elem in fruit: print elem for f in fruit: print f print f

Each time through the loop, the next character in the string is assigned to the variable after the for loop:  letter, elem, f The loop continues until no characters are left If you want to do something with each element in the body of the for loop, you have to use the same variable name as in the for loop Outside the for loop, the variable only has the last item as a value

word = “abracadabra” count = 0 for letter in word: if letter == “a”: count = count + 1 print count Looping and Counting

You have to initialize a variable (e.g. “count”) first and set it to 0 The for loop checks every character of the string and adds 1 to “count” if the character is an “a” When the for loop ends, the variable “count” contains the result

Some predefined functions: math.sqrt(64) a.upper(“hello”) len(“hello”) int( ) str( ) float( ) Functions

Creating New Functions You always have to define a new function: def name( ): #enter e.g. def print_address( ): print “Lange Winkelstraat 40” print “2000 Antwerpen” In the rest of the program you can call this function by typing print_address( )

Function = a named series of statements that performs a computation named: you define a function sequence of statements: e.g. assign (print) statements that are to be executed in the order predetermined by you

Rules for names = variables: first character cannot be a number you cannot use a Python keyword as a name case sensitive Some tips: try to choose a name that relates to what the function is doing avoid choosing the same name for a variable and a function

To end a function: in interactive mode  enter empty line in script mode  new line/empty line(s) Note: functions can take no, one or more argument(s) type(37) print_address( )

More arguments: >>>def print_word(token, number): print token*number >>>word = “Nevermore” >>>print_word(word, 3) Note: the names of the arguments are only temporary substitutes for other variables in the program: parameters

Composition Functions you created yourself can also be combined: def repeat_words( ): print_word(word, 3 ) print_word(word, 4 ) repeat_words ( )

Try it yourself: assign the word “python” to a variable, define a function that calculates and prints the word length of “python”, 1) using no argument 2) using the variable as an argument

1) word = “python” def word_length( ): print len(word) word_length( )

2) def word_length(word): print len(word) word_length(“hello”) text = “hi” word_length(text)

What would happen if you try to print the variable word outside the function if it is inside the function only? def word_length( ): word = “python” print len(word) print word

When you create a variable inside a function, it is local, i.e. it only exists inside the function !

Flow of Execution The order in which statements are executed Begins at the top of the program One at a time From top to bottom Functions do not change the order, but statements inside a function are only executed after the function is called

Functions are like a detour: statements are executed in order a function is called the program jumps to the body of the function and executes all statements inside the body (and does the same for functions within the function) the program continues with the statements under the function call

Arguments and Parameters def print_twice(franky): print franky the function assigns the argument to a parameter named franky whenever the function is called it will print the value of the parameter you pass into the function twice

Try: print_twice(‘spam’) print_twice(101) print_twice(123.45) What would happen if you try: print_twice(‘spam ’*5) print_twice(franky)

Why Use Functions? Less work for you: if you write a function once, you can use it again as much as you want during the program You can group a piece of your code, so that it is easy to read and debug If there is a bug, you only need to correct it once

Why Use Functions? (2) If you save them, you can import them in other scripts You can use the return values of fruitful functions in the rest of your program

Ex. Define a function that will count the letters of a word and prints the word + “has less than 5 letters” or “has more than 5 letters” or “no word given” if you put in an empty string “”.

Possible answer: def word_length(word): if len(word) < 5 and len(word) != 0: print word + “ has less than 5 letters” elif len(word) == 0: print "no word given” else: print word + " has more than 5 letters” word_length(“abracadabra”)

Keyboard Input In Python: raw_input( ) uses input from the keyboard When this function is called, the program stops and waits for the user to type something raw_input( ) always gives you a string input( ) assumes Python code

e.g. question = “What is your name? \n” print question name = raw_input(question) print “Welcome ” + name

For Next Week Tuesday Exercises on blackboard Deadline: 5/12

Thank you