- The Python Apprentice
- Robert Smallshire Austin Bingham
- 64字
- 2021-07-02 22:16:55
if...elif...else
For multiple conditions you might be tempted to do something like this:
>>> if h > 50:
... print("Greater than 50")
... else:
... if h < 20:
... print("Less than 20")
... else:
... print("Between 20 and 50")
...
Between 20 and 50
Whenever you find yourself with an else-block containing a nested if statement, like this, you should consider using Python's elif keyword which is a combined else-if.
As the Zen of Python reminds us, Flat is better than nested:
>>> if h > 50:
... print("Greater than 50")
... elif h < 20:
... print("Less than 20")
... else:
... print("Between 20 and 50")
...
Between 20 and 50
This version is altogether easier to read.
推薦閱讀
- Learning Scala Programming
- Python數(shù)據(jù)分析基礎(chǔ)
- Bulma必知必會(huì)
- Mastering ROS for Robotics Programming
- C++從入門(mén)到精通(第5版)
- 從零開(kāi)始學(xué)C#
- HTML5秘籍(第2版)
- Spring技術(shù)內(nèi)幕:深入解析Spring架構(gòu)與設(shè)計(jì)原理(第2版)
- MATLAB GUI純代碼編寫(xiě)從入門(mén)到實(shí)戰(zhàn)
- PHP與MySQL權(quán)威指南
- Practical Predictive Analytics
- Mastering Unreal Engine 4.X
- XML程序設(shè)計(jì)(第二版)
- 金融商業(yè)數(shù)據(jù)分析:基于Python和SAS
- 透視C#核心技術(shù):系統(tǒng)架構(gòu)及移動(dòng)端開(kāi)發(fā)