Decision Making and Loops

Objective : What I want you to learn?

ABC

Rationale : Why this is useful to you?

ABC

Learning Outcomes : What I want you to do after completing this topic?

ABC

Contents

If Statement in Python

If statements are used to control the flow of a program by executing different blocks of code depending on the value of a condition. The general syntax for an if statement in Python is as follows: 

The condition can be any expression that evaluates to a boolean value. If the condition evaluates to True, then code block 1 is executed. 

if condition:

    code block 1

import numpy as np


R = 8.31415     # J/(mol.K)

MM = 0.02897    # J/mol

gamma = 1.4     # (No Unit)

Temp = 293      # Kelvin


a = np.sqrt(gamma*(R/MM)*Temp)

print("The speed of Sound is ", a)


Vel = float(input("Enter the Velocity of the object in m/s : "))


MachNo = Vel/a

if MachNo > 1:

  print("The Flow Regime is Supersonic")

If  .. Else Statement in Python

if condition:

  code block 1

else:

  code block 2

The condition can be any expression that evaluates to a boolean value. If the condition evaluates to True, then code block 1 is executed. If the condition evaluates to False, then code block 2 is executed. 

import numpy as np


R = 8.31415     # J/(mol.K)

MM = 0.02897    # J/mol

gamma = 1.4     # (No Unit)

Temp = 293      # Kelvin


a = np.sqrt(gamma*(R/MM)*Temp)

print("The speed of Sound is ", a)


Vel = float(input("Enter the Velocity of the object in m/s : "))


MachNo = Vel/a


if MachNo > 1:

  print("The Flow Regime is Supersonic")

else:

  print ("The Flow Regime is Subsonic")

The speed of Sound is 343.10931454264454 Enter the Velocity of the object in m/s : 100 The Flow Regime is Subsonic 

The speed of Sound is 343.10931454264454 Enter the Velocity of the object in m/s : 400 The Flow Regime is Supersonic 

If  .. Elif Statement in Python

The if-elif statement is shortcut of if..else chain. While using if-elif statement at the end else block is added which is performed if none of the above if-elif statement is true. 

if (condition):

    statement

elif (condition):

    statement

.

.

else:

    statement

Nested If Statement in Python

Nested if statements in Python are if statements that are placed inside of other if statements. placed inside. This allows you to check multiple conditions and execute different blocks of code depending on the outcome of all of the conditions. 

Single Statement Suites

While, for and nested loops

Loop control statements