So, there are various contexts where for loops can be used.
- You wish to iterate over a list consisting of elements.
- L=[1, 2, 3, 4, 5]
- for i in L:
- print(i, end=" ")
Output would be something
- 1 2 3 4 5
2. You know the number of times some operation needs to be performed. Suppose, printing each of the iterations.
- for i in range(3):
- print(i)
This will give output
- 0
- 1
- 2
3) You have a list. But, you don’t wish to access elements of the list. But, your purpose is to just perform total iterations equal to the length of list.
- L=[1, 2, 3]
- for _ in range(len(L)):
- print("Hello World!")
Will give you output like
- Hello World!
- Hello World!
- Hello World!
Now, in point 3 I have used a “_” instead of a variable. So, this can be used when you don’t have to use the variable anymore. You just wish to loop over.
I hope it makes sense! :)
EDIT
4. Using for loop for iterating over a dictionary
- D={'a': 2, 'b': 3, 'c': 10, 'd': 15}
- for key, value in D.items():
- print(key, value)
- for key in D.keys():
- print(key)
- for values in D.values():
- print(values)
Try and see the output ;) Name is sufficient to predict though.
أضف تعليق:
0 comments: