Introduction to Programming - 3 Flashcards
What are loops in Python?
allow you to execute a block of code repeatedly based on a condition
Loop is a general term for a programming construct which allows us to
do things many times
Why is loops good practically? - (2)
might be making lots of stimuli for an experiment or analyzing lots of different datasets.
..or that thing you just did where you printed out the same ‘count’ statement more or less six times
2 types of loops in Python - (2)
- For loop
- While loop
What is For loop?
For loops in Python are used to iterate over a sequence (such as a list, tuple, string, or range) and execute the same block of code for each element in the sequence
Loop you will commonly encounter is a
for loop
General structure of for loop
What does this general structure mean? - (4)
What this means is that LOOPVARIABLE (which can be named whatever you want) will be set to the first item in LIST_OF_THINGS_TO_ITERATE_OVER. The code which is indented (just a comment in this case) will then run.
Once all of the code which is indented has been run, the loop will go back to the top,
LOOPVARIABLE will be set to the second item in LIST_OF_THINGS_TO_ITERATE_OVER and all of the indented code will run again.
This will repeat for each element in LIST_OF_THINGS_TO_ITERATE_OVER.
Example of for loop using structure
What will be the output?
Hello!
Hello 1
Hello!
Hello 2
Hello!
Hello 3
Hello!
Hello 4
Hello!
Hello 5
Hello!
Hello 6
Hello!
Hello 7
Hello!
Hello 8
Hello!
Hello 9
Hello!
Hello 10
In the for loop
The for keyword…
It is followed by…
The keyword in…
Finaly there is :
The code inside te for loop is … - (6)
The for keyword starts the loop.
It is followed by the variable which is created to run the loop.
The keyword in is then used, followed by the expression which gives the list of items over which to iterate.
As we will see later, this is not always a list or tuple - there are other possibilities.
Finally, there is a colon : which shows that the loop is starting.
The code inside the loop is indented. In other words it is shifted to the right - like this line
In loops, Python works out where your loop ends by - (2)
looking at the indentation of the text – i.e. it uses spaces. At first this can be confusing but it becomes second nature after a while.
To ident code inside loop you can either use
4 spaces or tab
Create a for loop that produces 1-10
Iterating over a list refers to the process of
accessing each element in the list one by one in a sequential manner.
The simplest form of a loop involves
setting up a list and then performing some code for each entry in the list.
The simplest form of a loop involves setting up a list and then performing some code for each entry in the list. For example, code below shows..
we print each element in a list followed by itself squared