1️⃣ break
The break statement is used to break the loop and the execution flow will come out of the loop. Lets implement break statement to control while loop:
Scenario-1: break statement using while loop
Mango Shop Implementation: Lets consider we have 100 mangoes in a variable ‘mangoes’. Write python code such that user will enter how much mangoes he want to purchase. Then calculate the stock & provide mangoes to user. User should know availability of mangoes present at the shop during each purchase.
Conditions:
User can shop mangoes multiple times till the stock becomes zero or insufficient.
User can stop purchase whenever he want to stop.
Out of stock: when user purchases all mangoes,he should see the message of out of stock.
Insufficient stock: If user enters number which is higher than stock mangoes then also he should see the message of Insufficient mango stock.
💻 Solution:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | # lets define mangoes variable with 100 mangoes
mangoes = 100
howmuch = int(input(f'how much mangoes do you want ? (stock:{mangoes} mangoes) :'))
while mangoes > 0:
mangoes -= howmuch
print(f'{howmuch} mangoes taken out and {mangoes} mangoes remaining')
print('---------------------------------------------')
repeat = input(f'Do you want to purchase again? (Y/N):')
if mangoes <= 0 :
print('Sorry Mangoes are Out of Stock !')
break
if repeat == 'Y':
howmuch = int(input(f'how much mangoes do you want ? (stock:{mangoes} mangoes) :'))
if howmuch > mangoes:
print(f'Sorry Insufficient Stock, Please try again! stock: {mangoes} mangoes)')
break
else:
break
print('Thank you for shopping with us !')
|
✅ Output:
how much mangoes do you want ? (stock:100 mangoes) :50
50 mangoes taken out and 50 mangoes remaining
---------------------------------------------
Do you want to purchase again? (Y/N):Y
how much mangoes do you want ? (stock:50 mangoes) :50
50 mangoes taken out and 0 mangoes remaining
---------------------------------------------
Do you want to purchase again? (Y/N):Y
Sorry Mangoes are Out of Stock !
Thank you for shopping with us !
Scenario-2: break statement using for loop
We have list containing random numbers, we just want to print the odd numbers sequentially.
condition: If we get any even number while iteration, we just want to break the loop.
💻 Example:
1 2 3 4 5 | my_numbers=[1,5,3,7,3,2,5,6]
for num in my_numbers:
if num%2==0:
break
print(num)
|
✅ Output:
1
5
3
7
3