-1

So I've been trying to make a program "how to find if a value is stored in a variable or not". I did this but it doesn't work, it always says that it is not found even tho its inside the variable

a = [2,5,7,9,11]

cari = input("Input the value : ")
ketemu = False
for i in range(0, len(a)):
    if cari == a[i]:
        ketemu = True
        break

if ketemu:
  print("Value: ", cari, "found it")
else:
  print("Value: ", cari, "not found")
Wenky
  • 23
  • 5

5 Answers5

0

You need to convert the result of input from string to int.

cari = int(input("Input the value : "))
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
  • Thank you for your answer, tried it and it worked. Why is it have to be like that if you can please answer me ? Appreciate it a lot :D – Wenky Oct 12 '21 at 18:07
  • @Wenky `input` returns a string and your list contains ints. An `int` will never be equal to a string. – Unmitigated Oct 12 '21 at 18:08
  • It is like that because python does not make assumptions for you. You might want to have digits as strings. *Explicit is better than implicit* – mozway Oct 12 '21 at 18:10
0

It is because, you written only input() which is taken as string when you enter the input. For example, if you put 5 as input, cari will be '5' and not 5. So change it from input() to int(input()). Code:

a = [2,5,7,9,11]

cari = int(input("Input the value : "))
ketemu = False
for i in range(0, len(a)):
    if cari == a[i]:
        ketemu = True
        break

if ketemu:
  print("Value: ", cari, "found it")
else:
  print("Value: ", cari, "not found")
0

Here's a slight modification to your code that will result the correct out come.

a = [2,5,7,9,11]

cari = int(input("Input the value : "))
ketemu = False
for i in range(0, len(a)):
    if cari == a[i]:
        ketemu = True
        break

if ketemu:
  print(f"Value: {cari} found it")
else:
  print(f"Value: {cari} not found")

pyzer
  • 122
  • 7
0

You missed to add the datatype in which you get your answer. If you're getting integer then put int(input()) and when you get string values then put str(input()) according to your query:

cari = int(input("Input the value : "))
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
-1

You can simplify the checking loop.

a = [2,5,7,9,11]
cari = int(input("Input: "))
if(cari in a):
    print(f"{cari} found")
else:
    print(f"{cari} NOT found")
ninjajosh5
  • 39
  • 5