Navigation

How do you use loops in Python?

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.
How do you use loops in Python?


So, there are various contexts where for loops can be used.
  1. You wish to iterate over a list consisting of elements.
  1. L=[1, 2, 3, 4, 5]
  2. for i in L:
  3. print(i, end=" ")
Output would be something
  1. 1 2 3 4 5
2. You know the number of times some operation needs to be performed. Suppose, printing each of the iterations.
  1. for i in range(3):
  2. print(i)
This will give output
  1. 0
  2. 1
  3. 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.
  1. L=[1, 2, 3]
  2. for _ in range(len(L)):
  3. print("Hello World!")
Will give you output like
  1. Hello World!
  2. Hello World!
  3. 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
  1. D={'a': 2, 'b': 3, 'c': 10, 'd': 15}
  2.  
  3. for key, value in D.items():
  4. print(key, value)
  5. for key in D.keys():
  6. print(key)
  7. for values in D.values():
  8. print(values)
Try and see the output ;) Name is sufficient to predict though.


>> Also you can read: How should you start learning Python?
مشاركة

أضف تعليق:

0 comments: