Variable loops

Fixed numbers, like the ones we've used in the range() function, are also called constants. If you use constants in the range() function of a for loop, the loop will run the same number of times whenever the program is run. In that case, we say the number of loops is hard-coded, because it's defined in your code and it never changes. That's not always what we want.

Sometimes we want the number of loops to be determined by the user, or by another part of the program. For that, we need a variable.

For example, let's say you were making a space-shooter game. You'd have to keep redrawing the screen as aliens get wiped out. You'd have some sort of counter to keep track of how many aliens were left, and whenever the screen was updated, you'd need to loop through the remaining aliens and draw their images on the screen. The number of aliens would change every time the player wiped out another one.

Because we haven't learned how to draw aliens on the screen yet, here's a simple example program that uses a variable loop: numStars = int(raw_input ("How many stars do you want? "))

Because we haven't learned how to draw aliens on the screen yet, here's a simple example program that uses a variable loop: numStars = int(raw_input ("How many stars do you want? "))

>>>----------=

=========== RESTART ======================

>>>

How many stars

do you want? 5

* * * *

The program asked the user how many stars he wanted, and then it used a variable loop to print that many. Well, almost! We asked for five stars and only got four! Oops, we forgot that the for loop stops one short of the second number in the range. So we need to add 1 to the user s lnput. numStars = int(raw_input ("How many stars do you want? "))

for i in range(1, numStars + 1): Adds 1, so if he asks for 5

Another way to do the same thing is to start the loop counting at 0, instead of 1. (We mentioned that back in chapter 8.) This is very common in programming, and we'll see why in the next chapter. Here's how that would look:

numStars = int(raw_input ("How many stars do you want? ")) for i in range(0, numStars): print '*',

>>> ====================== RESTART =====================

Was this article helpful?

0 0
100 Bowling Tips

100 Bowling Tips

Playing bowling with your friends can help you decide if it is indeed the hobby that you want to invest your time on today. Aside from that, it can help you get a better feel of the sport. More importantly, when you play with your friends, it would become a more fun activity, which you can look forward to each week.

Get My Free Ebook


Post a comment