syntax error in if…else condition

别来无恙 提交于 2019-12-04 07:22:13

问题


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:\n'))
y = int(input('Add y:\n'))
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

回答1:


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.



来源:https://stackoverflow.com/questions/50079139/syntax-error-in-if-else-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!