0
0
Pythonprogramming~5 mins

Length and iteration methods in Python - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the len() function do in Python?
The len() function returns the number of items in an object like a list, string, tuple, or dictionary.
Click to reveal answer
beginner
How can you loop through each item in a list named fruits?
Use a for loop: <br>for fruit in fruits:<br>   print(fruit) This goes through each item one by one.
Click to reveal answer
intermediate
What is the difference between for and while loops?
for loops run a set number of times over a sequence. while loops run as long as a condition is true.
Click to reveal answer
beginner
How do you find the length of a string name = 'Alice'?
Use len(name). It will return 5 because 'Alice' has 5 characters.
Click to reveal answer
intermediate
What happens if you try to use len() on an integer like len(5)?
You get a TypeError because integers don’t have a length. len() works only on collections like strings, lists, or tuples.
Click to reveal answer
What does len([1, 2, 3, 4]) return?
A4
B3
C1
DError
Which loop is best to use when you know exactly how many times to repeat?
Awhile loop
Btry-except block
Cif statement
Dfor loop
What will this code print?<br>for i in range(3):<br>   print(i)
A1 2 3
B0 1 2
C3 2 1
DError
What does len('hello') return?
A6
B4
C5
DError
Which of these can you use len() on?
AList
BInteger
CFloat
DBoolean
Explain how to find the length of a list and how to loop through its items.
Think about counting items and visiting each one.
You got /4 concepts.
    Describe the difference between a for loop and a while loop with examples.
    One repeats over a sequence, the other repeats while a condition is true.
    You got /3 concepts.