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 条件中的语法错误
- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01
- 使用 Cython 将 Python 链接到共享库 2022-01-01
- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01
- 如何使用PYSPARK从Spark获得批次行 2022-01-01
- 我如何透明地重定向一个Python导入? 2022-01-01
- 计算测试数量的Python单元测试 2022-01-01
- 我如何卸载 PyTorch? 2022-01-01
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01
- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01
- YouTube API v3 返回截断的观看记录 2022-01-01
