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

Slides:



Advertisements
Similar presentations
Self Check 1.Which are the most commonly used number types in Java? 2.Suppose x is a double. When does the cast (long) x yield a different result from.
Advertisements

CS 100: Roadmap to Computing Fall 2014 Lecture 0.
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.
I210 review Fall 2011, IUB. Python is High-level programming –High-level versus machine language Interpreted Language –Interpreted versus compiled 2.
CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
Variables Pepper. Variable A variable –box –holds a certain type of value –value inside the box can change Example –A = 2B+1 –Slope = change in y / change.
Python November 14, Unit 7. Python Hello world, in class.
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.
Introduction to Python
Fundamentals of Python: From First Programs Through Data Structures
Lilian Blot CORE ELEMENTS COLLECTIONS & REPETITION Lecture 4 Autumn 2014 TPOP 1.
Guide to Programming with Python Chapter Two Basic data types, Variables, and Simple I/O: The Useless Trivia Program.
Python.
Programming for Linguists An Introduction to Python.
Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language.
An Introduction to Textual Programming
Programming for Linguists An Introduction to Python.
Introduction to Python
Programming for Linguists An Introduction to Python 24/11/2011.
FUNCTIONS. Function call: >>> type(32) The name of the function is type. The expression in parentheses is called the argument of the function. Built-in.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Python Lesson Week 01. What we will accomplish today Install Python on your computer Using IDLE interactively to explore String Variables if/else while.
Python – Part 3 Functions 1. Function Calls Function – A named sequence of statements that performs a computation – Name – Sequence of statements “call”
Python Programming Chapter 7: Strings Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.
Input, Output, and Processing
Strings The Basics. Strings can refer to a string variable as one variable or as many different components (characters) string values are delimited by.
Variables and Expressions CMSC 201 Chang (rev )
Functions Chapter 4 Python for Informatics: Exploring Information
How to Read Code Benfeard Williams 6/11/2015 Susie’s lecture notes are in the presenter’s notes, below the slides Disclaimer: Susie may have made errors.
12/9/2010 Course A201: Introduction to Programming.
Python – Part 3 Functions 1. Getting help Start the Python interpreter and type help() to start the online help utility. Or you can type help(print) to.
Introduction to Python Dr. José M. Reyes Álamo. 2 Three Rules of Programming Rule 1: Think before you program Rule 2: A program is a human-readable set.
CSC 1010 Programming for All Lecture 3 Useful Python Elements for Designing Programs Some material based on material from Marty Stepp, Instructor, University.
By Austin Laudenslager AN INTRODUCTION TO PYTHON.
Variables and Expressions CMSC 201. Today we start Python! Two ways to use python: You can write a program, as a series of instructions in a file, and.
Last Week Modules Save functions to a file, e.g., filename.py The file filename.py is a module We can use the functions in filename.py by importing it.
Python Let’s get started!.
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.
COMPE 111 Introduction to Computer Engineering Programming in Python Atılım University
Variables, Types, Expressions Intro2CS – week 1b 1.
Trinity College Dublin, The University of Dublin GE3M25: Computer Programming for Biologists Python, Class 2 Karsten Hokamp, PhD Genetics TCD, 17/11/2015.
CS190/295 Programming in Python for Life Sciences: Lecture 6 Instructor: Xiaohui Xie University of California, Irvine.
Functions Chapter 4 Python for Informatics: Exploring Information Slightly modified by Recep Kaya Göktaş on March 2015.
Python Strings. String  A String is a sequence of characters  Access characters one at a time with a bracket operator and an offset index >>> fruit.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
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.
PYTHON PROGRAMMING. WHAT IS PYTHON?  Python is a high-level language.  Interpreted  Object oriented (use of classes and objects)  Standard library.
ENGINEERING 1D04 Tutorial 2. What we’re doing today More on Strings String input Strings as lists String indexing Slice Concatenation and Repetition len()
Python Basics.
String and Lists Dr. José M. Reyes Álamo.
Fundamentals of Programming I Overview of Programming
Introduction to Python
Topics Introduction to Repetition Structures
ECS10 10/10
Presented By S.Yamuna AP/IT
Variables, Expressions, and IO
Lecture 07 More Repetition Richard Gesick.
Engineering Innovation Center
CHAPTER 7 STRINGS.
Selection CIS 40 – Introduction to Programming in Python
Python - Strings.
Data types Numeric types Sequence types float int bool list str
CMSC201 Computer Science I for Majors Lecture 12 – Tuples
T. Jumana Abu Shmais – AOU - Riyadh
CEV208 Computer Programming
String and Lists Dr. José M. Reyes Álamo.
Language Constructs Construct means to build or put together. Language constructs refers to those parts which make up a high level programming language.
Introduction to Computer Science
General Computer Science for Engineers CISC 106 Lecture 03
Presentation transcript:

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

