Coding for Kids: Python: Learn to Code with 50 Awesome Games and Activities by Tacke Adrienne B

Coding for Kids: Python: Learn to Code with 50 Awesome Games and Activities by Tacke Adrienne B

Author:Tacke, Adrienne B. [Tacke, Adrienne B.]
Language: eng
Format: azw3
Publisher: Rockridge Press
Published: 2020-06-20T16:00:00+00:00


As we iterate through our loop, we ask the computer the same question: “Hey, if you add 2 to the next number in the numbers list, will the result be less than 20?” If it is, we finally get to the print() function and print that number. Again, we indent this code, as it is a new block that only runs after passing the first two levels of Boolean expressions.

numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]

i = 0

while(i < len(numbers)):

if (numbers[i] + 2) < 20:

print(numbers[i] + 2)

Finally, and probably the most important part of while loops, we have to add code to increment our iterator variable! Remember, we are the ones keeping track of how many loops we have repeated. We also know how important the iterator variable is, because we use it in our while loop’s Boolean expression and as our index in our if statement’s Boolean expression:

numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]

i = 0

while(i < len(numbers)):

if (numbers[i] + 2) < 20:

print(numbers[i] + 2)

i += 1

Notice how I put this code on the same indentation level as the if statement? Because there is no other code that needs to be repeated, and because we always want to keep count of how many times we have repeated our loop, we place the increment code (i += 1 ) here right before it starts the loop all over again.

Now, I said this was the most important part of while loops. Why? Try running the while loop without the code to increment our iterator variable. What happens ?

You’ve just encountered your first infinite loop ! Your shell will just keep printing the same number over and over again forever:



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.