I have a very basic question about loops. I’m trying to get into programming and am currently reading the book “Learn Python The Hard Way”, and got stuck on study drill number 5 on ex 33:
http://learnpythonthehardway.org/book/ex33.html
This is what my code looks like:
i = 0
numbers = []
def main(i, numbers):
userloop = int(raw_input("Type in max value for the loop > "))
while i < userloop:
print "At the top i is %d" % i
numbers.append(i)
userincrease = int(raw_input("Increase > "))
i += userincrease
print "Numbers now: ", numbers
print "At the bottom i is %d" % i
print "The numbers: "
print numbers
for num in numbers:
print num
main(i, numbers)
The thing is that i want to use a for loop instead of the while loop. Is that even possible and then, how do I do it? I’ve tried simply exchanging
while i < userloop:
with
for i in range(userloop)
But then, the i value kinda resets every time it reaches the “top” of the loop.
Since I’m very much new to this, please don’t be too mean if i missed something obvious.
By the way, does anyone know whether this book is any good to begin with or am I wasting my time?
A
forloop in python loops over a series of values provided by the expression afterin. In Python we use the termiterablefor anything that can produce such a series. That can be arange(), but it could be anything that can be iterated over (looped over). The loop variableireceives the next value on each iteration, whatever value there was before.Thus, the following is legal:
but the
i = 'spam'essentially does nothing.You’d have to approach it differently; skip those values instead:
Every time you ask the user for an increase, we update the value
print_atto be the sum of the current value ofiplus that increase, and then proceed to ignore most of the loop body untilicatches up withprint_at.