Clarification regarding If else statement

Hi I am a newbie here, I am writing arithmetic arranger code for the assignment but I am confused with the if and else statement the code as follows:

x = '69467675'
y = "1434"
if len(x) and len(y) <= 4:
    z = '-' * (max(len(x), len(y)) + 2)
    pos_of_op = 6 - (max(len(x), len(y)) + 1)
    if len(x) >= len(y):
        print(x.rjust(6) + '\n' + '+'.rjust(pos_of_op) + y.rjust(6 - pos_of_op) + '\n' + z.rjust(6))
    elif len(y) > len(x):
        print(x.rjust(6) + '\n' + '+'.rjust(pos_of_op) + y.rjust(6 - pos_of_op) + '\n' + z.rjust(6))
else:
    print('ERROR: The number of digits should be less than 5')

the if else statement is not working as I have written in Pycharm but it works if I write it as :

if len(x) <= 4 and len(y) <= 4:

what is the problem can somebody help me ?
PS: the indentations are properly given and I am not getting any error but it is not satisfying the condition and follows through the code

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

Thank you Kevin that helps a lot :slight_smile: :grinning:

I don’t do Python, but I don’t think that this:

len(x) and len(y) <= 4

is not doing what you think it does. You are thinking like a human. Python is interpreting it as:

(len(x)) and (len(y) <= 4)

You are thinking “if this and that are less than or equal to 4”. That kind of construction works in English, but not for a computer. It is evaluating each side of the “and” first and then combining them with the “and” so it is thinking you mean “if this (is truthy) … and … that is less than or equal to 4”.

Does that makes sense?

Thank you very much Kevin yes it makes sense

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.