Python Programming

If Condition in Python

In Programming, Python by Baqir Ali

During coding any piece of the application you will face a time when you need the application to make a decision. In order to make decisions either true or false, either execute a statement or not we use if statement.

So let’s make some programs

If Statement in Python

Scenario: if the temperature is above 30 it is hot:

temp=35
if temp>30:
    print("It is Hot Today")
print("--- The End ---")

Output:

It is Hot Today
— The End —

if you want multiple statements run on one condition then you should put all those statements in the same indentation. like if it is hot get an amberalla.

temp=35
if temp>30:
    print("It is Hot Today")
    print("get an amberalla")
print("--- The End ---")

If Else Statement in Python

Scenario: if the temperature is above 30 it is hot otherwise it is cold

temp=input("Enter temperature: ")
temp=int(temp);
if temp>30:
    print("It is Hot Today")
else:
    print("It is Cold")
print("--- The End ---")

Output:

Enter temperature: 25
It is Cold
— The End —

Scenario: check if the number is even or odd

val=input("Enter a Number: ")
val=int(val);
if val%2==0:
    print("It is Even")
else:
    print("It is Odd")
print("--- The End ---")

Output:

Enter a Number: 4
It is Even
— The End —

Else if statement in Python

If you want to use multiple conditions in your application then else if is the best option.

Scenario: get your marks and get your grade

val=input("Enter your marks: ")
val=int(val)
if val>100:
    print("Invalid")
elif val>80:
    print("A+")
elif val>70:
    print("B")
elif val>60:
    print("C")
elif val>=50:
    print("Pass")
elif val>=0:
    print("Fail")
else:
    print("Invalid")
print("--- The End ---")

Output:

Enter your marks: 65
C
— The End —

Support us by sharing this post