Pages

Monday, August 12, 2019

Decision Making and Loops in Python


Decision Making:
Decision making evaluates the multiple conditions that will produce TRUE or FALSE as an output. Following figure shows the typical structure of decision making:





Python programming language having following types of decision making statements,
  1.      If statement
  2.    If … else statement
  3.    Nested if statement

  1.        If statement :
It is used for decision making and run the body of the code when if statement is true.
Syntax:
            If expression:
                        statement(s)
Example:
            a=10
            b=8
if a>b:
            print(“a is greater than b”)


 2.      If … else statement:

In this type else statement is combined with an if statement. It is mainly used to execute Boolean conditions like if for true and else for false.

Syntax:
if expression:
            statement(s)
else:
            statement(s)

Example:
mark = int(input("Enter the mark of student:"))
if mark >= 40:
    print("Student is passed")
else:
    print("Student is failed")

Above code produce following output:

Enter the marks of student: 38

Student is failed


3.      Nested if statement:
When there are more than two conditions are presents, in that situation nested if statements are used.
Syntax:
if expression1:
    statement(s)
    if expression2:
      statement(s)
    elif expression3:
      statement(s)
    else
      statement(s)
elif expression4:
    statement(s)
else:
    statement(s)

Example:
if 1 = = 2:
    print('first')
elif 3 = = 3:
    print('middle')
else:
    print('Last')

Above code produce following output:
middle


Loops in Python:
In Python there are following types of loops are mainly used:
  1.       For loop
  2. While loop

 1. For loop: It executes a sequence of statements multiple times up to the given condition satisfied.
For example:
seq = [1,2,3,4,5]
for item in seq:
    print(item)

It displays following output:

1
2
3
4
5


2. While loop: It repeats a given one or more statements while a given condition becomes true.
Syntax:
while expression:
statement(s)
Example:
i = 1
while i < 4:
    print('i is: {}'.format(i))
    i = i+1

It displays following output:
                    i is: 1
                    i is: 2
                    i is: 3


No comments:

Post a Comment