loops

Chris Angelico rosuav at gmail.com
Sun Dec 2 22:44:10 CET 2012


On Mon, Dec 3, 2012 at 8:39 AM, Verde Denim <tdldev at gmail.com> wrote:
>         again = input('Roll again? (y = yes): ')
>
> Roll again? (y = yes): y
> Traceback (most recent call last):
>   File "dice_roll.py", line 17, in <module>
>     main()
>   File "dice_roll.py", line 15, in main
>     again = input('Roll again? (y = yes): ')
>   File "<string>", line 1, in <module>
> NameError: name 'y' is not defined
>
> This same loop structure appears in many places in this book "Starting
> out with Python, 2nd ed, Tony Gaddis), and they all yield the same
> error. Is there something I'm missing here?
>
> Thanks for the input...

The loop isn't the problem, your input() function is. In Python 2,
input() did the strange thing of evaluating what you typed; to simply
ask for a line and return it as a string, use raw_input(). As of
Python 3, the input() function does what raw_input() used to do, which
is what you want here.

You may be able to fix the problem by simply changing the function
name, but if the book is assuming Python 3, you will probably want to
switch to the newer interpreter. Also, the newer Pythons have a large
number of improvements in other areas, so it's well worth switching
anyway.

ChrisA



More information about the Python-list mailing list