[Tutor] NameError

ALAN GAULD alan.gauld at btinternet.com
Mon Aug 25 01:01:14 CEST 2014


forwarding to the group.
Please use ReplyAll when responding to the list.

 
Alan Gauld
Author of the Learn To Program website
http://www.alan-g.me.uk/

http://www.flickr.com/photos/alangauldphotos



>________________________________
> From: D.V.N.Sarma డి.వి.ఎన్.శర్మ <dvnsarma at gmail.com>
>To: Alan Gauld <alan.gauld at btinternet.com> 
>Sent: Sunday, 24 August 2014, 23:54
>Subject: Re: [Tutor] NameError
> 
>
>
>In the six places you have gb == boy or gb == girl, put 'boy' and 'girl'.
>I did and it works.
>
>
>regards,
>Sarma.
>
>
>On Mon, Aug 25, 2014 at 12:09 AM, Alan Gauld <alan.gauld at btinternet.com> wrote:
>
>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
>>
>>_______________________________________________
>>Tutor maillist  -  Tutor at python.org
>>To unsubscribe or change subscription options:
>>https://mail.python.org/mailman/listinfo/tutor
>>
>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20140825/ccd9ed12/attachment-0001.html>


More information about the Tutor mailing list