473,397 Members | 2,033 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,397 software developers and data experts.

problems with looping, i suppose

Here's an exercise I was doing to guess a number from 1-100. Just for
fun (ha ha) I decided to add some error checking too, and now when I run
it, the DOS prompt flashes real quick and disappears. At first, I had
just the top try/except block and not the second one, and that worked
(as far as it would work), but after adding the second try/except, it
has this problem. I'm sure it has something to do with the looping and
the breaks/continues.

I'd appreciate any help on this, and also any suggestions for programs
that let you step through code to debug it (I'm used to Visual Studio).
I have SPE installed at home, but not here at work so I can't try it
right now. I assume it has a debugger.

Thanks.
Mar 27 '06 #1
14 1457
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()
Mar 27 '06 #2
John Salerno wrote:
Here's an exercise I was doing to guess a number from 1-100.


Here's another question that is related:

while True:
year = raw_input('Enter year (or other character to quit): ')

try:
year = int(year)
except NameError:
break

if (year % 4 == 0) and (year % 100 != 0 or year % 400 == 0):
print year, 'is a leap year.\n'
else:
print year, 'is not a leap year.\n'

raw_input()

This works as expected, except that if you enter any character other
than a number, the program just quits. Why doesn't it still execute the
raw_input function and pause? I think this is what is happening in the
other exercise too, but I don't know why. If you break out of the loop,
should it still pause at raw_input?
Mar 27 '06 #3
Just barely looked the code answer:
check you scope on the second try block.

if that doesn't work...
I'll read it for real :)

Try PyDev plugin with eclipse - it's served me fairly well, but I did
come from Java - so I'm an eclipse fan already.

Mar 27 '06 #4
ak*********@gmail.com wrote:
Just barely looked the code answer:
check you scope on the second try block.

if that doesn't work...
I'll read it for real :)

Try PyDev plugin with eclipse - it's served me fairly well, but I did
come from Java - so I'm an eclipse fan already.


I think it has to do with the exception I'm using. For the leap year
program, it should be ValueError. For the other one, its' a combination
of that and the input function.
Mar 27 '06 #5
John Salerno wrote:
I think it has to do with the exception I'm using. For the leap year
program, it should be ValueError. For the other one, its' a combination
of that and the input function.


Hmm, turns out something was wrong with the indentation of the second
while loop! Even though it looked correct, it created problems when I
opened it in IDLE, so I just unindented the whole thing and reindented
it manually, and now it works.
Mar 27 '06 #6
Ok I felt a little bad for my quick answer, these just seem like
homework problems.

first problem - it's scope. (there are two scope errors in the sample)
white space is meaningful. get consistent with tabs or spaces, or
choose an editor that replaces tab press with space. It'll make life a
lot easier. And make copy and paste from the group easier for people
trying to help :)

Second problem (leap year) , you are catching the wrong kind of
exception in that problem, so it's bubbling out as an unhandled
exception. Use IDLE as a starting point, it's not much - but it would
quickly expose these kinds of proboems.
Run your code using idle or the interactive and you will see what is
going on.

As a side issue. On the second problem - you did say you just want to
quit in the event of non numeric input, so it's WAD. But the
underlying exception generated is not a NameError. Try catching any
error and printing it.

Mar 27 '06 #7
Ha, you found it all before I could fire it up.
The whitespace thing is very odd, and it took about a month before I
was comfortable using it for scope.

On the bright side, scope errors are a lot easier to find than you
might think, once you get used to looking at py code.

I thought, if your in the mood to pay for software, and on windows -
wing IDE is used by many of my wrkmates. IT looks like garbage on
linux (at least to my eyes) so I stick with eclipse, but Wing has a lot
of fans.

Mar 27 '06 #8
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()


Mar 27 '06 #9
Gary wrote:
0 Alignment problem with the "except" clause.
As I'm sure you've already discovered, Python is "whitespace
sensitive".


