Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
AQA Computer Science :: Cheat Sheet Programming Technique :: Loops Technique: Loops “Looping may be referred to as repetition or iteration. We can use loops in our programs for lots of different reasons. They help make code more efficient because they require less code to perform the same process.” Increasing Efficiency with Loops Here is some simple Python code for the numbers 1 to 10: print print print print print print print print print print 1 2 3 4 5 6 7 8 9 10 This takes a long time to write and it uses a lot of lines of code! To make this more efficient we can use a loop. Here is how we can make this more efficient using a for loop: For the time that x is between 0 and 10 Assigns 0 to the variable number x is just a temporary variable that we use for counting Computer Science @ Kingswinford Add 1 to whatever is stored in number Display the content of number AQA Computer Science :: Cheat Sheet Programming Technique :: Loops We use a “for loop” when we need to count the number of times a snippet of code will run. If we want something to repeat while a condition is true, we can use a while loop. We would use a while loop when we want to check if the condition is true before the snippet of code is run. Using the same example as above, we can create a while loop: Assigns 0 to the variable number Keep doing this while number is not equal to 10 Another type of loop is a repeat loop. A repeat loop will keep running until a condition becomes true. This means that the condition is checked at the end of the loop. You may see repeat until in some programming languages. Python doesn’t use repeat, you can use… while True: …as an alternative. AQA Pseudo Code This is how these loops look in AQA pseudo code: A While Loop WHILE myVar < 10 OUTPUT myVar myVar = myVar + 1 ENDWHILE A For Loop FOR x 1 to 10 OUTPUT i ENDFOR Computer Science @ Kingswinford AQA Computer Science :: Cheat Sheet Programming Technique :: Loops A Repeat…Until Loop REPEAT OUTPUT “Hello” UNTIL myVar = 3 Test Yourself Try creating a loop in Python that displays the 10 times table on the screen. HINT: You may not know this… If you need to display a variable within some text you can use this code below: name = “Becky” print "Hello %s, how are you today?" %(name) The %s symbol will be replaced with the variable mentioned at the end in the brackets. This piece of code would output as: Hello Becky, how are you today? Computer Science @ Kingswinford