# if/else in Python

This chapter will be a new milestone in learning about the programming world and you will be one step nearer to being called a programmer. You will learn about 'if' and 'else' in this chapter.

'if' and 'else' are used for making decisions. For example, you can think of - if your marks is more than 35% then you pass, else fail. If today is your birthday then it's a special day, else normal day.
One more example you can think of is that if you are making any website and want to allow some features to users with an account only, then you can think of - if a user has account, then this else not. Now let's implement this in Python.

• Python 2
• Python 3
```a = input() #taking input from user
if a>10:
print "your number is greater than 10"
else:
print "your number is smaller than 10"
```
```a = int(input()) #taking input from user
if a>10:
print("your number is greater than 10")
else:
print("your number is smaller than 10")
```
11
your number is greater than 10

### How to write?

In the first line, we are taking input.
`if a>10:` - Here we have used 'if'.

`a>10` - This is the condition of given to 'if'. This condition is comparing a with 10 and if a is greater than 10, then it is `True` and if smaller then `False`. So, the whole story is that if a>10 ( if a is greater than 10 ), then it will execute `print("your number is greater than 10")`, otherwise, it will execute `print("your number is smaller than 10")`.

See the flow given diagram below.

```if condition:
statement
statement
...
else:
statement
statement
...
```

We first write `if condition:` ( condition → What has to be judged. In the first example, the condition was '`a>10`' ). Statements under if are executed only when this condition is true otherwise, the statements under else are executed.

Notice that : is written after if and else.

After writing if condition:, we write statements (in the previous example, the statement was `print("your number is greater than 10")`).

Statements written inside if or else must be indented equally from the left margin. It means that all the statements written inside if must be equally spaced from the left. We have used indentation of 8 spaces. It means that before every statement inside if, there is a space left of 8 spaces.

Statements written after equal spaces inside if means that the written statements are inside if ( or body of if ).

Same goes with else as well. Statements written after equal spaces inside else means that the statements are under else.

If the condition of if is true, then statements inside if (body of if represented by equal indentation to the left margin) are executed and if it is false, then statements in else (body of else i.e., represented by equal indentation to the left margin) are executed.

The best way to do this indentation is to type TAB where we want to put the margin. You can set a different width of Tab space in text editors. I have this width of 8. That's why I am getting a width of 8 spaces every time.
In Python, this equal indentation represents the body. Here, it is the body of if and else. It represents what things are inside if and what are inside else. We will see this in many more place like loops, functions to represent their body.
```if condition:
a
b
c
d
else:
e
f
```

Here, a, b, c and d are inside if, as these are written after one Tab space after if. Similarly, e and f are inside else, as they are written after one Tab space after else.

So till now, we have only learned to use if and else.

Any statement written without indentation will be outside of if and else. Look at the example given below.

• Python 2
• Python 3
```a = 11
if a>10:
print "your number is greater than 10"
else:
print "your number is smaller than 10"
print a
```
```a = 11
if a>10:
print("your number is greater than 10")
else:
print("your number is smaller than 10")
print(a)
```
your number is greater than 10
11

Here, the statement `print(a)` is outside of both if and else. Before going further, let's learn about some different operators.

## Arithmetic operator

Commonly used arithmetic operators are:

Operator Name Description
- Subtraction Performs subtraction
* Multiplication Performs multiplication
/ Division Performs division
% Modulus Gives remainder after division
** Exponentitaion a**b is ab
// Floor Division Gives floor value of the result after division

Addition, multiplication and subtraction are simple mathematical operators with no change. Let's see an example over these.

• Python 2
• Python 3
```a = 20
b = 10
print a+b
print a-b
print a*b
```
```a = 20
b = 10
print(a+b)
print(a-b)
print(a*b)
```
30
10
200

#### division operator

Let's see an example.

• Python 2
• Python 3
```print 5/2
print 5.0/2
print 5.0/2.0
print 5/2.0
```
```print(5/2)
print(5.0/2)
print(5.0/2.0)
print(5/2.0)
```
2.5
2.5
2.5
2.5
In Python 2, 5/2 will give us 2 and not 2.5. If both the operands of / are integer, then the result in Python 2 is also an integer rounded to the nearest lower integer. It means that 1/2 will give 0 (as the nearest lower integer near to 0.5 is 0) in Python 2. To get float in Python 2, at least anyone of the both operands must be a float.

% operator gives us the remainder after division of two numbers.

** operator is the exponential operator. It will calculate the power of the first operand raised to second. For example, 4**2 means 42.

// is floor division operator. It means that it will give us a value that will be rounded off to the nearest lower integer after the division of two numbers, even if the numbers are float.

Let's see an example of these operators

• Python 2
• Python 3
```a = 5
b = 2
print a%b
print a**2
print 5.0//2
```
```a = 5
b = 2
print(a%b)
print(a**2)
print(5.0//2)
```
1
25
2.0

You can see in the example given above, % calculated the remainder, ** calculated 52 and // gave us 2.0 (not 2.5) which is rounded to the nearest lower integer i.e. 2.

## Priority order

In maths, you might have learned about BODMAS rule, but that rule is not applied here. If we have written more than one operation in one line, then which operation should be done first is governed by PEMDAS.

PEMDAS means :
Parentheses have the highest priority. It means brackets i.e. ( ).
Next is Exponential.
Then Multiplication and Division have the same precedence.
Then Addition and Subtraction have the same precedence.

Now a valid question comes in mind that which operator should be done first if they have the same precedence?

