Up: Python

Basics

slide 001 Hello, and welcome to the second episode of the Software Carpentry lecture on Python. This episode will introduce you to the basic elements of the language.
slide 002 Python is a simple interpreted language.
slide 003 The word “interpreted” means that unlike programs in C, Java, Fortran, and C#, Python programs don’t have to be compiled before they can be run: commands are executed immediately.
slide 004 To run Python interactively from a command shell, just type python. This will bring up a prompt, which is usually three greater-than signs.
slide 005 You can have Python do simple arithmetic…
slide 006 …or manipulate strings of text, just by typing in commands.
slide 007 More often, though, you will put commands in a file and have Python execute that.
slide 008 For example, you can use a simple editor like Pico…
slide 009 …to put the same commands we just ran in a file called very-simple.py
slide 010 …and then have Python run that file.
slide 011 A third choice that combines the best features of the two above is to use an integrated development environment, or IDE. We recommend Wing 101, the free student version of Wing, but there are many others.
slide 012 The IDE gives you an editor that is customized for displaying Python source code…
slide 013 …and an interactive shell for trying things out. We’ll explore some of the other tools IDEs provide later in this course.
slide 014 Back to Python itself. Like other languages, it allows you to create variables, which are names for values.
slide 015 Unlike compiled languages, though, Python variables are created by use:
slide 016 there’s no need to declare them explicitly.
slide 017 For example, assigning the string 'Pluto' to the variable planet automatically creates that variable.
slide 018 We can then print out its value to make sure it’s right.
slide 019 Internally, Python stores a table of all the variables created so far, and keeps track of the values they refer to.
slide 020 If we assign the string 'Charon' to the variable moon, Python adds an entry to this table for moon, allocates some memory to store the string 'Charon', and makes the variable point to that string.
slide 021 We can assign variables to variables, too, with statements like p = planet.
slide 022 This creates a new variable as before, but this time, that variable points to the same value that planet was pointing to.
slide 023 Sure enough, if we print p, Python displays the string 'Pluto'.
slide 024 A variable in Python is just a name.
slide 025 Unlike variables in some other languages, Python’s variables do not have specific data types.
slide 026 For example, we can assign a string 'Pluto' to planet
slide 027 …creating the table entry shown here…
slide 028 …and then immediately assign the integer 9 to the same variable. This would be an error in a language like Java, since strings and integers are different data types, but Python is quite happy to do this.
slide 029 One other important feature of Python is that values are garbage collected.
slide 030 This means that if nothing refers to a piece of data any longer, Python recycles its memory.
slide 031 For example, once we assign 9 to planet, nothing is pointing at 'Pluto' any longer, so Python is free to reclaim that memory and use it to store other information.
slide 032 Python is relaxed about the type of data assigned to variables, but it does insist that variables have values before they are used.
slide 033 For example, let’s assign the string 'Sedna' to planet
slide 034 …and then try to print the value of the variable plant (without an ‘e’).
slide 035 Python immediately displays an error message because we haven’t defined a value for anything called plant.
slide 036 It does not fill in some sort of default value for undefined variables, such as 0 or the empty string…
slide 037 …because doing so can mask errors resulting from simple typing mistakes.
slide 038 Also, while we’re here, notice Python’s commenting convention: anything from the ‘#’ character to the end of the line is ignored, which allows programmers to add explanations (or warnings) to their programs.
slide 039 In contrast with variables, values in Python do have types.
slide 040 For example, suppose we try to multiply a string by a number. Python is OK with this: it knows what * means when applied to a string and an integer.
slide 041 But if we try to add a string and a number, we get an error message, because Python doesn’t know what + means when applied to those types.
slide 042 In this case, you’d probably think that 'two3' would be a sensible answer.
slide 043 But then what should be the result of adding the string '2' to the string '3'? Should it be the string '23', the integer 5, or the string '5'?
slide 044 In programming languages, experience teaches that doing too much is just as bad as doing too little.
slide 045 If we really do want to “add” the string '2' to the integer 3, we can use some built-in functions to convert one or the other first.
slide 046 The function int takes a string of digits and produces the corresponding number…
slide 047 …while the function str turns a number (or almost anything else) into text.
slide 048 And speaking of numbers, Python provides several types.
slide 049 The simplest are integers, which on most machines are stored in 32 bits (though 64-bit machines are now becoming common).
slide 050 Python also provides floating point numbers, which are usually stored in 64 bits…
slide 051 …and complex numbers, which are written using ‘j’ for the imaginary part, and are stored in a pair of 64-bit numbers.
slide 052 If x is a complex number, then x.real and x.imag are its real and imaginary parts.
slide 053 Python provides the usual arithmetic operations on numbers.
slide 054 Plus for addition…
slide 055 …which can also be used to concatenate strings.
slide 056 Minus for subtraction…
slide 057 Star for multiplication…
slide 058 …which can be used on strings as well.
slide 059 Slash for division…
slide 060 …which produces an integer (throwing away any fractional part) if both its arguments are integers.
slide 061 Double star for exponentiation…
slide 062 …and percentage sign for integer remainder.
slide 063 Like other languages in the C tradition, Python allows you to use in-place forms of binary operators to make your programs more readable.
slide 064 For example, suppose we’ve assigned 500 to the variable years.
slide 065 If we write years += 1, Python adds 1 to the value in years.
slide 066 It’s exactly the same as writing years = years + 1, but it’s shorter and easier to read, particularly if the expressions involved are long or complicated.
slide 067 Sure enough, we’ve incremented years by 1.
slide 068 Other binary operators have in-place equivalents as well. Here, for example, we use %= to replace the value in years with the old value modulo 10.
slide 069 Again, this is the same as years = years % 10.
slide 070 And the answer is what we expect.
slide 071 Arithmetic operators turn numbers into numbers; comparisons turn numbers or strings into True or False.
slide 072 Simple ones, like less than, are written as you’d expect.
slide 073 But Python uses != for “not equal”.
slide 074 And a double equal sign to test for equality.
slide 075 Remember: a single = is assignment, while a double == is a comparison.
slide 076 Of course, partial inequalities like >= can be used too.
slide 077 And unlike most programming languages, Python allows inequalities to be chained together, just as in mathematics.
slide 078 You can even change the sense of the comparison midflight, but please don’t: it’s very hard to read.
slide 079 And please don’t try to do any kind of comparison on complex numbers other than equality and inequality: it doesn’t work in Python any more than it works in mathematics.
slide 080 Now that we’ve seen the basic “atoms” of Python, the next lecture will explore how to combine them to make useful programs.

  1. Cole Van Vlack
    October 15th, 2010 at 17:59 | #1

    Great first lecture. I read about you in the latest nature and thought I should see what you are teaching. Is there any way you can make it so that you can expand any of the slides or offer them in a downloadable format (.pdf, .ppt, etc…)? Some of the graphics are just hard to see. The videos look great though.

  2. Christian Mascher
    October 23rd, 2010 at 09:28 | #2

    Very good overview. You could correct a minor bug in

    >> print 2 + str(3)

    which only makes sense as >> print ’2′ + str(3)

    (and in newer versions print becomes print() … )

  3. Shy Guy
    October 31st, 2010 at 03:20 | #3

    Shouldn’t years modulo 10 – i.e, 501 % 10 – be 1?

  4. Mike901
    November 2nd, 2010 at 00:04 | #4

    501 mod 10 = 1 !!
    There’s an error in the slides…

    Please correct it!

  5. Tanya
    January 25th, 2011 at 18:31 | #5

    Isn’t it true that 501 % 10 = 1 as Shy Guy and Mike901 pointed out?

  6. luis
    January 26th, 2011 at 15:48 | #6

    @Christian Mascher
    Ooops. Bug report for this one!

    You are right, print 2+str(3) will produce a type error (as seen on a previous slide, “print string+number”). The intended form was “print ’2′ + str(3)”.

    Thanks for noticing.

  7. luis
    January 26th, 2011 at 15:50 | #7

    @Tanya
    @Mike901
    @Shy Guy

    Indeed. 501 % 10 = 1.
    Another error in the slides. Please assume it reads = 1 until we get around to fix it.

    Thanks!

  8. Terri Yu
    January 27th, 2011 at 19:57 | #8

    In the slide where the code

    print string * number

    is demonstrated, the string is defined by

    string = “two”

    This might be confusing because single quotes are used everywhere else for string literals, even though it is correct that either single or double quotes is fine.

  1. No trackbacks yet.