Home > other >  How do I check if a number is in an array from an input in python?
How do I check if a number is in an array from an input in python?

Time:06-23

Newbie here, why does it show a False value when clearly 5 is in the array. output below

output

arr = []

hidden_number = 5
bool = hidden_number in arr

no1 = int(input('number: '))
no2 = int(input('number: '))

arr.append(no1)
arr.append(no2)

print(arr)
print(bool)

CodePudding user response:

Because it is not when you ask the question.

Let us break it down, you create the array arr and define hidden_number as 5. But you do not add it to the array arr

arr = []

hidden_number = 5

The you ask the question if hidden_number is in arr:

bool = hidden_number in arr

As arr at this point is an empty array, the result of the question will be false.

Then you request the two numbers and add them to the list

no1 = int(input('number: '))
no2 = int(input('number: '))

arr.append(no1)
arr.append(no2)

You do not ask again if hidden_number is in arr so therefore the value of bool does not change and remain false.

So when you print arr will show that it contains [1, 5] but bool will still be false as you did not change it.

print(arr)
print(bool)

The bool hidden_number in arr will not automatically update as you add numbers to arr.

To change to what you want to achieve you need to do this

arr = []

hidden_number = 5

no1 = int(input('number: '))
no2 = int(input('number: '))

arr.append(no1)
arr.append(no2)

doesArrContainsHiddenNumber = hidden_number in arr

print(arr)
print(doesArrContainsHiddenNumber)

Also please do not use the name bool for a variable as that is what the type of the value is and can be used in type hints.

CodePudding user response:

The value of your bool is set before all of the other elements have been added into the array so, it prints false because at point there are no other numbers in the array . Instead you should check for the hidden number in the array after all the other numbers have been added below is the fixed code.

arr = []

hidden_number = 52

no1 = int(input('number: '))
no2 = int(input('number: '))

arr.append(no1)
arr.append(no2)

bool = hidden_number in arr

print(arr)
print(bool)
  • Related