Loops Flashcards
(26 cards)
What is a loop in Python?
A loop is a programming construct that repeats a block of code multiple times.
True or False: A loop can execute zero times.
True
What are the two main types of loops in Python?
The two main types of loops are ‘for’ loops and ‘while’ loops.
Fill in the blank: A ‘for’ loop in Python is typically used to iterate over _____ or _____ objects.
sequences, iterable
What keyword is used to terminate a loop early in Python?
break
What keyword can be used to skip the current iteration of a loop?
continue
Write a simple ‘for’ loop that prints numbers 1 to 5.
for i in range(1, 6): print(i)
True or False: A ‘while’ loop continues to execute as long as its condition is True.
True
What is the output of the following code: ‘for i in range(3): print(i)’?
0, 1, 2
What is the purpose of the ‘else’ clause in a loop?
The ‘else’ clause executes after the loop completes normally, not when it is terminated by ‘break’.
How do you create an infinite loop in Python?
By using ‘while True:’
Fill in the blank: The ‘range()’ function generates a sequence of _____ in Python.
numbers
What is the output of ‘for i in range(2, 10, 2): print(i)’?
2, 4, 6, 8
True or False: You can nest loops inside another loop in Python.
True
What does the ‘enumerate()’ function do in a for loop?
It adds a counter to an iterable and returns it as an enumerate object.
What will be the output of the following code: ‘for i in range(5): print(i * 2)’?
0, 2, 4, 6, 8
What is the syntax to define a ‘while’ loop?
‘while condition: do_something()’
Fill in the blank: The statement ‘break’ is used to _____ a loop.
exit
What is the difference between ‘break’ and ‘continue’?
‘break’ exits the loop entirely, while ‘continue’ skips to the next iteration.
True or False: Loops can only iterate over lists.
False
What happens if the condition of a ‘while’ loop is initially False?
The loop body will not execute at all.
Write a ‘while’ loop that counts from 1 to 5.
i = 1; while i <= 5: print(i); i += 1
What is a common use case for loops in programming?
To iterate over collections and perform operations on each element.
Fill in the blank: The ‘for’ loop can iterate over a _____, _____, or _____ in Python.
list, tuple, string