python中break语句的用法_Python break语句用法示例

本文概述

break是python中的关键字, 用于将程序控制带出循环。 break语句逐个中断循环, 即在嵌套循环的情况下, 它首先中断内部循环, 然后继续进行外部循环。换句话说, 我们可以说使用break来中止程序的当前执行, 并且控制转到循环后的下一行。

该中断通常用于需要为给定条件中断循环的情况下。

中断的语法如下。

#loop statements

break;

例子1

list =[1, 2, 3, 4]

count = 1;

for i in list:

if i == 4:

print("item matched")

count = count + 1;

break

print("found at", count, "location");

输出

item matched

found at 2 location

例子2

str = "python"

for i in str:

if i == 'o':

break

print(i);

输出

p

y

t

h

示例3:带有while循环的break语句

i = 0;

while 1:

print(i, " ", end=""), i=i+1;

if i == 10:

break;

print("came out of while loop");

输出

0 1 2 3 4 5 6 7 8 9 came out of while loop

例子3

n=2

while 1:

i=1;

while i<=10:

print("%d X %d = %d\n"%(n, i, n*i));

i = i+1;

choice = int(input("Do you want to continue printing the table, press 0 for no?"))

if choice == 0:

break;

n=n+1

输出

2 X 1 = 2

2 X 2 = 4

2 X 3 = 6

2 X 4 = 8

2 X 5 = 10

2 X 6 = 12

2 X 7 = 14

2 X 8 = 16

2 X 9 = 18

2 X 10 = 20

Do you want to continue printing the table, press 0 for no?1

3 X 1 = 3

3 X 2 = 6

3 X 3 = 9

3 X 4 = 12

3 X 5 = 15

3 X 6 = 18

3 X 7 = 21

3 X 8 = 24

3 X 9 = 27

3 X 10 = 30

Do you want to continue printing the table, press 0 for no?0

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值