有时我会把if中的长条件分解成几行。最明显的方法是:
if (cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
视觉上不是很吸引人,因为动作与环境融为一体。然而,这是使用4个空格的正确Python缩进的自然方式。
目前我正在使用:
if ( cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
但这不是很漂亮
你能推荐另一种方法吗?
(我对标识符进行了轻微修改,因为固定宽度的名称不能代表真实代码——至少不能代表我遇到的真实代码——并且会掩盖示例的可读性。)
if (cond1 == "val1" and cond22 == "val2"
and cond333 == "val3" and cond4444 == "val4"):
do_something
这适用于“和”和“或”(重要的是它们位于第二行的第一位),但对于其他较长的条件就更不适用了。幸运的是,前者似乎是更常见的情况,而后者往往很容易用临时变量重写。(这通常不难,但在重写时保持“和”/“或”的短路可能很难或不那么明显/可读。)
由于我在你的关于C++的博客文章中发现了这个问题,我将补充我的C++风格是相同的:
if (cond1 == "val1" and cond22 == "val2"
and cond333 == "val3" and cond4444 == "val4") {
do_something
}
如果我们的if-anelse条件必须在其中执行多个语句,那么我们可以像下面这样写。每当我们有if-else示例时,其中都有一个语句。
谢谢为我工作。
#!/usr/bin/python
import sys
numberOfArgument =len(sys.argv)
weblogic_username =''
weblogic_password = ''
weblogic_admin_server_host =''
weblogic_admin_server_port =''
if numberOfArgument == 5:
weblogic_username = sys.argv[1]
weblogic_password = sys.argv[2]
weblogic_admin_server_host =sys.argv[3]
weblogic_admin_server_port=sys.argv[4]
elif numberOfArgument <5:
print " weblogic UserName, weblogic Password and weblogic host details are Mandatory like, defalutUser, passwordForDefaultUser, t3s://server.domainname:7001 ."
weblogic_username = raw_input("Enter Weblogic user Name")
weblogic_password = raw_input('Enter Weblogic user Password')
weblogic_admin_server_host = raw_input('Enter Weblogic admin host ')
weblogic_admin_server_port = raw_input('Enter Weblogic admin port')
#enfelif
#endIf