Ling 555 —Programming for Linguists

Robert Albert Felty

Outline

Algorithms

What is an algorithm? An algorithm is a set of instructions or a recipe for a computer to carry out.

Numbers

By default, 1 / 2 yields 0 in python. This is integer division.
Solution: from __future__ import division

Variables

What is a variable? A variable is a name that refers to some value (could be a number, a string, a list etc.)

  1. Store the value 42 in a variable named foo
    foo = 42

  2. Store the value of foo+10 in a variable named bar
    bar = foo + 10

Statements

What is the difference between an expression and a statement? An expression is something, and a statement does something.

User input

  1. Ask the user to input a number, and store it as the variable foo
    foo = input("enter a number: ")

  2. What is the value of foo now?

  3. Add foo and bar together
    foo + bar

  4. Calculate the average of foo and bar, and save it as a variable named avg
    avg = (foo + bar)/2

Functions

What is a function? A function is a mini-program. It can take several arguments, and returns a value.

Modules

What is a module? Python is easily extensible. Users can easily write programs that extend the basic functionality, and these programs can be used by other programs, by loading them as a module

  1. load the math module
    import math

  2. Round 35.4 to the nearest integer
    math.round(35.4)

  3. Round the quotient of foo and bar down to the nearest integer
    math.floor(foo/bar)

Saving and executing scripts

Script File: hello.py
[language=python] #!/usr/bin/env python # this script prints ’hello, world’, to stdout print "hello, world" Add executable permission:
chmod a+x hello.py
Run the program:
./hello.py

String Basics