Learn about Python If Else

Introduction

In real life, we have to make decisions to perform a particular task. Subsequent tasks are completed depending on making the right decisions. But the computer can't think with its own intellect. We train them through programming. Here comes If Else. Let's see how it works.

Example

In this example, the computer will find the grade of the result depending on the marks.


print("Grade System")

marks = int(input("Enter your marks: "))
if marks > 90:
print("Outstanding!")
elif marks > 80:
print("A+")
elif marks > 60:
print("A")
elif marks > 45:
print("B+")
elif marks > 30:
print("B")
else:
print("Fail")

Output

Grade System
Enter your marks: 91
Outstanding!

Conditional If Else

Here, our program will tell if a person can watch or download a movie or not.


print("Get permission to Watch Fifty Shades of Gray")

name, age = input("Enter your Name and Age: ").split(',')

if name == 'Smith' and int(age) > 18:
print("You can watch the movie")
elif name == 'Smith' or name == 'Alex' and int(age) >= 17 :
print('You can download this movie')
else:
print("You can't watch or download this movie")

Output

Get permission to Watch Fifty Shades of Gray
Enter your Name and Age: Alex, 17
You can download this movie

In Keyword in Python

Here, the code will find if a character is present or not in a string.


name = 'reverse shell'
if 'e' in name:
print("e is Present ")
else:
print("Not present")

Output

e is Present

Check if a String is Empty or Not

This python program will check if a string is empty or not using the If Else statement.


name = 'Python'
if name:
print("All is OK!")
else:
print("There is no name to print")

Output

All is OK!

Subhankar Rakshit

Meet Subhankar Rakshit, a Computer Science postgraduate (M.Sc.) and the creator of PySeek. Subhankar is a programmer, specializes in Python language. With a several years of experience under his belt, he has developed a deep understanding of software development. He enjoys writing blogs on various topics related to Computer Science, Python Programming, and Software Development.

Post a Comment (0)
Previous Post Next Post