π for
Loops
December 02, 2016
β Loop
Code that repeats for a certain number of times, or while something is true.
β for
Loop
Code that repeats for a certain number of times.
numbers = [1,2,3]
for x in numbers:
print "This is number" + str(x)
This is number 1
This is number 2
This is number 3
Lists & Loops
What will print?
numbers = [2, 4, 6, 8]
for x in numbers:
x = x/2
print("This loop will repeat " + str(x) + " times")
Practice
Be sure to include comments as you code, explaining 1) what are you trying to do 2) where did you get stuck and 3) how you got unstuck.
Looping through lists
numbers = [2, 4, 244, 24, 13, 44, 53]
- Write a for loop to print out each number squared
- Write a for loop to print out three times the numbers in the list
- Write a for loop to print out βMy new favorite number is β and then each number
Conditionally Looping
There are multiple ways to solve these problems. Talk to you neighbors. Look at my starter code. Comment your work!
π Write a for loop to print only the odd numbers from this list
list = [3,4,7,13,54,32,653,256,1,41,65,83,92,31]
π Write code that prints out only the factors of a number input
number = input("What number would you like the factors of? \n")
π Countdown Write code that counts down from any number
n= input("What number would you like me to start at? \n")