John --
I looked at your exercise. As it appears in my browser, there appear
to be a couple of problems with the bottom "While" block.
0 Alignment problem with the "except" clause.
As I'm sure you've already discovered, Python is "whitespace
sensitive". If it looks like a block, it is; otherwise it isn't. The
"if" .. "elif" statements aren't "inside" ("to the right of") the
"try". Python will, I believe, interpret this as "try" with no
matching "except" or "finally" and will toss this as a syntax error --
and thus, I suspect, the flashing screen.
o logic error.
if "guess" == "number", program as written will print "congrats"
forever.
Assuming my "cut, copy, paste" works ok, try this: (hmm, the print
"congrats" line looks like it's broken into two lines when I preview
this. Please ignore -- it should all be on one line):
import random
number = random.choice(range(1, 100))
tries = 0
while True:
try:
guess = input('Enter a number between 1 and 100: ')
break
except NameError:
print 'Invalid number\n'
continue
while True:
tries += 1
try:
if guess < number:
guess = input('Too low. Try again: ')
elif guess > number:
guess = input('Too high. Try again: ')
else:
print 'Congratulations! You got it in
',tries,'guess(es).'
break
except NameError:
print 'Invalid number\n'
continue
raw_input()
I altered the "if" a bit -- just my own preference that an "if" always
have a matching "else".
If you're looking for something with an editor and a debugger -- try
"IDLE". If your installation is like mine, it's included. Look in
your Python directory under Lib/idelib for file "idle.pyw". (NB: At
the moment, I'm running a WinXP box and that's where it is here. My
poor old mind can't dredge up whether it's in the same relative place
in say, a Linux installation.) "IDLE" isn't perfect but it'll get you
started. (Also, FWIW, if you run this under "IDLE", you can omit the
trailing "raw_input()")
hope this helps.
gary
John Salerno wrote:
John Salerno wrote: Here's an exercise I was doing
This might help:
import random
number = random.choice(range(1, 100))
tries = 0
while True:
try:
guess = input('Enter a number between 1 and 100: ')
break
except NameError:
print 'Invalid number\n'
continue
while True:
tries += 1
try:
if guess == number:
print 'Congratulations! You got it in', tries, 'guess(es).'
break
elif guess < number:
guess = input('Too low. Try again: ')
elif guess > number:
guess = input('Too high. Try again: ')
except NameError:
print 'Invalid number\n'
continue
raw_input()