Coding in Python: a comprehensive Beginners Guide to Learn the Realms of Coding in Python


Download 1.25 Mb.
Pdf ko'rish
bet28/48
Sana30.01.2023
Hajmi1.25 Mb.
#1140552
1   ...   24   25   26   27   28   29   30   31   ...   48
Bog'liq
Coding in Python A Comprehensive Beginners Guide to Learn the Realms

The Break Keyword
If you want to exit the loop without running the code that remains, you can
add a break statement to the program. The break statement tends to redirect
the flow of a program and allow you to execute the code of your choice.
pgm = input("Please enter the name of the office item that you have
purchased:")
pgm += "\n(You have to enter 'q' to exit the program.) "
while True:
item = input(pgm)
if item == 'q':


break
else:
print("I have purchased the " + item.title())
= RESTART: C:/Users/saifia computers/Desktop/sample.py
Please enter the name of the office item that you have purchased:table
table
(You have to enter 'q' to exit the program.)
I have purchased the
table
(You have to enter 'q' to exit the program.) laptop
I have purchased the Laptop
table
(You have to enter 'q' to exit the program.) computer system
I have purchased the Computer System
table
(You have to enter 'q' to exit the program.) stack of paper.
I have purchased the Stack Of Paper.
table
(You have to enter 'q' to exit the program.) air conditioner
I have purchased the Air Conditioner
table
(You have to enter 'q' to exit the program.) q
>>>
You have another choice as well. Instead of breaking out of the loop, you can
integrate into the block of code a continue statement that will take the code
back to the start after the condition stands tested. See the following
mathematical example.


num = 0
while num < 40:
num += 1
if num %4 == 0:
continue
print(num)
= RESTART: C:/Users/saifia computers/Desktop/sample.py
1
2
3
5
6
7
9
10
11
13
14
15
17
18
19
21
22
23
25


26
27
29
30
31
33
34
35
37
38
39
>>>
You can see that the continue statement returned the code after a pause at the
point Python tested the condition. The num started at 0. I kept the figure
under 40 so the loop ran until 4, checked if the current number is divisible by
4 and then executed the rest of the code because the number was not divisible
by 4. Let us try another example to clear the concept fully.
num = 4
while num < 80:
num += 3
if num %4 == 0:
continue
print(num)
= RESTART: C:/Users/saifia computers/Desktop/sample.py
7
10
13


19
22
25
31
34
37
43
46
49
55
58
61
67
70
73
79
82
>>>

Download 1.25 Mb.

Do'stlaringiz bilan baham:
1   ...   24   25   26   27   28   29   30   31   ...   48




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling