[Tutor] NameError

Alan Gauld alan.gauld at btinternet.com
Sun Aug 24 20:39:32 CEST 2014


On 24/08/14 15:11, Mimi Ou Yang wrote:

> age = int(input("Enter your age: "))
> gb = input("Are you a boy or a girl? ")

input() returns a string so the values here
should be 'boy' or 'girl' - Notice the quote signs.

> op = input("How are you feeling today? ")
>
> if (age in (1,2,3,4,5,6,7,8,9,10,11,12)):
>      print (name,"you are a little",gb,"that is feeling",op,"today.")

If you are using loing sequences of values you should consider using the 
range() function instead or use a comparison check:

either

if age in (range(1,13):    # last value not included

or

if 1 <= age <= 12:

Its less typing and easier to see the intention.
For small numbers of values the tuple approach is
fine but once you get more than say, 7 values its
harder to read.

The exception is if you are testing for non
contiguous values, in that case an explicit tuple
will be needed.

> if (age in (18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33)) and (gb ==
> boy):

Notice that you are testing

.... and (gb == boy):

no quotes so Python looks for a variable called boy.


> if (age in (18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33)) and (gb ==
> girl):

The same here for girl


> (34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56))
> and (gb == boy):
> NameError: name 'boy' is not defined
>  >>>

So use quotes when testing for string values

you might also like to force the input to lowercase so that users can 
type Boy or BOY if they wish:

.... (gb.lower() == 'boy')

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list