Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

python break statements and examples

s = ‘geeksforgeeks’

Using for loop

**for letter in s:

print(letter)**
# break the loop as soon it sees 'e.'
# or 's'

** if letter == ‘e’ or letter == ‘s’:
break**

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The output is :
g
e

s= "geeksforgeeks"

for letter in s :

`if letter == "e" or letter =="s":` 


break

break

print(letter)
ın this code, I want to try the break statement method because ı didn’t understand the break method. And the answer is g and e. In my code, the output is only e. How can ı handle this problem?

>Solution :

Move the ‘print’ statement after the ‘break’ statement if you wish to print both ‘g’ and ‘e’. Here’s an instance:

s = "geeksforgeeks"
for letter in s:
    if letter == "e" or letter == "s":
        break
    print(letter)

// OPTION 2 Better approach

s = "geeksforgeeks"
for letter in s:
    if letter in ('e', 's'):
        break
    print(letter)

OPTION 1
This code will print ‘g’ and then exit the loop without printing the letter ‘e’ when it encounters the letter ‘e’.

OPTION 2 BETTER APPROACH
This version utilizes a tuple to determine whether the current letter is ‘e’ or’s’. This makes the code easier to read and shorter.
Also, it is generally recommended to use parentheses to group values within the ‘in’ operator to make it clear that multiple values are being evaluated.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading