In if-elif-else, the if statement is TRUE yet the else statement is getting executed
Question:
string = "aabbcc"
count = 3
while True:
if string[0] == 'a':
string = string[2:]
elif string[-1] == 'b':
string = string[:2]
else:
count += 1
break
print(string)
print(count)
The output for the program is ‘bbcc’ and 4. But I don’t understand why the else statement is running when the IF statement is true. Please help.
Answers:
The value of string gets replaced, then the loop continues. The second iteration, the string doesn’t start with "a" anymore. It also doesn’t end with "b". So you get 3+1 and "bbcc".
you are using while loop remember.
string = "aabbcc"
count = 3
while True:
if string[0] == 'a':
string = string[2:]
# here the value of string is assigned as bbcc
elif string[-1] == 'b':
string = string[:2]
else:
count += 1
break
print(string)
print(count)
After the vaiable string is assigned by bbcc, the loop runs again and this time string[0] != “a” and is equal to “b”. Therefore the statement in else is executed and the count becomes 4 and the loop breaks because of the break statement
There is no bug in the code And the code is running fine as it should be.
string = "aabbcc"
count = 3
while True:
if string[0] == 'a':
string = string[2:]
elif string[-1] == 'b':
string = string[:2]
else:
count += 1
break
print(string)
print(count)
The output for the program is ‘bbcc’ and 4. But I don’t understand why the else statement is running when the IF statement is true. Please help.
The value of string gets replaced, then the loop continues. The second iteration, the string doesn’t start with "a" anymore. It also doesn’t end with "b". So you get 3+1 and "bbcc".
you are using while loop remember.
string = "aabbcc"
count = 3
while True:
if string[0] == 'a':
string = string[2:]
# here the value of string is assigned as bbcc
elif string[-1] == 'b':
string = string[:2]
else:
count += 1
break
print(string)
print(count)
After the vaiable string is assigned by bbcc, the loop runs again and this time string[0] != “a” and is equal to “b”. Therefore the statement in else is executed and the count becomes 4 and the loop breaks because of the break statement
There is no bug in the code And the code is running fine as it should be.