6.4 For Loop Flashcards
What does the “For loop” do?
It executes a block of code repeatedly until the condition in the for statement is no longer valid.
What is an iterable?
It refers to anything that can be looped over, such as a string, list, tuple or dictionary.
What is the syntax for “For loop” usage in iterable?
for a in iterable:
print(a)
Write the script showing the “for loop” usage
flowers=[“Roses”,”lilies”,”daisies”,”Mandevila”]
for myFavourites in flowers:
print(myFavourites)
How can you display the index of the items in the list?
using the enumerate() function
What is the syntax of the enumerate () function?
for index, myFavourites in enumerate(flowers):
print(index,myFavourites)
Write the script for printing index numbers with for loop
for index, myFavourites in enumerate(flowers):
print(index,myFavourites)
Write the script for using the “for loop” to run it through the dictionary.
userAge={“Peter”:5,”John”:7}
for i in userAge:
print(i)
Write the script for using the “For loop” to get both the dictionary key and the data
userAge={“Peter”:5,”John”:7}
for i in userAge:
print(“Name=%s,Age=%d”%(i,age[i]))
first time the loop runs, it assigns the value Peter to i and age [i}] refers to the value assigned to Peter i.e. 5
What is an items method?
It is a built-in method. It returns each of the dictionary’s key-data pairas a tuple.
Write a script using “for loop” and items() method.
age={“Peter”:5,”John”:7}
for i,j in age.items():
print(“Name=%s,Age=%d”%(i,j))
Write the script for using the ‘for loop’ through a string
message = ‘Hello’
for i in message:
print(i)
How can you loop through a sequence of numbers?
by using built-in range() function
What is the syntax for the range() function and some important points to remember about it?
range(start,end,step)
Important points:
1) Start is always zero unless specified
2) End must be provided but isn’t included in the result
3) If step isn’t given, a list of consecutive numbers will be generated
What will range(5) yield?
0,1,2,3,4