Control and Loop Statements in Python PYTHON by Ravinder Nath Rajotiya - April 19, 2019May 10, 20210 Share on Facebook Share Send email Mail Print Print Table of Contents Toggle Control StatementsNested if Statement Control Statements There are many instances when it is required to take decision. If statement is a decision making statement. If statement in Python is used to test a condition and transfer the control of program to usual sequential next line of code or skips certain lines and jump to another point. It should be clearly noted that Python make use of indentation almost every where especially while writing if statement. If indentation is not used in a statement that particular line of code will be treated as not part of if statement or loop statements and is thus treated as statement outside the control and loop. example: >>> x=10 >>> if x>0: . . . print(x,” is +ve Number”) #indented line thus executed if x>0 TRUE >>>print(x,” is -ve”) # this will also be printed as unintended lines outside if So, one should be very careful while writing Python statement, as if you forget to indent you line of code properly, the line may be treated as outside the if statement and give wrong answer. Figure below shows the flowchart of the if-else statement. When the expression turns out to be TRUE the immediate next line of code in sequence are executed. If the expression is FALSE then the next line(s) of code are skipped. Example below shows some of the correct ways of writing the if and else statement in Python Flowchart of if else Statement Flowchart If – elif Statement in Python Python Syntax Python Example Syntax-1 If condition : Statement(s) #see indentation Syntax-2 if condition : Statement(s) else: statement(s) Syntax-3 If condition : Statement(s) elif condition : Statement(s) else: statement(s) There can be zero or more elif parts, and the else part is optional. The keyword ‘elif’ is short for ‘else if’, and is useful to avoid excessive indentation. An if … elif … elif … sequence is a substitute for the switch or case statements found in other languages. Nested if Statement Python permits writing if statement inside another if statement. This way of writing a if...elif...else statement inside another if...elif...else statement is called nesting Example: >>>x=10 >>> if x > 0 : >>> , , , if x == 0: >>> . . . . . . print (“x is zero”) >>> . . . else : >>> . . . . . . print(“Number is +ve”) >>> else : >>> . . . print (“Number is Negative”) Exercise: Write a program in Python to print whether a number is +ve or -ve Write a program in Python to calculate the % of marks of a student. Share on Facebook Share Send email Mail Print Print