Python supports the usual logical conditions from mathematics:
Equals: a == b
Not Equals: a != b
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
These conditions can be used in several ways, most commonly in "if statements" and loops.
An "if statement" is written by using the if keyword.
If statement:
a = 10
b = 20
if b > a:
print("b is greater than a")
Output:
b is greater than a
In this example we use two variables, a and b, which are used as part of the if statement to test whether b is greater than a. As a is 10, and b is 20, we know that 20 is greater than 10, and so we print to screen that "b is greater than a".
Note: Note that in if block indentation is most important, if you do not keep indentation, then above program will not execute, it will give an error
a = 10
b = 20
if b > a:
print("b is greater than a")
Above program will give an error like
IndentationError: expected an indented block
elif
The elif keyword is pythons way of saying "if condition is not correct then it will execute else part.
a = 10
b = 10
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
#Output:
a and b are equal
In the above case, if first b>a condition is not true then else condition a==b will execute.
Else:
The else case will execute if all above conditions are not true.
a = 10
b = 20
if a > b:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
Output:
a is greater than b
If-else:
You can also have an else without the elif:
a = 10
b = 20
if a > b:
print("b is greater than a")
else:
print("b is not greater than a")
Output:
b is not greater than a
Lab Assignment:
Write a python program to check given year is a leap year or not.
year=int(input("Enter Year : "))
if(year%4==0):
if(year%100==0):
if(year%400==0):
print(year," is a Leap Year")
else:
print(year, "is not a Leap Year")
else:
print(year," is not a Leap Year")
else:
print(year," is not a Leap Year")
#Output
Enter Year : 2000
2000 is a Leap year