Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
642 views
in Technique[技术] by (71.8m points)

python - syntax error in if...else condition

I'm learning programming in Python and I'm stuck with a syntax error in the line 8 in the following code

x = int(input('Add x:
'))
y = int(input('Add y:
'))
if x == y :
    print('x and y are equal')
else :
    if x < y :
        print('x is less than y')
    else x > y :
        print('x is greater than y')

I just don't see what's wrong there.

The full error is:

Traceback (most recent call last):
  File "compare.py", line 8
    else x > y :
         ^
SyntaxError: invalid syntax
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

else takes no condition. It's just else:, nothing more; the block is executed when the if condition (and any elifconditions) didn't match. Use elif if you must have another condition to test on.

In your case, just use

if x == y:
    print('x and y are equal')
elif x < y:
    print('x is less than y')
else:
    print('x is greater than y')

There is no need to explicitly test for x > y, because that's the only option remaining (x is not equal or less, ergo, it is greater), so else: is fine here.

Note that I collapsed your nested if ... else statement into an elif ... else extension on the top-level if.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...