【问题标题】:How to continue from the 'if' statement to the 'elif' in Python?如何从 Python 中的“if”语句继续到“elif”?
【发布时间】:2013-09-03 12:18:15
【问题描述】:

如何从if 语句继续到elif?我希望最终结果是“mybadgr”,但它一直打印出“badgr”。

a = "Badger"
vowels = 'AEIOUaeiou'
flicker = len(a)
if a[flicker - 2] in vowels and a[flicker -1] in'r':
    final = str(a[:flicker-2])+'r'
    flicker = len(str(final))
    #continue the if to elif
elif flicker < 6:
    final = 'My'+final

【问题讨论】:

  • el 中的elif 表示“其他”。只有在之前的 if/elifs 条件为 false 时才会对其进行评估。

标签: python string if-statement python-3.x count


【解决方案1】:

在一组 if - elif - else 语句中,Python 只会执行 一个 套件。返回True 的第一个ifelif 条件决定了选择哪个块;如果没有匹配,则执行else

不要使用elif,而是使用if 来开始一个新区块:

if a[flicker - 2] in vowels and a[flicker -1] in'r':
    final = str(a[:flicker-2])+'r'
    flicker = len(str(final))

if flicker < 6:
    final = 'My'+final

现在它是一个单独的if 套件,将与前面的if 分开测试。

请注意,您不需要使用flicker 从末尾开始索引;负指数达到同样的效果:

if a[-2] in vowels and a[-1] == 'r':
    a = a[:-2] + 'r'

if len(a) < 6:
    a = 'My{}'.format(a)

这实现了相同的结果(尽管只是设置了a),而不需要flicker 长度变量。

【讨论】:

  • 如果闪烁超过 6 会发生什么,你不会得到一个字符串错误
  • @user2699284:你为什么要这么做?
  • @user2699284:如果您的 first if 语句不匹配,但第二个匹配,则很可能尚未设置 final
  • 对不起,我正在重做我的代码以匹配你的冗长回复
  • 顺便说一下,我发布的堆栈溢出代码是我做的一个例子
猜你喜欢
  • 2022-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-03
  • 2016-07-30
  • 2020-10-28
  • 2015-01-16
相关资源
最近更新 更多