list =[1,2,3,4] count = 1; for i inlist: 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 instr: if i == 'o': break print(i);
输出:
p y t h
示例 3:使用 While循环break语句
i = 0; while1: print(i," ",end=""), i=i+1; if i == 10: break; print("came out of while loop");
输出:
0123456789 came out of while loop
例 3
n=2 while1: 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 0for 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 0for no?0