Question
What are some common errors when creating loops?
Answer
Loops can be tricky if you aren’t careful, and can end up crashing your program if they aren’t given conditions that can become False
eventually. Some common issues are:
- Conditions that never possibly become
False
, causing infinite loops and crashing.
- Forgetting to put the colon
:
after the loop’s declaration.
- Not indenting code you want to run inside of a loop
4 Likes
what is the point(logic) of else in the below code:
fruits = [‘banana’, ‘apple’, ‘orange’, ‘tomato’, ‘pear’, ‘grape’]
print ‘You have…’
for f in fruits:
if f == ‘tomato’:
print ‘A tomato is not a fruit!’
print ‘A’, f
else:
print ‘A fine selection of fruits!’
Well, in the code you’ve given there it is unnecessary, but that is being used for practice. If your ‘f’ does not ever equal ‘tomato’ it will print out something different. This is just showing you how the for/if/else works.
I am still not able to grasp
What would be the point of Else in any situation in FOR loop?
In IF loop, it comes in if the IF statement is False. Similarly for WHILE loop, when loop is false, then Else statement is run.
But can a FOR loop be false?
If not what’s the point of putting ELSE block, the code will anyways run the next line of code after the FOR loop.
Thanks in advance for your help
1 Like
Sorry for answering late, but else works in a different way in for loops, the else will run after the for loop is completed, except when you exit the loop using break. For example:
list = ["Apple", "Banana", "Orange"]
for item in list:
print(item)
if item == "Banana":
break
else:
print("Fruits")
In this example, the else will never run, because you will always exit the loop through a break statement. Instead, on this example:
list = ["Apple", "Orange"]
for item in list:
print(item)
if item == "Banana":
break
else:
print("Fruits")
You will always go through the else: statement, because there is no “Banana” item in the list, so the loop will complete.