I am learning to create a block of 'if' statements to check certain conditions and I want them to identify if the list has empty quote marks in it.
so for example:
favourite_fruit = []
if len(favourite_fruits) == 0:
print('Fruits are an important part of one's diet')
###This code works which is great as long as the list is empty in terms of it's length.
if the list isn't empty and they have something like: 'apple' in it, but another fruit like 'dates' is missing, then I would tell it to say:
if 'dates' not in favourite_fruit and len(favourite_fruit) != 0:
print ('Have you tried Dates? They are high in fibre, a good source of which, can help prevent constipation by promoting bowel movements.')
But the problem is if I type:
favourite_fruit = ['']
The length of this list is 1 but there is nothing in it so it will print out the dates quote but not the 'fruits are important' quote.
Is there a way for me to get python to identify there is nothing actually written in the list?
I am pretty much a beginner so I am still learning
Here is what I have tried though:
favourite_fruit = ['']
if 'dates' not in favourite_fruit and len(favourite_fruit) != 0 and favourite_fruit != "" and favourite_fruit != "\"\"" and favourite_fruit != '' and favourite_fruit != '\'\'':
print ('Have you tried Dates? They are high in fibre, a good source of which, can help prevent constipation by promoting bowel movements.')
But it still isn't working.
CodePudding user response:
Wondering why there are empty strings in the list.
Anyway, assuming you want to ignore empty strings, you may filter your list first. In Python, this is typically achieved with the following syntax, which is called a list comprehension:
favourite_fruit = [f for f in favourite_fruit is f != ""]
['']
becomes []
(empty list), ['apple', '']
becomes ['apple']
, etc. You get the idea.
Sidenote: in Python, a non-empty list is truthy and an empty list is falsy, so if len(favourite_fruits) == 0
can be written if favourite_fruits
.
CodePudding user response:
Is there a way for me to get python to identify there is nothing actually written in the list?
Empty strings are false, so all you need to do is check if any
of the items in favourite_fruit
is true.
any([]) => False
any(['']) => False
any(['dates']) => True