From Last Week… Write a script called yourname_ex1.py that calculates the average weight of 5 variables: 36.5 kg 47.8 kg 33 kg 68.3 kg 72 kg

w1 = 36.5 w2 = 47.8 w3 = 33 w4 = 68.3 w5 = 72 average_w = (w1 + w2 + w3 + w4 + w5)/5 print “The average weight of”, w1, “,”, w2, “,”, w3, “,”, w4, “and”, w5 “kg is:”, average_w, “kg.”

Write a script called yourname_ex2.py that assigns an integer value to a variable “age” and prints “you are a minor” if the value is under 18, that prints “you are over 18” if the value is 18 or more and prints “you are kidding” if the value is less than 0.

age = 0 if age>=0 and age<18 : print "you are a minor” elif age>=18 : print "you are over 18” else: print "you are kidding"

Nested Conditionals One or more conditionals are nested within another if age >= 0: if age <18: print “you are a minor” else: print “you are over 18” else: print “you are kidding”

Nested conditionals are more difficult to read They can often be simplified by logical operators

if age>=0: if age =0 and age<18: print “you are a minor” if 0 <= age < 18: print “you are a minor”

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)

Try this: convert into an integer convert into a string convert 37 into a floating-point number make the division of 10/3 a floating-point division using a type conversion function

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)

See rary/math.html for a full overview of all math functions in Python rary/math.html

Composition So far: variables, statements, expressions in isolation 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

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)

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

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

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 statement: letter, elem, f The loop continues until no characters are left If you do something with each element in 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

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] And fruit[:] ?

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

greet = “Hello, world!” new_greet = “J” + greet[1:] print new_greet This example concatenates a new first letter onto a slice of greet It has no effect on the original string

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

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, count contains the result

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 upper-case letters come before all the lowercase letters Tip: convert strings to a standard format, e.g. with the function.lower( ), before performing the comparison

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

Function = a named series of statements that performs a computation named: you define a function  again give it a name that describes what the function is doing sequence of statements: e.g. assign statements and/or print statements that are to be executed in the order predetermined by you

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

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)

Fruitful Functions vs. Void Functions Fruitful functions: return a value e.g. >>>result = len(“python”) >>>type(result) Void functions: do not return a value e.g. >>>result = print_twice(“python”) >>>type(result)

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

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

For Next Week Tuesday 1) Define a function that asks the user’s name and gives an answer: What is your first name? >>>Claudia Claudia contains 7 letters and ends with an a.

2) Play with some string methods. Write a function that will print a sentence of your choice: in capitals in lower case like a title Find the lowest and the highest index of a letter in your sentence. If the index of the letter is higher than 3, replace the letter with an other letter.

3) Write a script that implements the Dutch grammar rule of 't kofschip. If you do not know this rule, please check Wikipedia! The program should start with asking the user to type in a verb root such as "werk"(work) or "speel" (play). The program checks the last letter of the lemma and returns the past tense of the lemma by adding ‘+te’ or ‘+de’. werk -> werkte speel -> speelde gil -> gildelach ->lachte (Note: the program only handles regular cases. Do not worry about implementing the irregular forms such as 'leven' ('lev' -> 'leefde’))

Please mail them to by next Tuesday: Thank you