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

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

问题描述

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

x = int(input('Add x:
'))y = int(input('添加 y:
'))如果 x == y :print('x 和 y 相等')别的 :如果 x <:print('x 小于 y')否则 x >:print('x 大于 y')

我只是不明白那里有什么问题.

完整的错误是:

回溯(最近一次调用最后一次):文件compare.py",第 8 行否则 x >:^语法错误:无效语法

解决方案

else 不接受任何条件.它只是else:,仅此而已;当 if 条件(和任何 elif 条件)不匹配时,将执行该块.如果您必须有其他条件进行测试,请使用 elif.

在你的情况下,只需使用

如果 x == y:print('x 和 y 相等')elif x 

无需显式测试 x >y,因为这是剩下的唯一选项(x 不等于或不小于,因此,它更大),所以 else: 在这里很好.>

请注意,我将嵌套的 if ... else 语句折叠到顶级 if 上的 elif ... else 扩展中.

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

解决方案

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.

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

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