Table of Contents
Simple Control and Loops in Python
Variables ‘remember’ the value of something, and can be changed by the program. (Aside: there is a specific type of variable that cannot be changed, which are know as constants or constant variables).
For example in the following code we remember
hello world and print
the variable, which prints what we ‘remembered’.
hello = 'hello world' print(hello)
When coding, sometimes you may want to use the same few lines of code multiple times within your script. Alternatively, you may want to have the same few lines of code run every time a certain event occurs, e.g. when a specific key is pressed, or a particular phrase is typed. For tasks like this, you might want to consider using a function.
Functions are named blocks of code that perform a defined task. Just about the simplest function you can create in Python looks like this:
def hello(): print('Hello World!')
You tell Python that you’re creating a new function by using the
keyword, followed by the name of the function. In this case it is
hello. The parentheses after the function name are important.
The colon at the end of the line indicates that the code inside the function will be indented on the next line, just like in a
while loop or an
You can call a function by typing its name with the parentheses included. So to run the example function, you would type
*[call]: run the lines of code within the function
Here is the complete program:
def hello(): print('Hello World!') hello()
While loops (boolean)
You may recall the while loop from Module 1 which blinked the LED forever. Here is a more complete explanation:
The purpose of a while loop is to repeat code over and over while a condition is
True. This is why while loops are sometimes referred to as condition-controlled loops.
In this example, the condition is a boolean variable (which is a
variable that is either
True or `
False) we gave the name
keep_looping. Its value is set as
True at the top. The value can
False, which will make the condition of the while loop
False. When this happens, the loop stops running.
keep_looping = True while keep_looping: print("I am in a loop") command = input("Shall I keep looping?") if command == "no": keep_looping = False
This kind of loop is useful in situations where you want to repeat code until a specific event happens. For example, you may want a program to continue running until someone types something to tell it to quit.