Wow, I'm really confused. As it turns out, whitespace *was* the problem,
but it looks no different now (as it works) than it did then (when it
didn't work). I don't know if my copy/paste worked properly for you
guys, but as I see it in my newsreader, everything looks right.
try/excepts are indented inside whiles, if/else are indented within
tries, and if lines are indented under the ifs.

I just don't see where the problem was. Maybe it was a result of my text
editor doing whatever it does to auto-indent, because originally I
didn't have the while loop, so after adding it I had to indent the other
stuff. But it never *looked* wrong, so I don't get it...

Does what I originally pasted in my message look incorrect? To me, it
all seems indented properly.
Mar 27 '06 #10
John Salerno wrote:
Here's another question that is related:

while True:
year = raw_input('Enter year (or other character to quit): ')
try:
year = int(year)
except NameError:
break
...
raw_input()

This works as expected, except that if you enter any character other
than a number, the program just quits. Why doesn't it still execute the
raw_input function and pause?


Here's a clue:
try:
try:
x = int('abc')
except FloatingPointError:
print 'never reached'
print 'This is not reached either'
except ValueError:
print 'proper exception'
raw_input('Pause and reflect:')

--Scott David Daniels
sc***********@acm.org
Mar 27 '06 #11
ak*********@gmail.com wrote:
Ok I felt a little bad for my quick answer, these just seem like
homework problems.


NP. I appreciate your help. These are just little exercises I found
online, just to give me a reason to use Python. :)
Mar 27 '06 #12
John Salerno <jo******@NOSPAMgmail.com> wrote:
Does what I originally pasted in my message look incorrect? To me, it
all seems indented properly.


Yes. Somewhere or other you've got your tabstop set to 4, and python
treats literal tabs as being of equivalent indent to 8 spaces. As
does my newsreader, so the problem was obvious:

while True:
tries += 1
^ This was a tab (my cut&paste has turned it back into spaces)
try:
^ This was a tab too.
if guess == number:
^^^^^^^^ This was eight spaces even before I cut&pasted.

--
\S -- si***@chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/
___ | "Frankly I have no feelings towards penguins one way or the other"
\X/ | -- Arthur C. Clarke
her nu becomež se bera eadward ofdun hlęddre heafdes bęce bump bump bump
Mar 28 '06 #13
Sion Arrowsmith wrote:
John Salerno <jo******@NOSPAMgmail.com> wrote:
Does what I originally pasted in my message look incorrect? To me, it
all seems indented properly.


Yes. Somewhere or other you've got your tabstop set to 4, and python
treats literal tabs as being of equivalent indent to 8 spaces. As
does my newsreader, so the problem was obvious:

while True:
tries += 1
^ This was a tab (my cut&paste has turned it back into spaces)
try:
^ This was a tab too.
if guess == number:
^^^^^^^^ This was eight spaces even before I cut&pasted.


Ah, that makes sense now! Thanks!
Mar 28 '06 #14
In article <Dv******************@news.tufts.edu>,
John Salerno <jo******@NOSPAMgmail.com> wrote:
... and now when I run
it, the DOS prompt flashes real quick and disappears.


Does your DOS OS not have the equivalent of xterm, or KDE Konsole, or
such? Something that lets you execute more than just one command, so you
can see the results of the previous command before the window disappears?
Apr 5 '06 #15

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
by: kaptain kernel | last post by:
i've got a while loop thats iterating through a text file and pumping the contents into a database. the file is quite large (over 150mb). the looping causes my CPU load to race up to 100 per...
3
by: Carlos Ribeiro | last post by:
As a side track of my latest investigations, I began to rely heavily on generators for some stuff where I would previsouly use a more conventional approach. Whenever I need to process a list, I'm...
10
by: Michael Hill | last post by:
I am still having problems with the dom. blah ... I have a table like: <tbody id="list"> <tr> <td>a</td> <td>b</td> <td>c</td> <td>d</td> </tr> </tbody>
3
by: frozenee | last post by:
I've noticed that the listings in help don't take you to correct topic. anyone else have this problem? Is there a fix?
2
by: pj | last post by:
Code below is on continuous form. Depending on a Y/N field value the colours should change on the form. Although the looping appears to work it sets all controls in each record to the first...
5
by: masood.iqbal | last post by:
My simplistic mind tells me that having local variables within looping constructs is a bad idea. The reason is that these variables are created during the beginning of an iteration and deleted at...
13
by: Joseph Garvin | last post by:
When I first came to Python I did a lot of C style loops like this: for i in range(len(myarray)): print myarray Obviously the more pythonic way is: for i in my array: print i
7
by: uarana | last post by:
Hi All, Can someone please help me with the following code. I've been working on this for the past 2 days and i can't seem to get past this obstacle. Problem: The code opens up the Table...
2
by: hayz | last post by:
Flash sound file looping problems hello there I'm definitely a newb so please bare some patience. I have a flash sound file on the index page of a site i'm working on. First off i need the...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.