第十三章 break报错

break报错为什么?

def yourName(Name):
    if Name == "sunpu":
        print"    CCCC         A        RRRRR      TTTTTTT      EEEEEE    RRRRR    "
        print"   C     C      A A       R    R        T         E         R    R   "
        print"  C            A   A      R    R        T         EEEE      R    R   "
        print"  C           AAAAAAA     RRRRR         T         E         RRRRR    "
        print"   C     C   A       A    R    R        T         E         R    R   "
        print"    CCCC    A         A   R     R       T         EEEEEE    R     R  "
    else:
        break
name = raw_input("Enter your name: ")

yourName(name)

网上解释

 

问题:

in the following python code:


narg=len(sys.argv)
print "@length arg= ", narg
if narg == 1:
        print "@Usage: input_filename nelements nintervals"
        break

I get:


SyntaxError: 'break' outside loop

Why?

回答1:

Because break cannot be used to break out of an if - it can only break out of loops. That's the way Python (and most other languages) are specified to behave.

What are you trying to do? Perhaps you should use sys.exit() or return instead?

 

回答2:

Because the break statement is intended to break out of loops. You don't need to break out of an if statement - it just ends at the end.

 

回答3:

Because break can only be used inside a loop. It is used to break out of a loop (stop the loop).

 

回答4:

break breaks out of a loop, not an if statement, as others have pointed out. The motivation for this isn't too hard to see; think about code like


for item in some_iterable:
    ...
    if break_condition():
        break 

The break would be pretty useless if it finished the if block rather than breaking the loop. Consider that I cannot think of a case that you'd use break any way but inside an if statement to break the loop the if statement is in.

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值