Changes

Jump to navigation Jump to search

Workshop: Introduction to programming (with Python)

19 bytes added, 22:15, 12 September 2019
Loops
==Loops==
One of the most important concepts in procedural programming is the loop. Like the name suggests, a loop simply iterates through some selected lines of code a certain amount of times. In Python there are a few different types of loopsyou can choose from, they are:
#'''While Loop''' - Like the name suggests, a while loop repeats a block of code while a certain expression is true. This kind of loop is useful when we don't know how many times a loop will actually execute at runtime. The While Loop is composed of two parts; the loop statement and the code block to repeat (indented). The syntax looks like this:[[File:While Loop Example.png|thumb|An example of a while loop]]'''while ('''statement'''):''' '''''*code to repeat*'''''<br />The while loop will loop over the code block until the statement in parentheses equates to false. The statement can be an algebraic equation or variable. (ex: (n+1)/4 == 1) <br />[[File:Example For loop.png|thumb|2 examples of for loops that yield the same result. ]]
##To iterate over a list - Will run the code block once for each element in a list. You can reference the element data during each iteration by putting an element name after "for". Example of this syntax can be seen below: '''for''' element '''in''' list''':''' '''''*code to repeat*''''' <br />
##To iterate a certain number of times - Use Python's range function to repeat the code block a certain number of times. The syntax for range is: range (start, stop[, step]). Just like in the other type of for loop, you can reference each element of the range function but naming it. The syntax for this for loop goes: '''for ('''element '''in range('''start, stop[, step]''')):''' '''''*code to repeat*''''' <br />
#'''Nested Loops''' - Loops can be nested inside of each other! For each iteration of the outer loop, the entire contents of the loop will be ran to completion (including other nested loops).
#'''Breaks and Continues''' - "Break" and "continue" are statements which can be placed inside of a loop to modify the loop for special cases. Break is used to break out of (or exit) a loop. Continue is used to stop the current iteration of the loop and start again from the beginning. [[File:Break Flowchart.jpg|frameless]][[File:Continue Flow Chart.jpg|frameless]]
118
edits

Navigation menu