syntax error in if...else condition(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 条件中的语法错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:if...else 条件中的语法错误
基础教程推荐
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 包装空间模型 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 求两个直方图的卷积 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
