在 Python 逻辑中,嵌套的 Ifs 什么时候比 If-ands 更有用?[已结束]

When would nested Ifs be more useful than If-ands in Python logic? [closed]

提问人:Physics 提问时间:5/23/2023 更新时间:5/23/2023 访问量:48

问:


想改进这个问题吗?更新问题,以便可以通过编辑这篇文章来用事实和引文来回答。

6个月前关闭。

我们什么时候使用嵌套的 Ifs 和 If-ands?

例如,如果我想编写一个代码:

如果(收入低于截止): 如果(加拿大公民? 接受社会救助

我什么时候会像上面一样使用嵌套的 IF 而不是 If-and? 起初,我以为只有当内部语句的计算结果为 true 时,我们才想访问它,但使用 IF-,如果内部语句的计算结果为 false,您仍然可以跳过它。

python if-statement 嵌套 逻辑

评论

0赞 Codist 5/23/2023
这通常是一个可读性问题
2赞 Barmar 5/23/2023
当存在多个嵌套条件时,通常使用嵌套。if

答:

0赞 Artem Strogin 5/23/2023 #1
if cond_1 is True and cond_2 is True:
  do_this()
...

if cond_1 is True:
  if cond_2 is True:
    do_this()
  else:  # cond_2 is False but cond_1 is still True
    do_other()
...

评论

0赞 Physics 5/23/2023
哦,我现在明白了!谢谢你的例子,我现在看到了区别。