b and a>c): print("a is greatest") elif(b>a and b>c): print("b is greates" /> b and a>c): print("a is greatest") elif(b>a and b>c): print("b is greates" /> b and a>c): print("a is greatest") elif(b>a and b>c): print("b is greates"/>

How to represent nested if using OR or AND gates?

241 Views Asked by At
a=int(input("Enter a"))
b=int(input("Enter b"))
c=int(input("Enter c"))
if(a>b and a>c):
    print("a is greatest")
elif(b>a and b>c):
    print("b is greatest")
else:
    print("c is greatest")

This is my code to find the greatest number between 3 numbers.

I have different code written in my textbook, and I want to convert it into my type of code.

The code written in textbook is as follows-:

num1=int(input("Enter num1"))
num2=int(input("Enter num2"))
num3=int(input("Enter num3"))
if(num1>num2):
    if(num1>num3):
        print(num1,"is greater than",num2,"and",num3)
    else:
        print(num3, "is greater than", num1, "and", num2)
elif(num2>num3):
    print(num2,"is greater than",num1,"and",num3)
else:
    print("The three numbers are equal")

I want to convert this if statements into boolean expression in if condition and elif conditions, how do I do it?

2

There are 2 best solutions below

0
AudioBubble On BEST ANSWER
if (num1>num2) and (num1>num3):
    print(num1,"is greater than",num2,"and",num3)
elif (num3>num1) and (num3>num2):
    print(num3, "is greater than", num1, "and", num2)
elif (num2>num3) and (num2>num1):
    print(num2,"is greater than",num1,"and",num3)
else:
    print("The three numbers are equal")

You can always use max(num1,num2,num3) function but I guess you don't want that.

Edit:

In the example in your book, between the outer if and its nested if-else there is an implicit AND operator. So

if(num1>num2):
    if(num1>num3):
        print(num1,"is greater than",num2,"and",num3)
    else:
        print(num3, "is greater than", num1, "and", num2)

is actually equivalent to

if(num1>num2) and (num1>num3):
    print(num1,"is greater than",num2,"and",num3)
if(num1>num2) and (num1<=num3):
    print(num3, "is greater than", num1, "and", num2)

Similarly,

elif(num2>num3):
    print(num2,"is greater than",num1,"and",num3)

is equivalent to

if(num1<=num2) and (num2>num3):
    print(num2,"is greater than",num1,"and",num3)
0
X3R0 On

Here is a dynamic approach. Its a bit complicated but works perfectly.

If you read it carefully, then You will be able to understand it.

items = [int(input("Enter a: ")), int(input("Enter b: ")), int(input("Enter c: "))]
highest = items[0]
letter = "A"
for index, item in enumerate(items):
    if item > highest:
        highest = item
        letter = chr(ord("A")+index)

print("{letter} has the highest value of {highest}".format(letter=letter, highest=highest))

enter image description here