Given fig. is for the syntax and flowchart of the if statement in python.
lets learn how syntax (if statement) works from given Diagram.
We know that Python script starts execution from top and goes to end.
After step by step successful execution of script the control falls into the if statement.
after that The flow jumps to Condition.
and begins testing the Condition
1. if the condition tested is true. then executes statements inside if body.
i.e. '''body of if
statements to be
executed when
the condition in if statement is true '''

"Statements outside if" always executes after successful execution of above code and the control comes out of the code .

2. if the condition tested is false. then the code outside if executes i.e. "statements outside if" executes.
"statements outside if" always executes if the condition is true or false.


Example 1: Python script to show the use of if statement .


p=8;
q=6;
if p<q:    #test-condition
  print(p," is smaller than ",q);

if q<p:    #test-condition
  print(q," is smaller than ",p)


Output:
6 is smaller than 8
The above program illustrates the use of if statements to check minimum of two numbers.
1. In the above script, we have initialized two number variables with p, q with value as 8, 6 respectively.
2. Then, we have used if p<q: with a test-expression to check which number is the smallest . We have used a relational operator < in if statement. Since the value of p is greater than q, the condition will evaluate to false and dose not give any output.
3. Then, we have used second if q<p: with a test-expression to check which number is the smallest . We have used a relational operator < in if statement. Since the value of q is smaller than p, the condition will evaluate to true
4. Thus it executes print(q," is smaller than ",p) statement inside the block and dispalys output 6 is smaller than 8 After that, the control goes outside of the block and script terminates with a successful result.


Example 1: Python script to find Given number is Even or odd.

""" Python script to find given number is even or odd using modulus (%) Operator """
n=int(input("Enter Any Number"))
if n%2==0:
  print(n," is Even")
if n%2==1:
  print(n," is Odd")

Output:
Enter Any Number
5
5 is Odd
Program Explanation:
n=int(input("Enter Any Number"))=: The input function Shows message "Enter Any number on the Console". It accepts any input as String even though we enter integer values , so we have converted this input into integer using int().
if n%2==0: this expression evaluate to false. The result of n%2 is 1. Then our expression became 1==0 which is false and skip the first if block.
if n%2==1: this expression evaluate to true. The result of n%2 is 1. Then our expression became 1==1 which is true so execute the body or block of second if statement. where it has print(n," is Odd") statement displays output 5 is odd.

Previous Topic:-->> Decision Making in Python || Next topic:-->>if else in Python.