This tutorial covers various ways to execute loops in python. Loops is an important concept of any programming language which performs iterations i.e. run specific code repeatedly until a certain condition is reached.
1. For Loop
Like R and C programming language, you can use for loop in Python. It is one of the most commonly used loop method to automate the repetitive tasks.
How for loop works?
Suppose you are asked to print sequence of numbers from 1 to 9, increment by 2.
for i in range(1,10,2):Output
print(i)
1
3
5
7
9
range(1,10,2)
means starts from 1 and ends with 9 (excluding 10), increment by 2.Iteration over list
This section covers how to run for in loop on a list.
mylist = [30,21,33,42,53,64,71,86,97,10]Output
for i in mylist:
print(i)
30
21
33
42
53
64
71
86
97
10
Suppose you need to select every 3rd value of list.
for i in mylist[::3]:Output
print(i)
30
42
71
10
mylist[::3]
is equivalent to mylist[0::3] which follows this syntax style list[start:stop:step]
Python Loop Explained with Examples |
Example 1 : Create a new
from Planet SciPy
read more
No comments:
Post a Comment