Python For Loops
In computer science, a for-loop (or simply for loop) is a control flow statement for specifying iteration, which allows code to be executed repeatedly. ... For-loops are typically used when the number of iterations is known before entering the loop.
Task:
- Copy the example below into python then.....
- See if you can work out what each line of code is doing.
- Add #comments to explain the code.
- Now see if you can create your own for loop to run through a list of your favourite songs.
#for loop example
#remember list positions start at 0!
animals=["cat","mouse","chimp","pig","dog","cow"]
for i in animals:
print("first animal index position:",animals.index(i))
print("first animal name:",i)
print("Finished")
Python While loops
In computer programming languages, a while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement.
Task:
- Copy the example below into python then.....
- See if you can work out what each line of code is doing.
- Add #comments to explain the code.
- Now see if you can create your own while loop to count down from 100 to 0.
- Print 'Blast off' when your count down reaches zero.
- Write import time at the top of your code and use time.sleep(1) to slow down your count.
#while loop example
count=0
while count <= 100:
print("Number:",count)
count+=1
print("End of count")
Next
Check out the python challenges pages to see more complex examples of loops.