1 / 61

Programming for Linguists

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.

santo
Download Presentation

Programming for Linguists

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Programming for Linguists An Introduction to Python29/11/2012

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

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

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

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

  6. Mark = 6 print float(Mark + 4)

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

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

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

  10. 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.”

  11. 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.”

  12. 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.”.

  13. from __future__ import divisionc1=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." elif7 > gem >= 5: print "Geslaagd." else: print "Niet geslaagd."

  14. 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 placelike home” en probeer het resultaat te verklaren.

  15. 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.”.

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

  17. 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!

  18. 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)

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

  20. 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 mathmath.sqrt(64) math.exp(8)math.pow(8, 2) # 8 raised to power 2 • or import each function from the module:from math importsqrt, exp, powsqrt(64)

  21. 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 • Seehttp://docs.python.org/release/2.6.2/library/math.htmlfor a full overview of all math functions in Python

  22. Working with Strings • A string is a sequence of characters • Youcanaccess the charactersone at a time with the indexin between square brackets index always starts with zero!fruit = “bananas”first_letter = fruit[0]second_letter = fruit[1]last_letter = fruit[-1]

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

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

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

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

  27. 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.”

  28. 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)

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

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

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

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

  33. Traversal with a For Loop • 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

  34. fruit = “pear” forletter in fruit: print letter forelemin fruit: print elem forfin fruit: print f print f

  35. Each time through the loop, the next character in the string is assignedto the variableafter the for loop:  letter, elem, f • The loop continuesuntil no characters are left • Ifyouwant to do somethingwitheach element in the body of the for loop, you have touse the samevariable name as in the for loop • Outside the for loop, the variableonly has the last item as a value

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

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

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

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

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

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

  42. 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( )

  43. More arguments: >>>defprint_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

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

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

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

  47. 2) defword_length(word): print len(word) word_length(“hello”) text = “hi” word_length(text)

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

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

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

More Related