The Friendly Python

Lesson 1: The Expressive Python

A Taste Of Programming
Lesson: 1 2 3 4 5

Mississippi College

Computer Science 114

We won't write a program in this lab, but we'll practice running Python, and get a feel for the language by writing some Python expressions. These instructions are for a default installation of Python on Microsoft Windows. Python runs on many platforms, and the procedures will be only a little different on others.

  1. Open Idle from the Windows start menu.

    Idle is a program for making and running Python programs.

  2. You will see the Python Shell window where you can type Python expressions. Python evaluates them, and prints the result.

  3. Now, type some numeric expressions in the Idle window. After each one, press enter, and Python will show the result. (The >>> is Python's prompt; it lets you know Python is ready for you to type.) For instance,

    >>> 5 + 6
    11
    >>> 3*(3 + 8)
    33
    >>> (2 - 4) * ( 3 + 11)
    -28
    >>> 2 - 4 * 3 + 11
    1
    >>> 998
    998
    >>> 
    Note that the last "expression" is the simplest kind: No operators at all.

    Python arithmetic expressions generally do what you expect. Use + for addition, - for subtraction, * for multiplication and / for division. You can also use ** for exponentiation; that is, you can compute 56 by writing 5 ** 6. Python evaluates multiplication and division before addition and subtraction, just what your algebra teacher told you to do. You can also use parentheses to change the order.

    There is one unexpected pitfall: Do not type any spaces in front of your expressions. (We'll get to the reason for that in Lesson 3.)

    A. Express Yourself

    1. Suppose y = 4x2 + 5x - 10. Let Python find you y for when x = 7.
    2. If you count up to n, and total the numbers, the total is one half n times n+1. For instance, if you add 1 + 2 + 3 + 4 + 5, you get 15. You can also get fifteen by multiplying 5 by 6, then dividing by 2. Get Python to tell you the sum of the numbers from 1 to 3000.
    3. If you haven't yet managed to accidentally type an expression with spaces before it, make one on purpose to see what happens.

  4. Python, as many programming languages, makes a distinction between integer and floating point numbers. Floating point numbers are allowed to have fractional parts, and are always written with a decimal point, even if the fractional part is zero. Integers, of course, are whole numbers, and are written without a decimal point. Operations on floating point numbers, or on one of each, produce floats.

    >>> 4 * 5
    20
    >>> 4.0 * 5.0
    20.0
    >>> 4 * 5.0
    20.0
    >>> 3.45 + 2.8
    6.25
    >>> 4.987 * -14.9874
    -74.7421638
    >>> 
    Follow the decimal points: The first operation multiplies two integers and produces an integer. The second multiplies two floats and produces a float. They are floats because they are written with a decimal point, even though their values are integral. Some of the later examples have fractional parts, which is the more likely use of floating point.

    Why does any of this matter to programmers? In most cases it doesn't, except for the division operation. Addition, subtraction, and multiplication are tame because the sum, difference or product of two whole numbers is always a whole number. For division this is not so: one divided by two is a half, after all. When dividing integers, Python simply discards any fractional part to produce an integer result.

    >>> 11 / 2
    5
    >>> 11.0 / 2.0
    5.5
    >>> 456 / 503
    0
    >>> 456 / 503.0
    0.90656063618290261
    >>> 
    Try some divisions until you see how these rules work.

    Integer and floating point numbers are represented differently inside the computer, and integer arithmetic is faster for the CPU to perform. Having the two forms allows programmers to choose faster integer arithmetic when it will do, or slower floating point when needed.

  5. Understand what is happening in these two expressions.

    >>> (4 + 2) / (5 + 3)
    0
    >>> (4 + 2.0) / (5 + 3)
    0.75
    >>> 

    B. Sewing Division

    1. Write an expression to take the average of five floating-point numbers.
    2. Write an expression that will display 5/7 as a percentage. Should you use integer or floating point numbers?
    3. Find out what happens when you divide by zero. Does it matter whether you use integer or floating point?

  6. Python calculation is not limited to numbers. It also supports strings, which are just sequences of characters. Strings must be enclosed in quotes. You can use either double quotes or single quotes, but you must end with whatever you start with.

    >>> "Howdy"
    'Howdy'
    >>> 'Fred Lives!'
    'Fred Lives!'
    >>> "We're making strings."
    "We're making strings."
    >>> ""
    ''
    >>> "Not working.'
      File "<stdin>", line 1
        "Not working.'
                     ^
    SyntaxError: invalid token
    >>> 
    The last of the above examples produced an error message. It's quite likely you've managed to create one of these before now. In any case, they don't damage anything, except possibly your composure. You just figure out what's wrong and try again.

    Also notice that a string of characters is allowed to contain no characters at all. This is the empty string. It is much like an empty set in mathematics, or perhaps you might think of it as the string version of zero. Also note that it is different from the string containing a space.

  7. The + operator works on strings, but it doesn't add them.

    >>> "Hi " + 'there.'
    'Hi there.'
    >>> "These" + "are" + "glued"+'together.'
    'Thesearegluedtogether.'
    >>> "These" + '' + "are" + "glued"+ " " + 'together.'
    'Theseareglued together.'
    >>> 
    This operation is called concatenation. Concatenation is just a fancy name for "pasting strings together."

  8. Notice how flexible the + sign is. When you use one between two integers, it does an integer addition. When you use floats, you get a float addition, and when you use strings, you get concatenation.

    >>> 12 + 15
    27
    >>> 12.0 + 12.5
    24.5
    >>> "12" + "15"
    '1215'
    >>> 17 + 'Fred'
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
    TypeError: unsupported operand types for +: 'int' and 'str'
    >>> 
    This reuse of the same operator, the plus sign, to perform different operations on different types of data is called overloading. We have loaded several different meanings onto one operator. Most programming languages use overloading, and so does English: you can run a race, or you can run a chain saw. The verb "run" means rather different things depending on what it's applied to.

    Try some other string concatenations. Also, see if you can figure out what the * means when applied to a string and an integer. Does it make sense?

  9. Python also supports operations to extract portions of a string.

    >>> "fred"[2]
    'e'
    >>> "This is nice"[3:10]
    's is ni'
    >>> "Zippo"[0]
    'Z'
    >>> 'Take the large one'[0:10]
    'Take the l'
    >>> 
    The brackets extract a portion of a string to produce a new string. The numbers select characters based on their position. Position is counted from the left, starting with zero.*

    When you select using a single number, you get a string containing the single character at that position. When you use two, the first chooses the starting character, and the second indicates the first character past your selection. Try a few, and try combining them with the other string operations.

    >>> "Tuesday"[2:4] + 'Wednesday'[3]
    'esn'
    >>> 'Goober'[4]
    'e'
    >>> 'Goober'[4:4]
    ''
    >>> 'Goober'[4:2]
    ''
    >>> ("goober" + ' smile')[3:9]
    'ber sm'
    >>> 
    The two selection mechanisms have different names. When a single number is used, Python calls it a subscript. When two are used, it is called a slice. Slices of strings are also frequently called substrings.

  10. The slice notation allows a simple shortcut. If you omit the first number, it defaults to zero, and if you omit the second, the slice goes to the end of the string.

    >>> 'daisy'[3]
    's'
    >>> 'daisy'[:3]
    'dai'
    >>> 'daisy'[3:]
    'sy'
    >>> 'daisy'[:]
    'daisy'
    >>> 

  11. Sometimes it's nice to know the length of a string. You can find this with the len function.

    >>> len("abc")
    3
    >>> len('Freddo' + "a b"[1] + "Python")
    13
    >>> len("smith") + 5
    10
    >>> 
    Len is a an example of a built-in function. Functions are used as you see here, name first, then a list of arguments, which are the input values to whatever the function computes. This particular function takes a single string as its input, and produces an integer result.

    C. Strings And Things

    1. Write an expression that concatenates the strings "John" and "Marsha", then selects and prints the substring "nMa".
    2. Write an expression that contains the string "transfiguration" and prints as 'train'. Your expression should contain no strings other than "transfiguration", but you may need to type that in more than one place.
    3. Write an expression which contains one string, but evaluates to a string of asterisks of the same length. That is, if you write a version of your expression containing the string 'eggplant', your expression produces '********'.
    4. Find out what happens when you select portions of a string past its end. Does it matter whether you use subscripting or slicing?

  12. So far, we have been using Python to evaluate and print expressions. Often, though, programmers like to retain an expression's value for later use. This is done with variables, which are simply names that can retain values. For instance:

    >>> mike = 7
    >>> bill = 3 * mike
    >>> bill
    21
    >>> mike
    7
    >>> bill = mike - 18
    >>> bill
    -11
    >>> 
    Use the = sign to assign a value to a variable. Put the variable name to the left, and any Python expression to the right. The expression is evaluated, then given to the variable. When you use the variable name in subsequent expressions, it has the value assigned. You can change the value of a variable by simply assigning it again.

    To know the value of a variable, simply type the variable name, and Python will print its value. When you do this, you are just typing a no-operator expression.

    It is an error to use a variable name in some expression if you have not assigned it a value first.

    >>> alice = 42
    >>> alice + 10
    52
    >>> alice + jane
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
    NameError: name 'jane' is not defined
    >>> 

  13. Python variable names may contain letters, digits and the underscore character, _, but may not start with a digit, and usually should not start with underscore. Variable names may not contain spaces. Examples of legal variable names are t, Smith, Bill_Smith and Num_17. If you try to use Bill Smith, 7up or A$ as variable names, Python will hiss at you.

    >>> 7up = 33
      File "<stdin>", line 1
        7up = 33
          ^
    SyntaxError: invalid syntax
    >>> 
    While you may generally use any variable name you like within these rules, there is a small list of keywords, which are not allowed as identifiers. These have special purposes, and we will encounter some of them later. If you're curious, the full list is here.

  14. Python variable names are case-sensitive. That means it matters whether you use small or capital letters. The variables tank, Tank, TANK and TaNk are four separate names, unrelated as far as Python is concerned.

    >>> tank = 10
    >>> Tank = 'Boom'
    >>> TANK = "BOOOOOOOOMMMMMM"
    >>> tank
    10
    >>> Tank
    'Boom'
    >>> TANK
    'BOOOOOOOOMMMMMM'
    >>> TaNk
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
    NameError: name 'TaNk' is not defined
    >>> 

  15. Variables are not limited to holding numbers.

    >>> joe = "My way, or the highway."
    >>> len(joe)
    23
    >>> bill = 4
    >>> joe[bill:bill+5]
    ay, o
    >>> 
    Try assigning string values to some variables and using them.

  16. Because Python assignments use the =, they look a bit like mathematical equations. They are not. An assignment directs the computer to evaluate the expression on the right side, then assign its value to the variable on the left. This means that you can make assignments using the variable assigned.

    >>> sally = 17
    >>> sally
    17
    >>> sally = sally + 2
    >>> sally
    19
    >>> 
    In the second assignment, sally is initially 17 (from the first assignment). The second assignment starts by computing the expression sally + 2 to get 19, then assigns the 19 to sally. This also points out that assignments are not equations: x = x + 2 doesn't make much in algebra class.

    D. Variable Variations

    1. Set a variable to integer 37. Use an assignment to cut it in half using integer division. Repeat this until you reach zero.
    2. Assign any floating values you like to variables x, y and z. Then write an expression which takes the average of x, y and z. Change some of these values, then evaluate your expression again to see the changed result.
    3. Assign the variable s some long string value. Write an expression which returns a string consisting of the first two and the last two characters in s. For instance, if s is google, your expression should return the string gole. Try giving various values to s and trying your (same) expression again. What happens when your string is shorter than four?
    4. Write an expression which produces a string of asterisks of the same length as whatever is in s.
    5. Find out what happens when you send the len function a variable that contains an integer value.

Now that we know how to get python to evaluate expressions, we're ready to write some Python programs. This will involve creating files of these expressions which we can run repeatedly. That will be the subject of Lesson 2.


*Computer scientists like to count things from zero because it simplifies certain calculations. For instance, In the present year 2005, it's the 21st century, which started with 2001; the year 2000 was the last of the 20th century. If we had started with year zero of the zeroth century, we'd be living in the year 2004 in the 20th century, which would have started with the year 2000. The century number and the year always agree, and the century and the first two digits of the year change at the same time.


Copyright 2005, 2006 Thomas W Bennet  •  Image Credits  •  Terms of use: Creative Commons