For loops run a section of code a specific number of times. In Python, a for loop can be initialized with any iterable object. For loops can be initialized with:
for <var> in <interable>:
<code>
print('ENGR114')
print('ENGR114')
print('ENGR114')
ENGR114 ENGR114 ENGR114
for i in range(3):
print('ENGR114')
ENGR114 ENGR114 ENGR114
for i in range(3):
print(i)
0 1 2
# range(start,stop,step)
# print the numbers 10 - 16, only even
for i in range(10,18,2):
print(i)
10 12 14 16
# create a list of num,bers 10 - 16, only even using a for loop
lst = [] # create an empty list
for i in range(10,18,2):
lst.append(i)
print(lst)
[10, 12, 14, 16]
# use a for loop to print out all of the values from a list
lst = [10, 12, 14, 16]
for i in lst:
print(i)
10 12 14 16
# add the number 2 to each value in a list
n_lst=[] # create an empy list to hold the numbers that have 2 added to them
lst = [10, 12, 14, 16] # create a list of numbers that 2 will be added to
for i in lst:
n_lst.append(i+2)
print(n_lst)
[12, 14, 16, 18]
# place a space between the letters and numbers in ENGR114
course = 'ENGR114'
for character in course:
print(character + ' ', end='')
E N G R 1 1 4
# print out the character number (character index) and the character of a string
course = 'ENGR114'
for i,character in enumerate(course):
print(f'index:{i} character:{character}')
index:0 character:E index:1 character:N index:2 character:G index:3 character:R index:4 character:1 index:5 character:1 index:6 character:4
# print out the character number (character index) and the character of a string
lst = [10,12,14,16]
for i,num in enumerate(lst):
print(f'index:{i} number:{num}')
index:0 number:10 index:1 number:12 index:2 number:14 index:3 number:16