Write a Python function that takes two parameters: the first a list of strings and the second a single string. The function should return True or False depending on whether the string is in the list or not. For example, if the list contains eggs, milk, bananas, and the second parameter is pumpkin, the function should return False. Thank you.
Python code for above scenerio is:
#code
def my_fun(fruits,str): //function to check the condition
res=False //declaring a boolean variable
for x in fruits: //traversing the entire list
if(x==str): //checking whether string is present in list or
not
res= True
break //break the loop if variable has become true
else:
res= False
return res //returning true or false as output
fruits = ['eggs', 'milk', 'bananas']
print(my_fun(fruits,'pumpkin'))
In above code fruits is a list and str is string which needs to be matched with list items.Then inside my_fun() we are traversing entire list with for loop and checking whther any list item matches given string str. If it matches we make the res variable true and break the loop from there and if it does not match any item of list then we make res variable as false and at last we are returning res variable.
Then we are creating a list fruits with items given in question
fruits = ['eggs', 'milk', 'bananas']. Then we call function
my_fun() with two parameter a list fruits and second desired string
and then print the result we get from function.
I am attaching a screenshot of my compiler as well as expected output for proper indentation.
Get Answers For Free
Most questions answered within 1 hours.