Arguably, the if, for and while statement are the most important programming language construct. These programming construct are also available in Python programming language. The if statement is used for decision making, the for and while loop are used to do repetitive work. In this example we show how to use the if statement, the for statement and the while statement.

As an example of if statement consider that we have two alternative choice to select one path depending upon the result of random number. If we generate a random number between 0 and 1 and the outcome is less or equal to 0.5 then we select the first path otherwise we select the second path.

import random

p = random.random()

if 0 <= p <= 0.5:

print("choose first path")

else:

print("choose second path")

choose second path

The result is choose second path.

But what if there are more than two alternatives? In this case we have to use the elsif statement. This is shown below.

if 0 <= 0 <= 0.25:

print("choose 1st path")

elif 0.25 < p <= 0.5:

print("choose 2nd path")

elif 0.5 < p <= 0.75:

print("choose 3rd path")

else:

print("choose 4th path")

choose 1st path

The next important structure in Ipython programming language is the for loop structure. For loops are used to do repetitive task. If you say want to print 1,2,3,4 and 5 you can use for loop in Ipython programing language as follows.

for k in [1,2,3,4,5]:

print(k)

1

2

3

4

5

In particular the range function is used with for loop in python programming language. Then range(start,stop,increment) function accepts the start, stop and the increment parameters. The following program code would do the same thing as above.

for k in range(1,6):

print(k)

1

2

3

4

5

Note that the increment value is optional and the default value is 1.

The following is thus the same as above,

for k in range(1,6,1):

print(k)

Note also that range starts with index 0 and not 1. So for example see the following.

for k in range(6):

print(k)

0

1

2

3

4

5

Application of python for loop is for example doing summation in mathematics. See the following formula.

We can implement this summation as follows.

N = 5

x = 0

for i in range(1, N+1):

x += 2*i

print x

See Calculating Summation using While Looop in Python programming language where the same equation is implemented using while loop.

Another useful function for for loop is the linspace(). This is like the matlab linspace function. We will show this function used in the while loop.

The last important structure of any programming language is the while() loop. A while loop is used to do execute one or multiple statements until a certain condition is satisfied. An example of while loop in Ipython programming language is as follows.

from numpy import linspace

v0 = 4.5 # Initial velocity

g = 9.81 # Acceleration of gravity

t = linspace(0, 1, 1000) # 1000 points in time interval

y = v0*t - 0.5*g*t**2 # Generate all heights

# Find where the ball hits y=0

i = 0

while y[i] >= 0:

i += 1

# Now, y[i-1]>0 and y[i]<0 so let’s take the middle point

# in time as the approximation for when the ball hits h=0

print "y=0 at", 0.5*(t[i-1] + t[i])

# We plot the path again just for comparison

import matplotlib.pyplot as plt

plt.plot(t, y)

plt.plot(t, 0*t, ’g--’)

plt.xlabel(’Time (s)’)

plt.ylabel(’Height (m)’)

plt.show()

See Download Programming for Computations for the book.

As an example of if statement consider that we have two alternative choice to select one path depending upon the result of random number. If we generate a random number between 0 and 1 and the outcome is less or equal to 0.5 then we select the first path otherwise we select the second path.

import random

p = random.random()

if 0 <= p <= 0.5:

print("choose first path")

else:

print("choose second path")

choose second path

The result is choose second path.

But what if there are more than two alternatives? In this case we have to use the elsif statement. This is shown below.

if 0 <= 0 <= 0.25:

print("choose 1st path")

elif 0.25 < p <= 0.5:

print("choose 2nd path")

elif 0.5 < p <= 0.75:

print("choose 3rd path")

else:

print("choose 4th path")

choose 1st path

The next important structure in Ipython programming language is the for loop structure. For loops are used to do repetitive task. If you say want to print 1,2,3,4 and 5 you can use for loop in Ipython programing language as follows.

for k in [1,2,3,4,5]:

print(k)

1

2

3

4

5

In particular the range function is used with for loop in python programming language. Then range(start,stop,increment) function accepts the start, stop and the increment parameters. The following program code would do the same thing as above.

for k in range(1,6):

print(k)

1

2

3

4

5

Note that the increment value is optional and the default value is 1.

The following is thus the same as above,

for k in range(1,6,1):

print(k)

Note also that range starts with index 0 and not 1. So for example see the following.

for k in range(6):

print(k)

0

1

2

3

4

5

Application of python for loop is for example doing summation in mathematics. See the following formula.

We can implement this summation as follows.

N = 5

x = 0

for i in range(1, N+1):

x += 2*i

print x

See Calculating Summation using While Looop in Python programming language where the same equation is implemented using while loop.

Another useful function for for loop is the linspace(). This is like the matlab linspace function. We will show this function used in the while loop.

The last important structure of any programming language is the while() loop. A while loop is used to do execute one or multiple statements until a certain condition is satisfied. An example of while loop in Ipython programming language is as follows.

from numpy import linspace

v0 = 4.5 # Initial velocity

g = 9.81 # Acceleration of gravity

t = linspace(0, 1, 1000) # 1000 points in time interval

y = v0*t - 0.5*g*t**2 # Generate all heights

# Find where the ball hits y=0

i = 0

while y[i] >= 0:

i += 1

# Now, y[i-1]>0 and y[i]<0 so let’s take the middle point

# in time as the approximation for when the ball hits h=0

print "y=0 at", 0.5*(t[i-1] + t[i])

# We plot the path again just for comparison

import matplotlib.pyplot as plt

plt.plot(t, y)

plt.plot(t, 0*t, ’g--’)

plt.xlabel(’Time (s)’)

plt.ylabel(’Height (m)’)

plt.show()

See Download Programming for Computations for the book.

## No Comment to " The if, for and while statement in Python programming language "