computer scince and engineeringpython

python control statement if, if…else, if…elif…else statement with examples by unitdiploma

3views

Control Statement

•Concept of Indentation

•if, if…else, if…elif…else statement with examples

Control statements

•Control statements decides the direction of flow of program execution.

•Decision making:

•if statement

•if…else statement

•if…elif…else statement

The if statement

•It is used to execute one or more statement depending upon whether condition is true or not.

•Syntax:-

  num=1

if condition:                          if num==1:

  statements                             print(‘one’)

Identation

•In Python, the body of the if statement is indicated by the indentation. Body starts with an indentation and the first un-indented line marks the end.

•It refers to spaces that are used in the beginning of a statement. The statements with same indentation belong to same group called a suite.

•By default, Python uses 4 spaces but it can be increased or decreased by the programmers.

if x==1:

print(‘a’)

print(‘b’)

If y==2:

print(‘c’)

print(‘d’)

print(‘end’)

print (‘’end)

The if..else statement

•The if..else statement evaluates test expression and will execute body of if only when test condition is True. If the condition is False, body of else is executed. Indentation is used to separate the blocks.

•Syntax:-

If condition:

  Satement1

else:

  Statement2

Example

num = 3

if num >= 0:   

      print(“Positive or Zero”)

else:   

       print(“Negative number”)

if…elif…else Statement

•The elif is short for else if. It allows us to check for multiple expressions.

•If the condition for if is False, it checks the condition of the next elif block and so on.

•If all the conditions are False, body of else is executed.

•Only one block among the several if…elif…else blocks is executed according to the condition.

•The if block can have only one else block. But it can have multiple elif blocks.

Syntax

if condition1:

   Statement1

elif condition2:

   Statement2

elif condition3:

   Statement3

else:

Body of else

Example

num = 3.4

 if num > 0:   

        print(“Positive number”)

elif num == 0:  

        print(“Zero”)

else:   

        print(“Negative number”)

Leave a Response