Introduction to Computer Programming

Program 0: a gentle introduction to Python programming

Due date: Thursday, September 20 at 5pm


  1. Here is a simple arithmetic algorithm:

     def thrice_plus_1():
         n = int(input('Enter a number: '))
         m = (3 * n) + 1


     In [1]: thrice_plus_1()
     Enter a number: 5
     In [2]: thrice_plus_1()
     Enter a number: 7

    Write the inverse function, to match this behavior (so it should use integer division to round down):

     In [1]: inverse_tp1()
     Enter a number: 16
     In [2]: inverse_tp1()
     Enter a number: 23
  2. Write a program that corresponds to the following prose description:

    Take a number called x. Output the difference between the square of two more than x and the square of one more than x.

    Use variables and assignments. Keep your arithmetic expressions simple: no more than a single arithmetic operation per assignment statement. Example:

     In [1]: prose()
     Enter a value for x: 4
     The difference is 11
     In [2]: prose()
     Enter a value for x: 7
     The difference is 17
  3. Write a function that asks for two pieces of text, prints the length of each string, then prints the concatenation of the two strings, and finally prints the length of that concatenation. Example:

     In [1]: concat_len()
     Enter some text: hello
     Enter some more text: nwheels
     The first phrase has 5 characters
     The second phrase has 7 characters
     The concatenation of those phrases is: hellonwheels
     That has 12 characters

    In a comment, explain why it makes sense for Python to use + for both the usual addition of two numbers and the concatenation of two strings.

  4. Write a function that prints “All work and no play make Jack a dull boy” 50 times without using any kind of loop. In fact, use only variable assignment and string concatenation and no other operations. Try to use as few characters as possible. The phrase “All work and no play makes Jack a dull boy” has 42 symbols (letters and spaces). It can be done in well less than 50 * 42 = 2100 characters. (My solution uses less than 1/10th of that - i.e., less than 210 characters.) Include a comment explaining how this problem demonstrates one of the benefits of using symbolic abstraction.

  5. (Courtesy of Jim Marshall.) Write a program that asks the user for a total number of seconds, and converts this to the corresponding number of hours, minutes, and seconds. Hint: the integer division (//) and remainder (%) operators might come in handy here. Examples:

     In [1]: seconds()
     How many seconds? 250
     = 0 hours, 4 minutes, 10 seconds
     In [2]: seconds()
     How many seconds? 10000
     = 2 hours, 46 minutes, 40 seconds