The answer is that if operators have the same precedence then they are evaluated from left to right. E.g. - 3-2+2 will be evaluated from left to right. It means that 3-2 will be evaluated first (as it is in left). And 3-2 is 1. So, the expression will become 1+2 and finally get evaluated as 3.

E.g.-
8/4+3-5*6+8
Solving, '*' and '/' first from left to right.
2+3-30+8
Now solving, '+' and '-' from left to right
-17

If you don't want to remember these rules, then just put the expression you want to execute first in brackets. E.g.- If you want to divide the product of (2+2) and 444 by the quotient of (999/5), then write the expression as - ((2+2)*444)/(999/5). This will get evaluated as (4*444)/(999/5) and finally get simplified to 1776/199 (since 999/5 is 199 and not 199.8).

Now, you are ready to go for if and else.

#### Even or odd

• Python 2
• Python 3
```a = input()
if a%2 == 0: #checking divisiblity by 2
else:
```
```a = int(input())
if a%2 == 0: #checking divisiblity by 2
else:
```
13
You number is odd

The above code is self-explanatory. In the above code, a%2 will give us the remainder by dividing 'a' with 2. And if the remainder is 0 (perfectly divisible by 2), then the body of 'if' will be executed otherwise that of 'else' will be executed.

#### if under if

Yes, we can use one if inside another. This is also called nesting.

• Python 2
• Python 3
```print "Enter a number"
a = input() #taking input from user
if a%2 == 0: #checking divisiblity by 2
if a>10:
print "Your number is greater than 10 and even"
else:
print "Your number is even and smaller than or equal to 10"
elif a%2!=0:
```
```print("Enter a number")
a = int(input()) #taking input from user
if a%2 == 0: #checking divisiblity by 2
if a>10:
print("Your number is greater than 10 and even")
else:
print("Your number is even and smaller than or equal to 10")
elif a%2!=0:
```
Enter a number
12
Your number is greater than 10 and even

First see elif.
elif → elif is 'else if'. I think you have already got the feel of elif. Next lines will make it even more clear.

Firstly, the condition in 'if' will be checked. If it is true, then only 'if' will be executed and if it is false, then the compiler will check below.

If the condition of 'if' is false, then condition in 'elif' will be checked. In the same way, if the condition of elif is true, then its body will be executed otherwise the compiler will come below.

If 'if' and 'elif' both are false then else will be executed.

Now, if the condition of first if is true, then there is another if inside its body. So, now this if will be checked. Thus, if a number is even (a%2==0 is true) then next if inside its body will be checked. So, it will check if the number is greater than 10 or not. And if this if is also true then `print("Your number is greater than 10 and even")` will be executed, otherwise, since there is no else statement for this if so program will stop.

Notice the indentation of left margin in the above example, print "your number is greater than 10 and even" is inside both if a>10 and if a%2==0. If you are facing any difficulty, feel free to ask your question.
We can add any number of elif after if. Also, we can add any number of statements inside 'if', 'elif' or 'else'.
Also, if 'else' is not required then we can write only 'if' (without 'else' or 'elif') and it will run smoothly. Try this on your own.

See the flow chart below

```if condition:
statement
statement
...
elif condition:
statement
statement
...
elif condition:
statement
statement
...
...
...
else:
statement
statement
...
```

#### Another way to write the above code.

• Python 2
• Python 3
```print "Enter a number"
a = input()
if a%2 == 0 and a>10: #using 'and' in condition
print "Your number is greater than 10 and even"
elif a%2 == 0 and a<10: #using 'and' to check if both conditions are true or not
print "Your number is even and smaller than 10"
else:
```
```print("Enter a number")
a = int(input())
if a%2 == 0 and a>10: #using 'and' in condition
print("Your number is greater than 10 and even")
elif a%2 == 0 and a<10: #using 'and' to check if both conditions are true or not
print("Your number is even and smaller than 10")
else:
```
Enter a number
12
Your number is greater than 10 and even

In the Boolean section, you have learned about 'and'.
`a%2==0 and a>10` → if 'and' is used, then it will be true if both the operands are true, meaning if a%2 is equal to 0 and a is greater than 10.

Also, 'elif' will be true if both the conditions (`a%2 == 0 and a<10`) are true, meaning 'a' is divisible by two and a is less than 10. You can understand the rest of the codes on your own.

Let's see one more example to understand more clearly.

• Python 2
• Python 3
```print "Enter your age."
age = input()
if age < 13:
print "Hey! kid"
elif age>13 and age < 20:
print "So, you are enjoying your teenage."
else:
print "You are grown up."
```
```print("Enter your age.")
age = int(input())
if age < 13:
print("Hey! kid")
elif age>13 and age < 20:
print("So, you are enjoying your teenage.")
else:
print("You are grown up.")
```
20

### Use of pass

'pass' is used to skip from 'if' or 'else'. If we don't have to give any argument in any of 'if', 'else' or elif, we use `pass`. (We will see later that pass is also used with methods and classes). See an example to make it clear

• Python 2
• Python 3
```print "Enter your age."
age = input()
if age < 13:
print "Hey! kid"
elif age>13 and age < 20:
pass
else:
print "You are grown up."
```
```print("Enter your age.")
age = int(input())
if age < 13:
print("Hey! kid")
elif age>13 and age < 20:
pass
else:
print("You are grown up.")
```
14

As we have seen, using 'pass' just skipped and did nothing in 'elif'.

We highly recommend you to practice on this section. You will get a bunch of different problems in the practice section.
You will go through many questions including the above concepts in the practice section. If you are facing difficulty anywhere, then feel free to ask questions.
You practice and you get better. It's very simple.
- Phillip Glass  