Search code examples
pythoncomparisonlogical-operators

Python logical test of odd numbers


I wonder if my answer below is correct and feasible or are there any improvements Thank you. question: a program that checks x y and z if they are odd or even if they are odd checks if the number is the biggest of all three. Below my answer:

    x = 4
    y = 7
    z = 9

  #first condition where 3 numbers are all odd.

    if x%2 == 1 and y%2 == 1 and z%2 == 1:
        if x > y and x > z:
            print "x is the biggest odd number."
        elif x > y and z > x:
            print "z is the biggest odd number."
        else:
            print "y is the biggest odd number."

#second condition where 2 of the numbers are odd
elif x%2 == 0 and y%2 == 1 and z%2 == 1:
    if y > z:
        print "y is the biggest odd number."
    else:
        print "y is the biggest odd number."
elif x%2 == 1 and y%2 == 0 and z%2 == 1:
    if x > z:
        print "x is the biggest odd number."
    else:
        print "z is the biggest odd number."

elif x%2 == 1 and y%2 == 1 and z%2 == 0:
    if x > y:
        print "x is the biggest odd number."
    else:
        print "y is the biggest odd number."    

#third condition where only one of the numbers is odd.

elif x%2 == 0 and y%2 == 0 and z%2 == 1:
    print "z is the biggest odd number."
elif x%2 == 1 and y%2 == 0 and z%2 == 0:
    print "x is the biggest odd number."
elif x%2 == 0 and y%2 == 1 and z%2 == 0:
    print "y is the biggest odd number."

#last condition if none of the numer are odd or not numbers.

else:
    print " None of the numbers are odd or not a number."

Solution

  • Wow! That is a ton of code. Why don't you just put x,y,z in a list. Use a list comprehension to remove even numbers. Then select the maximum value using the max function. Something like this

    arr = [x,y,z]
    arr = [i for i in arr if i%2!=0] #select only odd numbers
    print(max(arr)) #display the maximum number
    

    Then you can use max(arr) to figure out what variable contains the maximum odd number.