1

我目前正在使用 for 循环。它遍历一堆命令,最后,我希望它打印一些东西。在这个 for 循环中,是一个 if-else 语句。

我使用 break 来中断 if- 语句,然后它直接进入 else 部分。

for x in list:
   if x is 1:
      do a bunch of commands
      break
   else:
      do a bunch of other commands
print 'Success'

我需要 print 语句留在 If 循环中,所以它是有条件的,但在 for 循环之外,所以它不会重复很多次。有任何想法吗?

我希望它仅在 x 不等于 1 时打印“成功”。但最后只有一次。

4

3 回答 3

2

你可以使用一个标志——一个你设置的变量来指示一个事件的发生(在这种情况下,else分支已经到达)。

success = False
for x in list:
   if x is 1:
      do a bunch of commands
      break
   else:
      do a bunch of other commands
      success = True

if success:
    print 'Success'

这里发生的情况是,else可能会在循环中多次到达案例,将成功变量设置为True(可能)多次。最后的if语句检查标志是否True在末尾,因此'Success'最多打印一次。

于 2013-04-05T21:57:41.933 回答
2

在这种情况下你不需要一个标志,python 有你覆盖,使用for else

for x in list:
  if x is 1:
      # do a bunch of commands
      break
  else:
      # do a bunch of other commands
else:
    # only if we didn't break from the loop (no 1 in the list)
    print 'Success'  
于 2013-04-05T22:36:29.173 回答
0

必须设置标志

标志 = 0

def findlength(s): length = len(s) for p in password: if(length >= 6): flagA = 1 else: flagA = 0

return flagA

def findupper(u): for p in password: if(p.isupper() == 1): flagB = 0

    else:
        flagB = 1

return flagB

def findlower(l): for p in password: if(p.islower()): flagC = 0

    else:
        flagC = 1

return flagC

def findnumber(d): for p in password: if(p.isdigit()): flagD = 1

    else:
        flagD = 0
return flagD
于 2016-12-03T04:58:18.137 回答