Week 5

Textual User Interface, Some Strings, Functions, and Conditionals

Author:Christopher Haynes
Email:chaynes@indiana.edu
Affiliation:Indiana University
Course:BL CSCI A201
Date:2008-02-07
Copyright © 2008, Christopher Haynes—all rights reserved.

Contents

RUR-PLE reading this week

Temperature conversion program with printed output

# celsius1.py, by chaynes@indiana.edu

# Print conversion of tempearture in constant 'fahrenheit' to degrees Celsius.

fahrenheit = 53.0

celsius = 5.0/9 * (fahrenheit - 32)

print fahrenheit, "degrees Fahrenheit is", celsius, "degrees Celsius"

Temperature conversion program with interactive input

# celsius2.py, by chaynes@indiana.edu

# Prompt for tempearture in degrees Fahrenheit and print its conversion to degrees Celsius.

fahrenheit = int(raw_input("Degrees Fahrenheit: "))

celsius = 5.0/9 * (fahrenheit - 32)

print fahrenheit, "degrees Fahrenheit is", celsius, "degrees Celsius"


Interactive character (shell) input

Other temperature conversion program notes

Textual User Interfaces

GUI vs. TUI

Shell Scripts

Interactive demo: simple strings and the print statement

::
>>> 3
3
>>> print 3
3
>>> 'this is a string'
'this is a string'
>>> print 'this is a string'
this is a string
>>> print 'The answer is', 1+2
The answer is 3
>>> print 1, '+', 2, '=', 1+2
1 + 2 = 3

What is printing?

Demo: more fun with type functions

>>> int('3')
3
>>> int('1+2')
Traceback (most recent call last):
  File "", line 1, in 
ValueError: invalid literal for int() with base 10: '1+2'
>>> float(' 3.14159 ')
3.1415899999999999
>>> str(3.14159)
'3.14159'
>>> str(1 + 2)
'3'

Type functions revisited

Example: abstracting behavior

# celsius3.py, by chaynes@indiana.edu

# Prompt for tempearture in degrees Fahrenheit and print its conversion to degrees Celsius.

# return the result of converting the Fahrenheit temperature to celsius
def celsius(fahrenheit):
    return 5.0/9 * (fahrenheit - 32)

def main():
    f_temp = float(raw_input("Degrees Fahrenheit: "))
    c_temp = celsius(f_temp)
    print f_temp, "degrees Fahrenheit is", print c_temp, "degrees Celsius"

main()

return statement

Demo: printing is not returning

>>> def print_three():
        print 3
>>> def return_three():
        return 3
>>> return_three() + 1
4
>>> print_three() + 1
3
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
>>> print return_three()
3
>>> print print_three()
3
None
>>>

Printing vs. returning

clicker Which is probably better for a simple program that only you will use?

  1. A graphic user interface
  2. A textual user interface
  3. Neither, they are about the same difficulty to implement

Answer: B

clicker If a function is supposed to return a value it computes

  1. it must contain a return statement
  2. it must contain a print statement
  3. it may contain either a return or a print statement
  4. it must contain both a return and a print statement

Answer: A

clicker What does the following program do?

def f():
    print 3

f
  1. There is a syntax error, so the program does not run
  2. The program runs, but does nothing
  3. 3 is printed

Answer: B

Demo: forever temperature conversion service

# celsius4.py, by chaynes@indiana.edu

# Repeatedly prompt for tempearture in degrees Fahrenheit
# and print its conversion to degrees Celsius.

# return the result of converting the Fahrenheit temperature to celsius
def celsius(fahrenheit):
    return 5.0/9 * (fahrenheit - 32)

def main():
    while True:
        f_temp = float(raw_input("Degrees Fahrenheit: "))
        c_temp = celsius(f_temp)
        print f_temp, "degrees Fahrenheit is", print c_temp, "degrees Celsius"
    
main()

Infinite loops

Ways of killing programs

Demo: string literals, docstrings, and help

>>> print 'The Knights said "Ni"'
The Knights said "Ni"
>>> print "That'll do"
That'll do
>>> s = """This is a multi-line
... string with
... three lines"""
>>> print s
This is a multi-line
string with
three lines
>>> min(2, 3)
2
>>> min

>>>
>>> help(min)
Help on built-in function min in module __builtin__:

min(...)
    min(iterable[, key=func]) -> value
    min(a, b, c, ...[, key=func]) -> value

    With a single iterable argument, return its smallest item.
    With two or more arguments, return the smallest argument.

>>> def middle(x, y, z):
...     """
...     Of the three values that are given,
...     return the one that is between the other two.
...     """
...     return max(x, min(y, z))
...
>>> help(middle)
Help on function middle in module __main__:

middle(x, y, z)
    Of the three values that are given,
    return the one that is between the other two.

>>>

String literal syntax

Help is just a function call away

Doc strings

Example: temperature conversion program with string documentation

# celsius5.py, by chaynes@indiana.edu

def celsius(fahrenheit):
    """
    Return the result of converting the Fahrenheit temperature to celsius.
    
    >>> celsius(32)
    0.0
    >>> celsius(212)
    100.0
    >>>
    """
    return 5.0/9 * (fahrenheit - 32)

def main():
    """
    Repeatedly prompt for tempearture in degrees Fahrenheit
    and print its conversion to degrees Celsius.
    """
    while True:
        f_temp = float(raw_input("Degrees Fahrenheit: "))
        c_temp = celsius(f_temp)
        print f_temp, "degrees Fahrenheit is", print c_temp, "degrees Celsius"
main()

Module use demo

>>> import math
>>> math.sqrt(4)
2.0
>>> import random
>>> random.random()
0.24550873036853438
>>> random.randrange(10)
5

Modules

import statement

Using module attributes

Module functions introduced this week

Conditional evaluation example

# celsius6.py, by chaynes@indiana.edu

def celsius(fahrenheit):
    """
    Return the result of converting the Fahrenheit temperature to celsius.
    
    >>> celsius(32)
    0.0
    >>> celsius(212)
    100.0
    >>>
    """
    return 5.0/9 * (fahrenheit - 32)

def main():
    """
    Repeatedly prompt for tempearture in degrees Fahrenheit
    and print its conversion to degrees Celsius.

    Exit if 'quit' is entered.
    """
    while True:
        text = raw_input("Degrees Fahrenheit, or 'quit': ")
        if text == 'quit':
            return
        f_temp = float(text)
        c_temp = celsius(f_temp)
        print f_temp, "degrees Fahrenheit is", c_temp, "degrees Celsius"
    
if __name__ == '__main__':
    main()

Sentinel loops

Am I running as a program or a subprogram?

Comparison operators

Simple if statement

What's true?

Two-armed conditionals

Conditional flow charts

onetwoif.png


Example: isDivisible

Exercise: abs function

clicker abs function implementation

clicker Which of the following four functions returns the minimum of its two arguments?

def a(x, y):                  def c(x, y):
    if x <= y:                    if x < y:
        x                             print x
    else:                         else:
        y                             print y

def b(x,y):                   def d(x, y):
    if (x < y):                   if y > x:
        return y                      return x
    else:                         else:
        return x                      return y

Answer: D

Chained conditionals

Chained conditional flow chart

ifchain.png


Using chained conditionals

FYI Though block is the term for a sequence of statements in most languages, in official Python documentation the term suite is used instead of block

Example: sign

Boolean operators

and and or are lazy

Operator precedence revisited

Chained ordering operators

How to learn a programming language

Practice and review problems

Python Syntax page

Trees

Parse trees

Parse tree tools