[英]Why is it not possible to have an IF statement in a TRY block in Python, and if somehow possible, is it good practice?
I am getting an indentation error, but my code is indented properly. 我收到缩进错误,但我的代码缩进正确。 If I take out the if statement, the code will run fine.
如果我取出if语句,代码将运行良好。 Here is the relevant snippet:
这是相关的片段:
80 try:
81 votes_a = breakdown[0]['count']
82
83 if breakdown[0]['pick'] != m.home:
84 votes_b = votes_a
85 except IndexError:
86 votes_a = 0.0
If I remove lines 83 and 84 the code will work. 如果我删除第83和84行,代码将起作用。 Is it not possible/advisable to have control statements within try/except blocks of python code?
在try / except的python代码块中是否有可能/可取的控制语句?
cheers 干杯
Update: The indentation error was not in the line that django told me, it was the line above. 更新:缩进错误不在django告诉我的行中,这是上面的行。 And, yes, there was one tab thrown in there instead of a space.
而且,是的,那里有一个标签而不是空格。 Thanks.
谢谢。
Of course it's possible. 当然有可能。 If you get indentation errors, but indentation looks good visually, there's a good chance you've mixed tabs with spaces.
如果您收到缩进错误,但缩进在视觉上看起来很好,那么您很可能将制表符与空格混合。 It's best to not use tabs at all.
最好不要使用制表符。 You can run Python with
-tt
to detect inconsistent tab usage. 您可以使用
-tt
运行Python以检测不一致的选项卡使用情况。
Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> breakdown = []
>>> breakdown.append({'count':5, 'pick':0})
>>> abc = 0
>>> try:
... votes_a = breakdown[0]['count']
... if breakdown[0]['pick'] != abc:
... votes_b = votes_a
... except IndexError:
... votes_a = 0.0
...
>>> print votes_a
5
>>>
As it seems, the code itself is fine. 看起来,代码本身很好。 You must've messed up spaces/tabs somewhere
你必须搞砸某处的空格/标签
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.