Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

How do I make a define function in Python that cloud check a list?

+5 votes
asked Feb 1, 2023 by YC72909 (340 points)
edited Feb 1, 2023 by YC72909
Hi,

I wanted to make a define function in Python that could check for a 7 in a list. If the list has a 7, I want to function to return a print statement that says that the item is in the list. I set the parameter to the variable that represented the number in the list. E.g. this is what I did for number 1 in the list:

def check(seven):
    if seven == 7:
        print("Seven is in the list.")
    else:
        print("Seven is not in the list.")
print(check(num1))

Thank you,

@YC72909 Scratch & Online GDB

2 Answers

0 votes
answered Feb 2, 2023 by Michael Lopardo (140 points)
def check(seven):
    if 7 in seven:
        print('Seven is in the list')
    else:
        print('Seven is not in the list')
commented Feb 2, 2023 by YC72909 (340 points)
Thank you for your help.
0 votes
answered Feb 2, 2023 by audiomct (140 points)

While using a return and print statement in the same function can be done, it's a bit confusing, particularly in the same if/else control block. I'm not sure if the seven parameter is supposed to represent your list but I would approach the solution like this.

llist = [1,2,3,4,5,6,7,8,9]

def check(llist):
    for x in llist:
        if(x == 7):
            return "Seven is in the List"
    return "Seven is not in the list"
    
seven = check(llist)

print(seven)

- I use a for loop inside the function, where x takes on each successive value in the llist, which is passed as a parameter.

- The if condition is inside the loop and the return string for finding seven is in that scope as well. Once a return statement is executed, it will automatically exit the function, so we don't need to worry about the 2nd return statement running in this case.

- In case 7 is not found, the second return string, which is outside the for loop scope, is sent out of the function.

- Whichever return statement is sent out of the function and stored in the variable seven, can then be passed to print and the string will be output.

 

commented Feb 2, 2023 by YC72909 (340 points)
sure, I'll try.
commented Feb 2, 2023 by YC72909 (340 points)
Thank you, it worked. Also thank you for your explanation.

YC72909 Scratch & Online GDB
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...