Introduction to Pythonpythonintro.pdf

download Introduction to Pythonpythonintro.pdf

of 17

Transcript of Introduction to Pythonpythonintro.pdf

  • 7/27/2019 Introduction to Pythonpythonintro.pdf

    1/17

    CS 16Introduction to Python

    Intro to Algorithms and Data Structures

    Introduction to Python

    1 What is Python?

    A snake! A snake! A scaaary snake? Yes, but Python is also a programming language thatyoull be learning this semester! Python bears some resemblance to Java, but in generalit is cleaner and easier to read. There are a few important differences from Java that youshould note:

    First, you dont need to declare the types of variables. Thus, you write x = 1 ratherthan i n t x = 1. Variables do have types, but you dont need to announce the type whenyou first use a variable. In fact, you can write x = 1 and then x = abcd in the sameprogram; after the first assignment, x is an integer; after the second, its a string. (N.B. Ingeneral this is a very bad idea, so avoid it!)

    Second, the environment in which you work with Python lets you type bits of code andsee what happens without an intermediate compiling step. This makes experimentationand testing very simple.

    Third, a feature of Python that you will grow to love and cherish is how easy it is toread. Instead of using a lot of punctuation and other symbols, which are what makes codein most programming languages look daunting and scary, Python uses English keywordsand natural-sounding syntax. For example, this is a declaration and an if-condition inPython:

    x = 1

    i f x > 0 :

    print "x is positive"

    print "What beautiful syntax!"

    print "Do you love Python yet?"

    Youll notice that instead of using curly braces to delimit code blocks, Python uses whites-pace indentation. That means that correctly nesting your code now has semantic meaning,instead of just making it easier for you (and your TAs) to read. Well learn more aboutsyntax later, so for now, just marvel at its beauty.

    Python is similar to Java in that it also handles your memory management, meaning itallocates memory and has a garbage collector to free up that memory once it is no longerneeded, making your life a whole lot easier. If youre not already convinced that Pythonrules...

    2 Why should you learn Python?

    Well be using Python throughout the semester to code up some of the algorithms youll belearning. As a computer scientist you should get used to learning new languages readily,not only because its an important part of the subject, but also because its useful (and

    Introduction to Python January 29, 2013 1

  • 7/27/2019 Introduction to Pythonpythonintro.pdf

    2/17

    CS 16Introduction to Python

    Intro to Algorithms and Data Structures

    fun!). Python is especially important to learn because it is used very widely as a scriptinglanguage Pixar uses it for all their tools, for instance so knowing it could one day helpyou get a job making a movie like Toy Story 3.

    3 Day 1

    Your journey through python begins today...

    4 Writing your first program in Python

    Its tradition when learning a new programming language that your first program is a HelloWorld program, so lets start out by writing a simple one-line program that prints Hello

    world!To start, open a terminal and run cs016_install pythonIntro. This will create a di-

    rectory located at ~/course/cs016/pythonIntro and copy over a few files which well uselater in the tutorial. Go ahead and cd into the tutorial directory: cd ~/course/cs016/pythonIntro.

    Open the text editor Kate, by typing kate & in your terminal. Just like you used Kateto write .java files in CS15, well be using Kate to write .py files in CS16. Before you doanything else, we need to configure Kate to work best with Python:

    1. Click the Settings menu item in Kate and go to Configure Kate....

    2. In the Configure dialog, youll see theres a category for Editing in the outlineview on the left. Open the indentation options.

    3. Select Python as the Default indentation mode.

    4. Specify 4 characters for indentation.

    Its important you configure Kate as specified above because Python uses whitespaceindentation to delimit your code (more on this later). For the sake of convenience, we insistthat you use 4 spaces to indent your code. It will make your code look consistent acrossmachines and prevent inconsistencies between spaces and hard tabs.

    Now that Kate has been configured, lets actually write some Python code! Type

    print Hello world!

    and save your file as helloWorld.py. The .py is very important, so dont forget it! Savethe file in your ~/course/cs016/pythonIntro directory. Now go back to your terminal,make sure you are in the pythonIntro directory and type python helloWorld.py to runthe program. It will print Hello world! to your terminal.

    Hold on, do you really have to type python yourProgramName.py every time you wantto run a program? (Or for the especially lazy, scroll through your commands until you findthe last time you typed it?) Heck no! Go back to Kate and type

    Introduction to Python January 29, 2013 2

  • 7/27/2019 Introduction to Pythonpythonintro.pdf

    3/17

    CS 16Introduction to Python

    Intro to Algorithms and Data Structures

    #! /usr/bin/python

    at the top of your helloWorld.py file. This tells your machine to use Python to interpretthe file when executed. Then save the file, go back to your terminal, and type chmod +xhelloWorld.py to make the file an executable. Now if you type ./helloWorld.py intoyour terminal your program prints Hello world! to the terminal. From now on, all ofyour Python files should start with #!/usr/bin/python.

    5 Python Syntax

    Lets say that instead of wanting to write a program that just prints Hello world! andthen ends, you wanted to write a program with a function that takes in a string with yourname as the parameter, and prints Hello ! Following the CS16 Python coding

    conventions, the function would look like this:

    def say_hello(name):

    """say_hello: string -> .

    Consumes: a string, name

    Produces: nothing

    Purpose: prints a greeting of the form "Hello !"

    """

    print "Hello " + name + "!"

    When you define a function in Python, you simply write def (which stands for define),followed by the name of the function, with all words lowercase and separated by underscores,

    then the parameters in parentheses, and lastly a colon. Next, document your function witha docstring in triple quotes. For an in-line comment, use #, instead of the // from Java.Thedocstring should include a description of the parameters and return type, the purpose ofthe method, what the method consumes (the parameters), and what it produces/returns.There is a detailed handout on coding conventions on the course website that you can readlater, but its good to get used to them now.

    The actual body of this function is simple. First off, it is indented four spaces from thefunction declaration. This is crucial. If you do not indent your code correctly, it will notwork. Whitespace indentation is used in Python to nest blocks of code, rather than curlybraces. Each subordinating code block must be indented four spaces relative to the codeon which it depends. As you get used to programming in Python, this will become second

    nature. The code here prints the concatenated string of Hello + str + ! tothe shell. Note that the print() function doesnt require that you enclose the string inparentheses since it is a special built-in function in Python, but most functions do requireparentheses.

    To test out this function, type it into Kate, and put this code at the end:

    if __name__ == "__main__":

    say_hello("Stephen") #substitute your name

    Introduction to Python January 29, 2013 3

  • 7/27/2019 Introduction to Pythonpythonintro.pdf

    4/17

    CS 16Introduction to Python

    Intro to Algorithms and Data Structures

    Its very important this code comes after the function definition, because functions mustbe defined before they can be called. (Note that this is different than Java).

    This bit of code will allow you to run it as a standalone program. The main line here issimilar to Javas public static void main(String args[]). It contains the code thatwill run when you execute the program. Save your file (make sure it ends in .py!) and thenrun it using one of the two techniques we discussed earlier. The terminal will now greetyou as if your name is Stephen.

    Substitute your name into the parameters and watch your terminal try to befriend you.Unfortunately if you try to say hi back, you will see this:

    gemini ~/course/cs016 $ python sayHi.py

    Hello Stephen!

    gemini ~/course/cs016 $ Hello Terminal!

    bash: Hello: command not found

    So much for that ;(Lets look at something a little more complicated. Say you had written out some

    pseudocode for a function that prints out the numbers 1 to n for n 1. It might looksomething like this:

    Algorithm printOneToN(n):

    This algorithm prints out the numbers from 1 to n for n 1.If n is less than 1, it prints an error message to alert the user.

    Input: an integer n

    Output: none

    if n < 1 then

    print "Invalid input: integer value cannot be less than 1"

    return

    for i 1 t o n d oprint i

    In Python, following the CS16 Python coding conventions, it would look like this:

    def print_one_to_n(n):

    """print_one_to_n: int -> .

    Consumes: an integer, n

    Produces: nothingPurpose: this function prints out the numbers from 1 to n for n >= 1.

    If n is less than 1, it prints an error message to alert the user.

    """

    i f n < 1 :

    print "Invalid input: integer value cannot be less than 1"

    return

    Introduction to Python January 29, 2013 4

  • 7/27/2019 Introduction to Pythonpythonintro.pdf

    5/17

    CS 16Introduction to Python

    Intro to Algorithms and Data Structures

    for i in range(1, n + 1):

    print i

    Youll notice that there arent many differences between the pseudocode and Python. Thatis because Python is wonderful! Lets go over some of the new Python syntax.

    An if-condition starts with if followed by the condition and a colon, no parenthesesneeded. Even though there are multiple lines of code in the if-block, there are no curlybraces because everything is indented four spaces. So fresh and so clean. We could alsowrite the if-statement as the equivalent statement:

    if not n > 0:

    Python favors English keywords in the place of punctuation, so you will see not used inPython in place of ! in Java, and instead of &&, and or for ||.

    The function also has a for-loop to print the numbers from 1 to n. So why does itsay range(1, n + 1)? The built-in function range() generates arithmetic progressionsbased on the optional start parameter, and required stop parameter that you feed it. Letsunderstand this a bit better by just running python from your terminal. Python providesits own shell, where you can now run python commands to try things things out.

    Type range(10). Your required stop parameter is 10 and the start parameter defaultsto 0, so the integers from 0 to 9 print out, since it stops before 10. Now type range(1,10). Since you specified the start of the progression, it prints the numbers from 1 to 9. So ifwe want the function to print out the sequence, including n, we have to write range(1, n+ 1). When youre finished trying things out in the interactive shell, type exit() to quit,or use ctrl+D.

    There is a lot more to Python syntax, but these are some basics to get you started.Here is a super nifty Java to Python conversion table, which will be a boon to you in thecoming weeks:

    Introduction to Python January 29, 2013 5

  • 7/27/2019 Introduction to Pythonpythonintro.pdf

    6/17

    CS 16Introduction to Python

    Intro to Algorithms and Data Structures

    6 Your first Python problem

    Now it is time to write a short Python program that prints out the first 100 Fibonaccinumbers. Remember, each number in the Fibonacci series is the sum of the two numbersbefore it, and the first and second numbers of the series are both one.

    Once you complete this assignment, create a second method which recursively calculatesand returns n! where n is the input value.

    Introduction to Python January 29, 2013 6

  • 7/27/2019 Introduction to Pythonpythonintro.pdf

    7/17

    CS 16Introduction to Python

    Intro to Algorithms and Data Structures

    Methods

    You need to implement the following methods in the sectionOne.py file that was installedearlier.

    fibonacci: This method takes no arguments and returns nothing. It prints out thefirst one hundred Fibonacci numbers, with one number per line.

    factorial: This method takes a non-negative integer n as an argument and it returnsthe n!. This method should be implemented in a recursive fashion. Remember that0! is 1!

    7 Another Python problem

    You will write a short python program that prints out whether todays date (the day ofmonth) is a prime number or not. It should print out one line which states the day of themonth and whether it is prime. For example:

    It is day 23 of the month, which is prime.

    or

    It is day 25 of the month, which is not prime.

    Methods

    You need to implement the following methods in the primePrinter.py file that was in-stalled earlier.

    is_prime: This method must take one non-negative integer argument and return aboolean stating whether that number is a prime or not. (This method should workfor all non-negative integers, not just those between 1 and 31.) To test whether anumber is prime, simply check whether it has any divisors. Hint: Remember the modoperator (%) from Java? It works the same in Python.

    get_today: This method takes no arguments and it returns an integer in the range1-31 representing the day of the month. This should not be a hard-coded value (if youinvoke the same method tomorrow, it should return tomorrows day-of-the-month!).

    Hints

    Youll notice at the top of the file theres a line that reads:

    from datetime import date.

    This imports the datetime module, which has already been written by someone else.Modules in Python are similar to libraries you used in Java (e.g. javax.Swing). But it

    Introduction to Python January 29, 2013 7

  • 7/27/2019 Introduction to Pythonpythonintro.pdf

    8/17

    CS 16Introduction to Python

    Intro to Algorithms and Data Structures

    doesnt import the entire module, just the date component, which you can read aboutmore here: http://docs.python.org/library/datetime.html#date-objects . Us-ing the date object should help you implement get_today.

    If you want to print out an integer value concatenated with a string, you can usethe built-in Python function str(). str(myInt) will convert the integer value to astring.

    Testing

    Testing is important. Well be requiring you to write and submit tests for the Python assign-ments you write in the future. For this problem, write a method testPrimePrinterMethods()to ensure both methods work as expected:

    Print the result of the get_today method. If your code returns todays date, youveprobably implemented it correctly.

    Test your is_prime at least on all the days of any month. Suggestion: write a forloop to loop through all of those numbers and print out whether they are prime.

    Add a call to testPrimePrinterMethods() to your __"main"__ body to actually run thetests when you run your program. When youre convinced they work, you can commentout or remove this function call from the main body, so that your program can be used tomeet its original objective.

    8 Handing InYoure done with day one of the python intro! Feel proud, for you are now a snake-charmer...kind of. Hand in primePrinter.py and sectionOne.py by running cs016 handinpythonIntro. Be sure your code is well-tested and commented!

    9 Day 2

    While you may have charmed many a snake already, future perils await on Day 2 of thePython Intro!

    10 Python lists

    Python lists will be used frequently in CS16. Lists are Pythons version of Java arrays. Youcan create them as follows (try them out in the interactive interpreter using the pythoncommand):

    >>>myList = [10, 2, 15, 30]

    Introduction to Python January 29, 2013 8

    http://docs.python.org/library/datetime.html#date-objectshttp://docs.python.org/library/datetime.html#date-objects
  • 7/27/2019 Introduction to Pythonpythonintro.pdf

    9/17

    CS 16Introduction to Python

    Intro to Algorithms and Data Structures

    And index into them in much the same way as in Java:

    >>>myVal = myList[2] #myVal will now = 15

    Unlike Java arrays, Python lists also have methods you can call, which you can read aboutin the documentation. Heres an example that builds a list of the first ten perfect squares:

    >>>perfectSquares = []

    >>>for i in range(1, 11):

    ... perfectSquares.append(i*i)

    #append adds the specified parameter to the end of the list

    If you need to instantiate a list of a certain length (i.e. you want to use it as an array), the

    following syntax will be very helpful:

    >>>pythonArray = [0]*5

    >>>pythonArray

    [0, 0, 0, 0, 0]

    But what if I need a multi-dimensional list/array? you ask. Great question! Pythonhandles this data structure as a list of lists:

    >>>grid = [[1,2,3], [4,5,6], [7,8,9]]

    >>>grid

    [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

    >>>grid[0][1]2

    >>>grid[2]

    [7,8,9]

    >>> [x[1] for x in grid]

    [2, 5, 8]

    #notice that x represents a sub-list in the grid list

    This may seem strange at first, but as long as you remember lists within lists, youll befine. You can read about addition Python data structures, (like dictionaries!) at:http://docs.python.org/tutorial/datastructures.html

    10.1 List comprehensions

    Python supports a concept called list comprehensions which can help you create listsvery easily. Here are a few examples:

    Introduction to Python January 29, 2013 9

    http://docs.python.org/tutorial/datastructures.htmlhttp://docs.python.org/tutorial/datastructures.html
  • 7/27/2019 Introduction to Pythonpythonintro.pdf

    10/17

    CS 16Introduction to Python

    Intro to Algorithms and Data Structures

    >>> vec = [2, 4, 6]

    >>> [3*x for x in vec]

    [6, 12, 18]

    >>> [3*x for x in vec if x > 3]

    [12, 18]

    >>> [3*x for x in vec if x < 2]

    []

    >>> [[x,x**2] for x in vec] #x**2 in Python is x*x

    [[2, 4], [4, 16], [6, 36]]

    11 Object-oriented programming in Python

    Python supports object-oriented programming as you learned in CS15 with Java. To doso, you declare a class with properties (instance variables) and capabilities (methods) asfollows:

    class Student:

    """The student class models a student with a name, ID number,

    a graduation year, and a concentration.

    """

    def __init__(self, name, idNumber, concentration, graduationYear):

    self._name = name

    self._idNumber = idNumber

    self._graduationYear = graduationYearself._concentration = concentration

    def setConcentration(self, concentration):

    self._concentration = concentration

    # Other accessors/mutators...

    def printStudentInfo(self):

    print "Student named " + self._name + " has ID number " + \

    str(self._idNumber) + ", is graduating in " + \

    str(self._graduationYear) + " and is studying " + \self._concentration + "."

    To actually create an instance of this class, and call methods on it, we do the following:

    if __name__ == __main__ :

    stephen = Student("Stephen", 1002354, "Mathematics", 2013)

    stephen.setConcentration("Computer Science")

    Introduction to Python January 29, 2013 10

  • 7/27/2019 Introduction to Pythonpythonintro.pdf

    11/17

    CS 16Introduction to Python

    Intro to Algorithms and Data Structures

    stephen.printStudentInfo()

    Create a file called student.py and test this out for yourself. What does this exampleshow us?

    1. The constructor for a class is defined using a special method named __init__, whichcan take any number of parameters. To create an instance of the class, we call theconstructor and pass in the appropriate parameters. Note we do not use a newoperator like we did in Java.

    2. The instance variables belonging to a class do not need to be explicitly defined at thetop of the file like they do in Java. Like local variables, we dont need to specify theirtypes, and they spring into existence when theyre first assigned a value. If we try to

    use a variable that has not yet been given a value, well get an AttributeError thatlooks like this: AttributeError: Student instance has no attribute _idNumber.Try this for yourself by eliminating the assignment, self._idNumber = idNumberfrom the constructor, and re-running the program. When we re-run the program, theprintStudentInfo() method attempts to print out _idNumber, but _idNumber hasnot been created because it has never been given a value. (This is kind of like a Javanull pointer in that initializing your variables is important).

    3. When accessing/mutating the value of an instance variable, we always do so withself._variableName, NOT by using _variableName like we do in Java.

    4. The methods belonging to a class should take in self as their first parameter. When

    you call stephen.printStudentInfo(), it calls the printStudentInfo method ofthe Student class, and passes in stephen as the first parameter. So when you definethe method, it must take in a reference to the object its modifying, and when youcall the method, you dont supply that first parameter. For this reason, methoddefinitions will always have one more formal parameter (in the method definition)than actual parameters (when we invoke the method).

    5. We couldnt fit the entire print statement of printStudentInfo on one line. Wecould have broken up the method into multiple calls to print. Instead we used a \to write a multiline Python statement. Remember Python uses whitespace to delimitcode, not braces and semicolons like Java, so we need a way to tell Python the nextline is still a continuation of the current command.

    Now, try changing the method signature to:

    def __init__(self, name, idNumber, concentration, graduationYear = 2016):

    And the instantiation of Student in main to:

    Introduction to Python January 29, 2013 11

  • 7/27/2019 Introduction to Pythonpythonintro.pdf

    12/17

    CS 16Introduction to Python

    Intro to Algorithms and Data Structures

    stephen = Student("Stephen", 1002354, "Mathematics")

    This tells python to set the default value of graduationYear to 2016 if no parameteris supplied. Often you have a function that uses lots of default values, but you rarely wantto override the defaults. Default argument values provide an easy way to do this, withouthaving to define lots of functions for the rare exceptions. Also, Python does not supportoverloaded methods/functions and default arguments are an easy way of faking the over-loading behavior. (Note: once you use a default parameter, all subsequent parameters musthave default values as well.)

    11.1 Inheritance

    The syntax for subclassing is as follows:

    class SubclassName(SuperclassName):

    The class SuperclassName must have already been defined. Inheritance works approx-imately the same as it does in Java. One major difference is the way to call methods ofyour parent class. Instead of using super.methodName(arguments), just callSuperclassName.methodName(self, arguments).

    11.2 Private variables

    Private instance variables that cannot be accessed except from inside an object dont existin Python. However, there is a convention that is followed by most Python code: a nameprefixed with an underscore (e.g. _myObject) should be treated as private and not usedoutside of the class in which it is contained.

    12 Testing

    12.1 assert

    In future Python assignments, well be expecting you to write thorough test cases to exerciseyour code and ensure it is correct. Testing is a very important part of software engineering.When new features are added to a software package, or when code is refactored to improve

    design/readability, developers need a way to make sure none of the old functionality breaks.Tests will allow you to make sure your functions do precisely what they say they do. Theycan also help in debugging if you know from your tests which functions are working, youwont waste time looking for bugs in the wrong place.

    In CS16, well be using a few different testing techniques. For now, lets take a look atassert.

    Introduction to Python January 29, 2013 12

  • 7/27/2019 Introduction to Pythonpythonintro.pdf

    13/17

    CS 16Introduction to Python

    Intro to Algorithms and Data Structures

    def add(a, b):

    return a + b

    if __name__ == "__main__":

    assert add(2, 3) == 5, "Arithmetic failure"

    assert will check that both sides of the equality are equal. If the evaluation of the first ar-gument does not equal the second argument, an AssertionError exception will be thrown,printing the (optional) message.

    12.2 coverage

    Writing good tests is just as important as writing good code. You want to make sure your

    tests hit all possible execution paths of the function youre testing. One way to do this isto use coverage, a module that will report which lines of code are executed during yourtesting. Heres how to use it:

    if __name__ == "__main__":

    import coverage

    coverage.start()

    import myaddmodule #replace with the name of your .py file

    # add all tests (using asserts) here

    coverage.stop()

    coverage.report(myaddmodule)

    You nest all of your testing code between calls to start() and stop(). coverage willkeep track of which lines of code in myaddmodule (the module youre testing) are executed,and display the results when you call report(). Go ahead and give it a shot!

    13 File I/O

    13.1 Reading a .txt file

    File I/O is very simple in Python, and is one of the tools well expect you to become familiarwith this semester. You can manipulate files from JPEGS to spreadsheets, but well startoff working with a simple text file. Open up the demo.txt file, to see what youll be workingwith. Now, open up python in your terminal, and try out the following commands:

    >>>file = open("demo.txt")

    >>>colors = []

    >>>for line in file:

    ... colors.append(line) #be sure to tab here

    Introduction to Python January 29, 2013 13

  • 7/27/2019 Introduction to Pythonpythonintro.pdf

    14/17

    CS 16Introduction to Python

    Intro to Algorithms and Data Structures

    ...

    >>>file.close()

    >>>print colors

    [red\n, orange\n, yellow\n, green\n, blue\n, indigo\n, violet\n]

    >>>for hue in colors:

    ... print hue.strip()

    ...

    red

    orange

    yellow

    green

    blue

    indigo

    violet

    The \n character is called a newline and represents a carriage return in a file. We usethe strip() method to remove unneeded whitespace from our strings. Always make sureto close the files you open to avoid eating up system resources.

    13.2 Writing to a .txt file

    Try the following code in the Python interactive interpreter:

    >>>file = open(my_file.txt, w) #the w arg allows us to write to the file

    >>>file.write(This is the first line\n)

    >>>for i in range(11):... file.write(str(i) + \n)

    ...

    >>>file.close()

    Verify that this code created a file named my file.txt in your current directory thatcontains This is the first line and the numbers 0-10. The built-in function str() convertsobjects, such as ints, to their string representations.

    14 Writing your second program in Python!

    Yay! Now its time to play with objects in python! Also with pies! Because pies are amaz-ing and delicious and very American. In your pythonIntro stencil folder, you should seetwo files called pieCount.txt and pieCounter.py. pieCount.txt is a text file (woohoo!you know how to read from and write to these) with each line of the form ,. Throughout the month, TAs have been recording how many pies theyeat and is the number of pies that a given TA ate at a given sitting.

    Introduction to Python January 29, 2013 14

  • 7/27/2019 Introduction to Pythonpythonintro.pdf

    15/17

    CS 16Introduction to Python

    Intro to Algorithms and Data Structures

    The second file in your stencil folder is an almost empty .py file that youll fill up withcode! YAY!

    14.1 Your code

    You should create one object that takes in a filename (a python string) as a parameter to itsconstructor. You can call your object whatever you want, but Ill refer to it as pieCounter.pieCounter should have one method (which Ill call countPies) that takes in the name ofa specific TA, counts up how many pies that the TA has eaten, and prints that number.Once youve written your class, instantiate your class in the name == main blockat the bottom of the .py file and call your method, passing in a few different TA names.Some examples are Timothy Parsons, Elijah ben Izzy, and Nicolas Cage.

    14.2 Hints!

    1. Characters of text files are strings in python! To cast a string to an integer, use theint() function. int(5) returns 5.

    2. Opening and closing files is expensive! Do you want to open and close the file ev-ery time a user calls countPies? Or should you read in the files contents in theconstructor and never have to open the file again?

    3. If you dont need a counter when iterating through a list, you shouldnt use range.Use the following syntax instead:

    >>> wordlist = [wooo, I, love, pie!!!]

    >>> for word in wordlist:

    ... print word

    ...

    wooo

    I

    love

    pie!!!

    4. You can get all the lines from a file in one list by calling myfile.readlines().

    5. split is a super cool method of python strings! Heres an example use: "My -

    name - is - George Washington!!!".split(-) returns ["My ", " name ", "is ", " George Washington!!!"]. That is: given some delimiter as a parameter,it breaks a string up into chunks, separated in the original by that delimiter.

    14.3 Handing in

    To hand in your code for this lab (well be looking at it in section next week) run cs016 handinpythonIntro2.

    Introduction to Python January 29, 2013 15

  • 7/27/2019 Introduction to Pythonpythonintro.pdf

    16/17

    CS 16Introduction to Python

    Intro to Algorithms and Data Structures

    15 Notes about Python

    15.1 Python version

    Please do NOT use Python 3 because Python 3 is not compatible with Python 2.6, whichwell be using for the duration of the course (and is still the industry standard).

    15.2 The use of if main

    For reasons explained here: https://developers.google.com/edu/python/introduction(under section Python Module) you should always put all code you wish to execute directly(i.e. code not part of a specific class or function definition) under a big if statement. ThePython syntax for the condition is: if __name__ == __main__. Heres an example:

    def function():# Function definition goes here.

    if __name__ == __main__:

    # Code to be executed when you run this program

    All your Python handins are required to follow this convention. We will deduct pointsfrom your grade if your code does not include this, so dont forget!

    15.3 Coding Conventions

    We require you to follow the CS16 coding conventions for Python assignments throughoutthe semester. We expect you to read and follow it. You can find the coding conventionshere: http://www.cs.brown.edu/courses/cs016/docs/PythonStandards.pdf

    15.4 Lambdas

    Python supports the ability to define one-line miniature functions on the fly. A traditionalfunction definition looks like this:

    def f(x):

    return x*2

    f(3) # evaluates to 6

    Heres a lambda function that accomplishes the same thing:

    g = lambda x: x*2

    g(3) # evaluates to 6

    Introduction to Python January 29, 2013 16

    https://developers.google.com/edu/python/introductionhttp://www.cs.brown.edu/courses/cs016/docs/PythonStandards.pdfhttp://www.cs.brown.edu/courses/cs016/docs/PythonStandards.pdfhttps://developers.google.com/edu/python/introduction
  • 7/27/2019 Introduction to Pythonpythonintro.pdf

    17/17

    CS 16Introduction to Python

    Intro to Algorithms and Data Structures

    Note the abbreviated syntax. There are no parentheses around the parameter list. Theresalso no return statement. The return keyword is implied, since the entire function canonly be one expression. The function itself has no name. Thats why lambda functions aresometimes called anonymous functions. We can call the function through the variable ithas been assigned to (in this case, g).

    Heres one more example:

    (lambda x: x*2)(3) # evaluates to 6

    In this example, we use the function without even assigning it to a variable.

    15.5 Additional reading

    This introduction to Python only scratches the surface of what Python is and what it can do.

    You can find the official tutorial here: http://docs.python.org/release/2.5.2/tut/tut.html .The sections that will be most useful for CS16 are: 1, 3, 4.1-4.6, 4.7.6, 5, 6, 7.1, 8.1-8.5 and9.3.

    16 Installing on your computer (Optional)

    16.1 Linux, Mac OS X

    Python should already be installed! To test it out, type python into your terminal to startthe interactive interpreter.

    16.2 WindowsGo to http://python.org/getit/ and download the latest 2.7 build for Windows. This shouldbe something like Python 2.7.3 Windows Installer. Install all the necessary files, thenopen up a Command Prompt (click Run from Start and enter cmd). If Python was installedat C:\python27 type:

    set path=%path%;C:\python27

    If it was installed in a different location, substitute C:\python27 with that. This com-mand lets you use the interactive interpreter.

    Introduction to Python January 29, 2013 17

    http://docs.python.org/release/2.5.2/tut/tut.htmlhttp://docs.python.org/release/2.5.2/tut/tut.htmlhttp://python.org/getit/http://python.org/getit/http://docs.python.org/release/2.5.2/tut/tut.html