I’m trying to teach myself python right now, and I’m using exercises from “Learn Python The Hard Way” to do so.
Right now, I’m working on an exercise involving while loops, where I take a working while loop from a script, convert it to a function, and then call the function in another script. The only purpose of the final program is to add items to a list and then print the list as it goes.
My issue is that once I call the function, the embedded loop decides to continue infinitely.
I’ve analyzed my code (see below) a number of times, and can’t find anything overtly wrong.
def append_numbers(counter):
i = 0
numbers = []
while i < counter:
print "At the top i is %d" % i
numbers.append(i)
i += 1
print "Numbers now: ", numbers
print "At the bottom i is %d" % i
count = raw_input("Enter number of cycles: ")
print count
raw_input()
append_numbers(count)
I believe you want this.
Without converting the input to integer, you end up with a string in the
countvariable, i.e. if you enter1when the program asks for input, what goes into count is'1'.A comparison between string and integer turns out to be
False. So the condition inwhile i < counter:is alwaysFalsebecauseiis an integer whilecounteris a string in your program.In your program, you could have debugged this yourself if you had used
print repr(count)instead to check what the value incountvariable is. For your program, it would show'1'when you enter 1. With the fix I have suggested, it would show just1.