when there is a need to check something in python, there are generally two types of operators are needed:
1. comparison operators
2. logical operators
comparison operators
comparison operators are the operators that return true or false (boolean values) based on the condition.
comparison operators are as follows:
>: greater than
example:
print(4>4)
print(4>2)
print(4>5)
output:
false
true
false
<: less than
example:
print(4<4)
print(2<4)
print(5<4)
output:
false
true
false
<=: less than or equal to
example:
print(4<=4)
print(2<=4)
print(5<=4)
output:
true
true
false
>=: greater than or equal to
example:
print(4>=4)
print(4>=2)
print(4>=5)
output:
true
true
false
==: equal to
example:
print(4==4)
print(4=="4")
print(5==4)
output:
true
false
false
!=: not equal to
example:
print(4!=4)
print(4!="4")
print(5!=4)
output:
false
true
true
logical operators
logical operators are used to check multiple conditions at a time.
1. and: returns true if both conditions are true
and condition1 condition2 final result
case1 True True True
case2 True False False
case3 False True False
case4 False False False
example:
print(2>2 and 3<4)
print(2>=2 and 2>1)
print(2<3 and 3>3)
print(3!=3 and 2==4)
output:
False
True
False
False
2. and: returns true if one of the condition is true
and condition1 condition2 final result
case1 True True True
case2 True False True
case3 False True True
case4 False False False
example:
print(2>2 or 3<4)
print(2>=2 or 2>1)
print(2<3 or 3>3)
print(3!=3 or 2==4)
output:
True
True
True
False
3. not: returns true ,if final result is false.
example:
print(not(2>1 and 3<4))
output:
False
if statement
if statements are used to perform tasks based on the condition.
syntax:
if condition:
#code if the condition is true
else:
#code if the condition is false
example:
Q1.CHECK THE NUMBER IS NEGATIVE OR POSITIVE.
num=29
if num<0:
print(num",is negative")
else:
print("num",is positive")
Q2.CHECK IF THE NUMBER IS ODD OR EVEN.
num=29
if num%2==0:
print(num",is even")
else:
print("num",is odd")
Q3.CHECK IF THE NUMBER IS PALINDROME OR NOT.
num=29
if num%2==0:
print(num",is even")
else:
print("num",is odd")
Q4.CHECK WHETHER THE NUMBER IS PALINDROME OR NOT.
num=int(input("enter any 3-digit number"))#taking user input
rev=0
lastdigit=0
backup=num
lastdigit=num%10
num=num//10
rev=rev*10+lastdigit
lastdigit=num%10
num=num//10
rev=rev*10+lastdigit
lastdigit=num%10
num=num//10
rev=rev*10+lastdigit
print("reverse is ",rev)
if backup==num:
print("number is palindrome")
else:
print("number is not palindrome")
0 Comments