loops

V

Verde Denim

I'm just getting into py coding, and have come across an oddity in a py
book - while loops that don't work as expected...

import random

MIN = 1
MAX = 6

def main():
again = 'y'

while again == 'y':
print('Rolling...')
print('Values are: ')
print(random.randint(MIN, MAX))
print(random.randint(MIN, MAX))

again = input('Roll again? (y = yes): ')

main()

Produces -
python dice_roll.py
Rolling...
Values are:
5
4
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...
 
S

Steven D'Aprano

I'm just getting into py coding, and have come across an oddity in a py
book - while loops that don't work as expected...

This error has nothing to do with the while loop. Read the error message
that Python gives you:
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


In Python 2, there is a serious design flaw with the "input" function,
fortunately corrected in Python 3. The flaw is that input automatically
evaluates whatever you type as Python code. So when you type "y", the
input function tries to evaluate the name y, which doesn't exist.

No while loop required:

py> again = input('Roll again? (y = yes): ')
Roll again? (y = yes): y
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'y' is not defined


The solution is either to use Python 3, where this is no longer an issue,
or to replace "input" with "raw_input":

py> again = raw_input('Roll again? (y = yes): ')
Roll again? (y = yes): y
py> again
'y'



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...

I see what you did there... *wink*
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top