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**
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.