vendredi 4 septembre 2015

Python: Conditional statement giving unexpected results [duplicate]

This question already has an answer here:

I am currently learning Python from Edx and this was one of the questions in the quiz.

Assume that two variables, varA and varB, are assigned values, either numbers or strings.

Write a piece of Python code that prints out one of the following messages:

"string involved" if either varA or varB are strings

"bigger" if varA is larger than varB

"equal" if varA is equal to varB

"smaller" if varA is smaller than varB

This is the code I came up with.

varA = 5
varB = 10

if varA or varB == type(str):
    print "string involved"
elif varA and varB == type(int):
    if varA > varB:
        print "bigger"
    elif varA == varB:
        print "equal"
    elif varA < varB:
        print "smaller"

Yes, I do know this is the wrong answer. I finally came up with the right answer, but what caught my attention was this wrong code.

If I assign varA and varB with some string, I get the expected result, which is "string involved" but if I give them some integer value, I still get the output as "string involved".

According to my knowledge, if the variables are assigned integers, then the first if statement will check if either of the variable are strings or not and if not, then the elif statement will be executed. But in my case, that is not happening. Can someone please explain this to me?

Please note that I already came up with a solution for the quiz question so ignore that.

Thank you.

Aucun commentaire:

Enregistrer un commentaire