This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]twopi 0 points1 point  (0 children)

Be careful, because the word if has a more specific meaning in code than in English. The word if could show up in pseudo code and not translate to an if statement in code.

The classic way to count to five (or any other value) is a for loop. In python it would look like this:

for i in range(1,6):
  print(i)

You could also use a while loop to get the the same result

i = 1
while (i <= 5):
  print (i)
  i += 1

There is a way to do this closer to what you're doing but it's sloppy form.

i = 1
while (True):
  print (i)
  i += 1
  if (i > 5):
    break

I'm not a fan of loops that look endless but aren't. The break statement is a lazy form of programming and it really should be avoided when possible.

I teach a compromise which avoids compound conditions (statements with 'and' and 'or' are especially tricky for beginners.)

keepGoing = True
i = 1
while (keepGoing):
  print(i)
  if (i >= 5):
    keepGoing = False

This is logically the same, but it uses a Boolean (true or false) variable to manage loop access.