Reputation: 493
I want to check if the number entered by the user is same with the number in the list and the way I select the item in the list using for loop to compare with the number is not working. It's like it just loop through the first item in the list. Even when I type 43(example), it still print (43 is available in the list), I thought the first item is 65, which will not be same with 43.
ARR = [65,75,85,95,105]
def check_number ():
NUM = int (input ("Please enter the number you want to check with"))
for x in range (len (arr)):
check == ARR [x]
if check == ARR [x]:
print (NUM,"is available in the list")
else:
print (NUM,"is not available is the list")
check_number ()
Upvotes: 1
Views: 1098
Reputation: 543
There is no need to use loop
for comparison because it traverse
and compare the number
with list
. It was bit lengthy process instead of it you can use in
for comparison between number
and list
. Code for the same scenario was stated below:-
# Declared List named 'ARR'
ARR = [65,75,85,95,105]
# Declaration of 'check_number()' function for checking whether Number is Present in list or not
def check_number ():
# User imput of 'Number' for Comparision
NUM = int (input ("Please enter the number you want to check with:- "))
# If 'Number (NUM)' is present in 'List (ARR)'
if NUM in ARR:
print (NUM, "is available in the list")
# If 'Number (NUM)' is not present in 'List (ARR)'
else:
print (NUM, "is not available is the list")
check_number()
# Output_1 for the above code is given below:-
Please enter the number you want to check with:- 45
45 is not available is the list
# Output_2 for the above code is given below:-
Please enter the number you want to check with:- 65
65 is available in the list
Upvotes: 1
Reputation: 3663
A much better of checking whether a value (any hashable value including numbers and strings) is a member of a list is to use Python's built-in set
type:
arr = set([65, 75, 85, 95, 105])
def check_number():
num = int (input ("Please enter the number you want to check with"))
if num in arr:
print (num, "is available in the list")
else:
print (num, "is not available is the list")
check_number ()
It is both more time-efficient for larger data sets, and more idiomatic.
Upvotes: 2
Reputation: 149
You can use the in
keyword for comparison.
ARR = [65,75,85,95,105]
def check_number ():
NUM = int (input ("Please enter the number you want to check with"))
if NUM in ARR:
print(NUM, ' is available in this list')
else:
print(NUM, ' is not available in this list')
check_number()
Upvotes: 1
Reputation: 412
You can simply do
ARR = [65,75,85,95,105]
def check_number ():
NUM = int (input ("Please enter the number you want to check with"))
if NUM in ARR:
print (NUM,"is available in the list")
else:
print (NUM,"is not available is the list")
check_number ()
Using in
to check if an array contains an element is the "pythonic" way to do it.
Upvotes: 1