How to use for loop in PythonPython for loop iterate over the sequences. It repeats the piece of code n number of times. Consider the following flowchart of for loop. FlowchartPython for loop can be used in two ways.
Using SequenceThe sequence is referred to as list, set, string, tuple, and dictionary in Python. We can extract the elements of the sequence using for loop. Below is the syntax for loop. Syntax: Let’s understand the following example. Example – 1 Output: 10 20 30 40 50 60 Example – 2 Output: J a v a T p o i n t Using the range() functionThe range function() generates the sequence of the numbers. For example, if we execute the range(5) and it will generate the 0 to 4. The syntax of the range() function is given below. Syntax: It accepts the three arguments.
Let’s understand the following example. Example – 1 Output: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 Example – 2 Traverse the List element using range() function Output: Hii Peter Hii Joseph Hii Ricky Hii Devansh Hii Kevin Explanation: The len() function returns the length of the list. The range() got the number of elements in the list and printed its elements. |
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/263617.html