# Comparin 3 different values and return middle (if/elif)

Hello,

I have little problem with comparing 3 different variables and it should always return middle one.

Example:

char1 = a
char2 = b
char3 = c

If char1 > char2 and char2 > char3:
print(char2)
elif char1 < char2 and char1 > char3:
print(char1)
elif char3 > char2 and char3 < char1:
print(char3)

And it should always return which is middle in alphabets using if/elif + and or

Been trying to do that but so far its only working partly and my brain is stuck. It only prints from char2 and char3 with B

Did you mean to make a, b, & c strings?

Remember that both operands in the expression have to evaluate to `True` for your `print()` to print something out.

Do any of your statements evaluate to `True`? How would you change it to make it work to print â€śbâ€ť (or whatever it is that you want printed)?

Summary
``````char1 = "a"
char2 = "b"
char3 = "c"

if char1 > char2 and char2 > char3:  #this evaluates to False and False (False)
print(char2)
elif char1 < char2 and char1 > char3: #this evaluates to True and False (False)
print(char1)
elif char3 > char2 and char3 < char1: #this evaluates to True and False (False)
print(char3)
``````

docs are here and here and over here too.

2 Likes

Im not sure if i presented my problem correctly, but if im using them in different order c,a,b. It should return that B is middle value. No matter which variable string is stored at.

Or even using q,o,u any order; it should print q.

Also a key point to remember is that when Python compares strings, it converts them to their ordinal value (ASCII value) and then compares the integers from left to right. So, each letter has a value. The value of a is less than say, b or c.

See here
and here for ASCII values.

``````char1 = "a" #ordinal value is 97

char2 = "b" #ordinal value is 98

char3 = "c" #ordinal value is 99

if char1 > char2 and char2 > char3:  #this evaluates to False and False (False)
print(char2)
elif char1 < char2 and char1 > char3: #this evaluates to True and False (False)
print(char1)
elif char3 > char2 and char3 < char1: #this evaluates to True and False (False)
print(char3)
``````

Substitute the numbers for the strings in the comparisons. Nothing prints b/c all statements evaluate to False in the control flow statement.

2 Likes

Thank you! This helped me a lot. Didnt even know that characters are evaluated as numbers.

1 Like