The Friendly Python

Lesson 2: Simple Programs

A Taste Of Programming
Lesson: 1 2 3 4 5

Mississippi College

Computer Science 114

Lesson 1 gave us a chance to stick our toes into the Python-infested waters*; now it's time to dive in.

In these exercises, we will create programs, which are saved as files. You may store these files where ever you like, including on the desktop, or the computer's C: drive. Since out lab PC hard drives are periodically cleared, any files you want to keep should be saved on removable storage, such as a floppy or USB pen drive. Your instructor may also want you to hand in certain files, and will give you instructions how this is to be done.

Secondly, you will often be asked to enter a specific program listed in this page. Copy-and-paste is not a crime. However, please limit yourself to copying from these lesson pages, and not from other sources, or from each other. Figuring this stuff out in your very own brain is the only way to learn it.

  1. Begin by opening Idle as we did in Lesson 1.

  2. Now, create a window in which to enter your program. Select New Window from the File menu on the Python expression evaluation window.

  3. A new Untitled window will appear. Enter the following program into it:

    mike = 17
    bill = -6
    print mike * bill
  4. Save your file using the File menu on the window where you entered the program (not the Idle Python Shell window). Use Save As, and save the file as myfile.py. As noted above, you may save it where ever you like.

  5. Now, use Idle to run the program. Choose Run Module from the Run menu. The output will be placed in the main window, which will show something like this:

    >>> ============== RESTART ==============
    >>> 
    -102
    >>> 
  6. As you can see, your program is run, and its output is added to the expression evaluation window. The RESTART line indicates that, before running your program, Idle discarded any variables you created in the window, so your program starts with a clean slate.

    Running the program just means executing each statement in order from the start. Python set mike to 17, then set bill to -6, then printed their product. Their values are still present, if you want to see them:

    >>> ============== RESTART ==============
    >>> 
    -102
    >>> mike
    17
    >>> bill
    -6
    >>> 
    The print statement is new, but it should be fairly obvious what it does: it prints the value of an expression on the screen. When you are running Python interactively by typing expressions directly, each expression value is automatically printed on the screen. When running a program, expressions are not printed. You must use the print statement to see their values.

  7. Take the word print out of your program so it looks like this:

    mike = 17
    bill = -6
    mike * bill
    Run it again, and notice that it no longer prints your value. Then put the print word back.

  8. Try running the program with different values. Change the assignments to mike and bill, then save and run the program again.

  9. Output looks nicer when it's labeled. Modify your program so that it looks like this:

    # Simple product.
    mike = -5
    bill = 12
    print "The product is", mike * bill
    Save it and run it. There are a couple of things to notice about this:
    • The print statement takes a list of expressions separated by commas. Each one is printed on the same line, separated by spaces.
    • The string is printed without quotes.
    This helps create a nicely-formatted output message.

    We've also thrown in one other small thing that programmers use. The first line, starting with # is a comment. A comment is part of the program which is ignored by the computer. Programmers use them to make notes to themselves or other programmers. Comments may identify who wrote the program, or what it is for. They are often used to summarize what part of a program accomplishes, or to explain the method used. When Python sees a # character (unless it is part of a string), Python simply ignores the # and the rest of that line.

  10. Modify your program to compute a different product and run it again.

  11. Now, it gets boring to keep changing your program just to put new values in it. It's much nicer to enter the values whenever you run the program. For that, we need an input statement. Modify your program to look like the following:

    # Product with input
    mike = raw_input("Please enter a value for mike: ")
    print "You entered", mike
    bill = 7
    print "The product is", mike * bill
    Save your program and run it. It will ask for a value for mike. Enter an integer value. Python will then let you know what you entered, set bill to 7, then produce the product. Did it produce the value you expected? Why?

  12. If that was what you expected, good for you!. You must have

    • Remembered what * does when applied to a string and an integer.
    • Realized that raw_input returns a string, not an integer.
    Obviously, the function raw_input takes a string as its argument, which it prints on the screen when asking for input. It also returns a string. This makes sense since a string is just a sequence of characters, which is what one types on a keyboard.

    You might think that, since the characters you typed were digits, Python would figure out that you were sending it an integer. The raw_input function does not do this; it just puts the characters into a string and returns it. To get an integer, we use the built-in int function which takes a string of digits and returns the represented integer. Change your program to look like this one:

    # Correct product with input
    mike = raw_input("Please enter a value for mike: ")
    print "You entered", mike
    bill = 7
    print "The product is", int(mike) * bill
    Save the program, run it a few times, and see if this is more what you expected. Also, try entering some data which is not an integer, and see what happens.

  13. The above program works fine, but Python programs usually seem to use it like this:

    # Product with input
    mike = int(raw_input("Please enter a value for mike: "))
    print "You entered", mike
    bill = 7
    print "The product is", mike * bill
    Modify your program to look like this one. Run it a few times. Can you find any difference in its behavior (what you observe when it runs)? Is there any difference in how it operates (what goes on inside while it runs)?

  14. Modify your program again so that that it requests and reads a value for bill in the same way. Run your program a few times to see if it works.

    A. Get With The Program!

    1. As noted in Lesson 1, if you count up to n, and total the numbers, the total is one half n times n+1. Write a Python program that asks for an n value and reports the total of the integers from 1 to n.
    2. Suppose y = 4x2 + 5x - 10. Write a program which will request a value for x, and print the corresponding y value. (The function float can be used to convert input strings to floating point numbers.)
    3. The area of a triangle is one half the base times the height. Write a Python program which will ask for the base and hight, and report the area.

  15. We've been going to all this trouble to convert the input strings into numbers, but we can certainly leave them as strings. Here's a program for a short madlib:

    # Short madlib.
    name = raw_input("Please enter a proper name: ")
    adv = raw_input("Please enter an adverb: ")
    adj = raw_input("Please enter an adjective: ")
    pn = raw_input("Please enter a plural noun: ")
    print
    print name, "went", adv, "to the store"
    print "and bought some", adj, pn + '.'
    Open a new editing window, enter this code, and save it with whatever name you like and the ending .py. Run it a few times. What is the purpose of a print with nothing to print? And, why does the last print use a + sign instead of a comma between pn and the final period? (Both things effect the appearance of the output rather than the information presented.)

    B. The String's The Thing

    1. Extend the above madlib program by adding two or more additional inputs, and producing one or more additional lines.
    2. Write a Python program that requests one line of input, tells you how many characters you typed, and reports the first and last character. The output should look like this:
      Please enter a line: I like snakes
      You typed 13 characters.
      The first one was 'I'.
      The last one was 's'.
      Don't forget your string operations from Lesson 1.
    3. Write a program which takes a line of input, and prints it with a box around it. Like this:
      Please enter a line: Snakes are our friends.
      +-----------------------+
      |Snakes are our friends.|
      +-----------------------+
      For this, you will need the len function, concatenation, and the * operator for string and integer.

In Lesson 1, learned to make Python expressions. In this lesson, you learned to put them into a file, and get input values for them to process. These programs always run the same expressions on these data. In Lesson 3, we'll learn to write programs which can use the input data to select which expression to run, or to run one several times. Onward to Lesson 3!


*Yes, I know pythons generally live on the ground or in trees. I just needed to start out somehow.


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