[Tutor] Request for help with code
Cameron Simpson
cs at cskk.id.au
Tue Nov 6 18:50:57 EST 2018
On 06Nov2018 15:50, Joseph Gulizia <joseph.gulizia at gmail.com wrote:
>I'm using the bookazine "The Python Book" First Edition on pages 13-14 it
>gives the code (listed further below).
>
>It asks for user to state a given number of integers (for example 4)...then
>user enters integers. It doesn't stop seeking input after the number
>requested thereby creating an infinite loop.
It is vital to preserve the indenting when pasting in code. Indent level
is critical to Python's control flow. I'm going to look anyway, but
without the indenting I may misinterpret the logic.
[...snip...]
# creates a collection (list) called ints
ints=list()
# keeps track of number of intergers
count=0
# Keep asking for an interger until we have the required number
while count<target_int:
new_int=raw_input("Please enter interger{0}:".format(count+1))
isint=False
try:
new_int=int(new_int)
except:
print("You must enter an interger")
# Only carry on if we have an interger. If not, we'll loop again
# Notice below I use == which is different from =. The single equals sign
is an
# assignment operator whereas the double equals sign is a comparison
operator. I would
# call it a married eguals sign....but whenever single is mentioned I have
to mention marriage.
if isint==True:
# Add the interger to the collection
ints.append(new_int)
# Increment the count by 1
count+=1
[...snip...]
Here is where I imagine the problem may lie, but it depends critically
on the indenting. Your while loop should look something like this:
while count < target_int:
... read the int ...
if isint == True:
ints.append(new_int)
count += 1
However, consider this:
while count < target_int:
... read the int ...
if isint == True:
ints.append(new_int)
count += 1
All I have changed is the indent. This means that the increment of count
is _outside_ the while loop body. Which means that it never happens
inside the loop, and therefore count never increases, and therefore the
end of loop condition is never reached. Infinite loop.
The other likelihood is that isint somehow does not become true. If that
is the case, the count also never increments.
I suggest that you put several print() statements into the loop at
strategic points (note the indenting - the same as the block they're
embedded in):
while count < target_int:
print("loop: count =", count, "target_int =", target_int)
... read the int ...
if isint == True:
print("isint is true!")
ints.append(new_int)
count += 1
print("count =>", count)
You should see that the expected code is actually reached and run, and
if it isn't, the corresponding print()s do not happen.
Cheers,
Cameron Simpson <cs at cskk.id.au>
More information about the Tutor
mailing list