根据收到的参数执行操作

2024-04-29 12:25:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个api,它接受两个参数“a”和“b”。在接收到参数后,它检查它们是否存在,并根据接收到的参数执行一些操作。下面是一些psudo代码。你知道吗

args = get.parameters

if "a" in args:
    print "x" # execute "x"
if "b" in args:
    print "y" # execute "y"
if both exists:
    print "x" # execute "x"

最好的办法是什么?你知道吗


Tags: 代码inapiexecute参数getifexists
3条回答

根据您提供的有限信息,我首先检查ab是否存在。然后出现anot bbnot a。这样你就不会错过任何条件。你知道吗

if 'a' in args and 'b' in args:
    print "x" # execute "x"
elif "a" in args:
    print "x" # execute "x"
elif "b" in args:
    print "y" # execute "y"
else:
    print 'ERROR need "a" or "b"'

我也不明白为什么不使用if-elif-else而不是多个ifs。这些应该是或条件之一。你知道吗

import sys
args = sys.argv;
if len(args) > 1:
    args = args[1:]
    if "a" in args and "b" in args: print "x"
    elif "a" in args: print "x"
    elif "b" in args: print "y"

根据评论中提出的要求,我将这样做:

if "a" in args:
    print "x"
elif "b" in args:
    print "y"
else:
    raise ValueError("must specify at least a or b")

执行"a" in args and "b" in args检查没有意义,因为要执行的操作与只有"a"的情况相同。注意elif,它确保只有在第一次检查失败时才执行第二次检查。你知道吗

相关问题 更多 >