[Tutor] Defining functions

Kent Johnson kent37 at tds.net
Fri Mar 25 00:43:02 CET 2005


John Carmona wrote:
> Hi there,
> 
> I have written (well almost as I copied some lines from an existing 
> example) this little programme - part of an exercise.

> def print_options():
>        print "------------------------------"
>        print "Options:"
>        print "1. print options"
>        print "2. calculate circle area"
>        print "3. calculate square area"
>        print "4. calculate rectangle area"
>        print "5. quit the programme"
>        print "------------------------------"
>        choice = input("Choose an option: ")
>        if choice == 1:
>            print_options()
>        elif choice == 2:
>            area_circ()
>        elif choice == 3:
>            area_squ()
>        elif choice == 4:
>            area_rect()
>        elif choice == 5:
>            print_options()
> 
> If I try to change the 1, 2, 3, 4 or 5 by a letter i.e. a, b, c, d, e 
> the programme stop functionning. I get an error message saying that
> 
> Traceback (most recent call last):
>  File "C:/Python24/Example/area_cir_squ_regt.py", line 39, in -toplevel-
>    print_options()
>  File "C:/Python24/Example/area_cir_squ_regt.py", line 27, in print_options
>    choice = input("Choose an option: ")
>  File "<string>", line 0, in -toplevel-
> NameError: name 'c' is not defined

The input() function evaluates the input as if it is Python code. So you can type 1+2 to input and 
it will return 3, for example:

  >>> print input('type a valid expression: ')
type a valid expression: 1+2
3

If you type a bare string, Python expects this to be a variable name:
  >>> print input('type a valid expression: ')
type a valid expression: a
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
   File "<string>", line 0, in ?
NameError: name 'a' is not defined

This is exactly the same error you would get if you just typed a bare 'a' at the interpreter prompt:
  >>> a
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
NameError: name 'a' is not defined

To get a string from input(), you have to type it with quotes:
  >>> print input('type a valid expression: ')
type a valid expression: 'abcd'
abcd

raw_input() will return the literal string the user typed. If you input is a string, this is what 
you want:
  >>> print raw_input('type anything: ')
type anything: 1+2
1+2
  >>> print raw_input('type anything: ')
type anything: abcd
abcd

In general, raw_input() is safer than input(), which is vulnerable to abuse. Even if you want an 
integer input, you can use raw_input() and int():
  >>> print int(raw_input('type a number: '))
type a number: 35
35

Kent

PS you do need to quote the letters in your if / elif also.



More information about the Tutor mailing list