# If and Else

# If

  • if will take action when condition is True.
if True:
    print("1")
1
2
output

OUTPUT

1

if False:
    print("1")
1
2
output

OUTPUT

# Let's practice together

a = 10
b = 20
if(a<b):
    print(1)
1
2
3
4
output

OUTPUT

1

a = 10
b = 20
if(a<b and b>100 and a<0):
    print(1)
1
2
3
4
output

OUTPUT

a = 10
b = 20
if(a<b and b<100):
    print(1)
    if(a < 0):
        print(2)
1
2
3
4
5
6
output

OUTPUT

1

a = 10
b = 20
if(a<b and b<100):
    print(1)
    if(a < 0):
        print(2)
    if(a > 0):
        print(3)
        if a == 10:
            print(4)
    if(a-10 == 0):
        print(5)
1
2
3
4
5
6
7
8
9
10
11
12
output

OUTPUT

1 3 4 5

a = 10
b = 20
if(not a>b):
    print(1)
1
2
3
4
output

OUTPUT

1

a = 10
b = 20
if(not (a>b) ):
    print(1)
1
2
3
4
output

OUTPUT

1

# Let's start coding together

  • To be given score. Then show the grade.
Grade Score
A [80, 100]
B [70, 80)
C [60, 70)
D [50, 60)
F [0, 50)

OUTPUT

score: 99 get A

OUTPUT

score: 50 get D

OUTPUT

score: 72 get B

OUTPUT

score: 49 get F

Solution
score=float(input("score: "))
if(score>=80 and score<=100):
    print("get A")
if(score>=70 and score<80):
    print("get B")
if(score>=60 and score<70):
    print("get C")
if(score>=50 and score<60):
    print("get D")
if(score>=0 and score<50):
    print("get F")
1
2
3
4
5
6
7
8
9
10
11

# Let's start coding together (2)

  • do the simple calculator

OUTPUT

Number1: 5 (+ - * /): + Number2: 3 8.0

OUTPUT

Number1: 5 (+ - * /): * Number2: 5 25.0

OUTPUT

Number1: 9 (+ - * /): - Number2: 9 0.0

OUTPUT

Number1: 9 (+ - * /): / Number2: 2 4.5

Solution
n1=float(input("Number1 : "))
op=input("(+ - * /): ")
n2=float(input("Number2 : "))
if(op=="+"):
    print(n1+n2)
if(op=="-"):
    print(n1-n2)
if(op=="*"):
    print(n1*n2)
if(op=="/"):
    print(n1/n2)
1
2
3
4
5
6
7
8
9
10
11

# Let's start coding together (3)

  • compare between two numbers

OUTPUT

Enter first number: 50 Enter second number: 1 50.0 > 1.0

OUTPUT

Enter first number: 1 Enter second number: 8 1.0 < 8.0

OUTPUT

Enter first number: 5 Enter second number: 5 5.0 == 5.0

Solution
a=float(input("Enter first number: "))
b=float(input("Enter second number: "))
if(a<b):
    print(f"{a} < {b}")
if(a>b):
    print(f"{a} > {b}")
if(a==b):
    print(f"{a} == {b}")
1
2
3
4
5
6
7
8

# Else

  • else will take action if if statement which matchs with itself, is False.
if False:
    print("1")
else:
    print("2")
1
2
3
4
output

OUTPUT

2

# Let's practice together

a = 10
b = 20
if(a<b):
    print(1)
else:
    print(2)
1
2
3
4
5
6
output

OUTPUT

1

a = 10
b = 20
if(not a<b):
    print(1)
else:
    print(2)
    if(a<b):
        print(3)
        if(a<0):
            print(4)
        else:
            print(5)
    else:
        print(6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
output

OUTPUT

2 3 5

# Exercise Book 09.If and Else