If, else and elif statment in Python

As other programming languages, Python also provides if and else statement to control the program flow. Every if statement has code block attached with it. If the condition is valid and true, code block will be executed, otherwise it will be skipped.

if(Condition is true):
    execute this code block

When it comes to the syntax, Python is flexible and easy as compare to other languages. There is no need to use “( )” brackets with if statement (you can use if you want) and there is no “{ }” brackets required to start the code block because every code block starts with “:” colon, hit enter and start writing the code.

name = "Abid"
if name = "Abid":
    print("Hello Abid")

student_marks = 89
if student_marks > 85: ## without small brackets
    print( "Student got A")

if (student_marks > 85): ## with small brackets
    print( "Student got A")

As you can see, you can add “( )” brackets or skip them, does not matter but one thing you must remember that whenever you want to start new block of code, it will start from next line right after “:” colon.

else statement 

if(Condition is true):
    execute this code block
else:
    execute this code block

See this example:

student_marks = 80
 
if (student_marks > 85): ## new block
    print( "Student got A")
else: ## new block
    print("Student got B")

When there are more than one conditions to handle, else statement comes into play. If first condition is true execute first code block otherwise execute second one. Else statement comes always after if statement. This example says that if student got more than 85 marks then assign A grade to student otherwise B grade. You can do some experiments by changing student_marks value.

elif statement (else if) 

Sometimes you are facing such a situation where you have many possibilities to execute. For example you have to decide, on based of marks, which grade will be assigned to the student. For this situation Python provides elif which is a short form of else if.  

if(Condition is true):
    execute this code block
elif(condition is true):
    execute this code block
else:
    execute this code block

Execute the following example, change value of studentMarks and see the different output.  

studentMarks = 85
grade = ""
 
if studentMarks >= 90:
    grade = "A"
elif studentMarks >= 80:
    grade = "B"
elif studentMarks >= 70:
    grade = "C"
elif studentMarks >= 60:
    grade = "D"
else:
    grade = "F"
    
print("Student got",grade)