if ... else条件中的语法错误 [英] syntax error in if...else condition

查看:192
本文介绍了if ... else条件中的语法错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Python编程,我在以下代码的第8行遇到语法错误

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.

完整的错误是:

Traceback (most recent call last):
  File "compare.py", line 8
    else x > y :
         ^
SyntaxError: invalid syntax


推荐答案

else 不带条件。它只是否则:,仅此而已;当 if 条件(以及任何 elif 条件)不匹配时执行该块。使用 elif 如果您必须有其他条件可以进行测试。

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')

无需明确测试 x> y ,因为这是剩下的唯一选项( x 不等于或小于,ergo,它更大),所以否则:在这里没问题。

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.

请注意,我折叠了你的嵌套 if ... else 声明到 elif ... else 扩展名在顶级如果

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

这篇关于if ... else条件中的语法错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