0

So I am relatively new to python, not sure what is wrong here? I am sure it is a basic thing that I am missing but not sure what it could be, below is the code to find a matching target to any of the numbers in the list, which should work according to me but doesn't.

def abc(target,list1):
    for a in list1:
        if a == target:
            return a
        else:
            return 0
def main():
    target = input("enter target")
    list1 = []
    n = int(input("Enter number of elements : ")) 
    for i in range(0, n): 
        ele = input() 
    list1.append(ele)

g = abc(target,list1)
print(g)

if __name__== '__main__':
    main()

Below is the output which obviously returns 0 as the code does not work:

Enter target7
Enter number of elements : 4
5
6
7
8
0

should it not return 7 as the value in the list matches the target

2 Answers2

0

As stated in the comments, your logic in abc() is off.

This should work as expected:

def abc(target, list1):
    return target if target in list1 else 0


def main():
    target = int(input("enter target"))
    list1 = []
    n = int(input("Enter number of elements : "))
    for i in range(0, n):
        list1.append(int(input()))
    print(abc(target, list1))


if __name__ == '__main__':
    main()

Output:

Enter number of elements : 4
5
6
7
8
7
baduker
  • 19,152
  • 9
  • 33
  • 56
0

You had the wrong indentation:

def abc(target,list1):
    for a in list1:
        if a == target:
            return a
        else:
            return 0


def main():
    target = input("Enter target: ")
    list1 = []
    n = int(input("Enter number of elements: "))
    for i in range(0, n):
        ele = input(f"Enter element #{i+1}: ")
        list1.append(ele)

    g = abc(target,list1)
    print(g)


if __name__== '__main__':
    main()
Enter target: 2
Enter number of elements: 1
Enter element #1: 2
2
Chiel
  • 1,865
  • 1
  • 11
  • 24