0
python intentation (for , if)
fruits=["apple","bannana","cherry"] for x in fruits: if x=="bannana": break print (x) print(x) in this code first print (x) prints apple as expected but second one prints bannana which i couldn't see through please help i'm new to programming
3 Answers
+ 4
because while looping over fruits a new variable x was created globally , now when x variable holds value as "bannana", loop breaks and you exist out of for loop and the final value that x is holding is still "bannana" , which you print at the end.
+ 2
If your aim is to remove the banana from the list.
then, why not use >>>
fruits = ["apple","banana","cherry"]
fruits.remove("banana")
print(fruits)
0
you could also build a new filtered list:
filtered_fruits = [x for x in fruits if x!="bannana"]
print(filteted_fruits)
# output: ["apple","cherry"]
if you only want if list contains an element:
print("found" if "bannana" in fruits else "not found")
...
your code print all items of fruits until it encounter an item with value "bannana", in wich case it break (stop iterating) the loop, then it print the last value wich was assigned to x: "bannana".
what are you trying to achieve exactly?