首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >语句,用于嵌套和非嵌套if。

语句,用于嵌套和非嵌套if。
EN

Stack Overflow用户
提问于 2016-01-28 04:54:34
回答 2查看 654关注 0票数 1

我想知道是否有任何方法为多个级别的if语句提供一条其他语句。

我将详细说明:

代码语言:javascript
复制
if <condition-1>:
    if <condition-2>:
        do stuff
    elif <condition-3>:
        do other stuff
else: #if either condition-1 or all nested conditions are not met
    do some other thing

我知道通过添加一个带有“做其他事情”的函数来解决这个问题,然后用嵌套的else和toplevel调用它,但是我想知道是否有什么方法可以让这个看起来更干净一些。

预先谢谢,欢迎有任何想法。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-01-28 04:56:57

不,不是真的。这正是python不希望您做的事情。它更喜欢保持可读性和清晰性,而不是“浮华”技巧。您可以通过组合语句或创建“标志”变量来做到这一点。

例如,你可以

代码语言:javascript
复制
if <condition-1> and <condition-2>:
    # do stuff
elif <condition-1> and <condition-3>:
    # do other stuff
else:
    # do some other thing

或者,如果您出于某种原因不想继续重复条件1(检查成本很高,更清楚地不继续重复它,或者您只是不想继续键入它),我们可以这样做。

代码语言:javascript
复制
triggered_condition = False
if <condition-1>:
    if <condition-2>:
        triggered_condition = True
        # do stuff
    elif <condition-3>:
        triggered_condition = True
        # do some other stuff
if not triggered_condition:
    # do some other thing

如果在函数中使用这一点,我们甚至可以跳过标志。

代码语言:javascript
复制
if <condition-1>:
    if <condition-2>:
        # do stuff and return
    elif <condition-3>:
        # do some other stuff and return
# do some other thing
# if we got here, we know no condition evaluated to true, as the return would have stopped execution
票数 2
EN

Stack Overflow用户

发布于 2016-01-28 05:06:17

有几种方法不是特别直观/可读的.但工作:

在这个例子中,我们利用了for ... else ...语法。任何成功的情况都应该中断。

代码语言:javascript
复制
for _ in [1]:
    if <condition>:
        if <condition>:
            # where ever we consider ourselves "successful", then break
            <do stuff>
            break
        elif <condition>:
            if <condition>:
                <do stuff>
                break
else:
    # we only get here if nothing considered itself successful

另一种方法是使用try ... else ...,其中“成功”的分支应该会引发异常。

这些不是特别好,是不推荐的!

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35053136

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档