In the context of this exercise, within a Python for loop, does, or should, every if statement have an else statement?
Answer
No, for if statements in general, whether or not they are part of a for loop, they do not always need to be followed by an else statement. (This may be helpful to keep in mind for this exercise!)
If nothing else should happen if the condition is False, then it might make sense to exclude the else entirely. This not only saves space, by reducing the code by a few lines, but can also potentially speed up a program, by moving to the next iteration of a loop immediately instead of running additional code per iteration.
Not necesarily. Sometime you just want to check one condition. Take as example that you want to prepare a coffe with milk. Supposing you already have the coffe, you will go and check in your fridge if you have milk. If yes you add it. Anyother result you do nothing.
Have you given the problem another attempt? The word ācontainsā indicates membership. Is there a common Python keyword that might indicate the same thing? in comes to mind. We can use it in an if statement, or in a logical expression.
if x in y:
or
return x in y
In that capacity we could call in a membership operator.
The only way I can offer individual support is in a topic, not a DM. This permits public involvement, and perhaps correction of anything I may have stated. Iām open to that, and willing to bear that scrutiny in the aim of correctness. To my mind, this is better for you.
hey mtf, I am confused by this code in this exercise, I don;t seem to get it the line āfor character in wordā in the correct answer, see below. I thought when we iterate a list, we iterate the entire list, but word is an argument/input, how can we assign a variable to an argument?? shouldnt the code be like this:
correct answer:
def letter_check(word, letter):
for character in word:
if character == letter:
return True
return False
my answer:
def letter_check(word, letter):
for word in letter_check:
if word == letter:
print (True)
else:
print(False)