Tải bản đầy đủ (.pdf) (3 trang)

039 break statements tủ tài liệu training

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (370.22 KB, 3 trang )

Python break, continue and pass statements
In this lesson, we are going to learn to use break, continue and pass statements to alter the flow of a loop.

break statement
The break statement terminates the loop containing it. It’s really useful statement and commonly used by the
programmers.
Here is the syntax of break statement:
break

Let’s look at an example that uses the break statement in a for loop.
In [1]: #The use of 'break' statements with "for" loops.
number = 0
for number in range(10):
number = number + 1
if number == 5:
break
# break here
print('Number is ', number)
print("Outside of the loop")
Number is
Number is
Number is
Number is
Outside of

1
2
3
4
the loop


The Complete Python 3 Programming Course: (Beginner to Advanced)


In [2]: number = 0
for number in range(10):
number = number + 1
if number == 5:
#break
pass
print('Number is ' + str(number))
print("Outside of the loop")
Number is 1
Number is 2
Number is 3
Number is 4
Number is 5
Number is 6
Number is 7
Number is 8
Number is 9
Number is 10
Outside of the loop
In [3]: #We know this loop from the "while" loops lesson.
i=1
while (i < 20):
print("Number is ",i)
i +=1
Number
Number
Number

Number
Number
Number
Number
Number
Number
Number
Number
Number
Number
Number
Number
Number
Number
Number
Number

is
is
is
is
is
is
is
is
is
is
is
is
is

is
is
is
is
is
is

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

In [5]: #The use of 'break' statements with "while" loops.
i=1
while (i < 10):

print("Number is ", i)
if (i == 5):
break
i +=1
Number
Number
Number
Number
Number

is
is
is
is
is

1
2
3
4
5

The Complete Python 3 Programming Course: (Beginner to Advanced)


In [6]: while True: # How can we stop an infinite loop?
name = input("Please enter your name:(You can press 'q' button to exit the p
rogram!):")
if (name == "q"):
print("The program is terminated...")

break #break here
print(name)
Please enter your name:(You can
John
Please enter your name:(You can
Alex
Please enter your name:(You can
Omer
Please enter your name:(You can
The program is terminated...

press 'q' button to exit the program!):John
press 'q' button to exit the program!):Alex
press 'q' button to exit the program!):Omer
press 'q' button to exit the program!):q

This is the end of break statement.
Let's look at the continue statement.
In [ ]:

The Complete Python 3 Programming Course: (Beginner to Advanced)



×