To check whether an entered value exists in a List - python

This is my simple code. When a User enters a value, it has to be compared with the list I have used and should return the output as required. But when I execute the code and enter a value that is a part of the list, it returns the print statement under the else construct. Please help me with your suggestions
mylist=[1,2,3]
print('Enter the Rank:')
x=input()
if x in mylist:
print('You have passed')
else:
print('Sorry you have failed')

The items in mylist are ints. Input returns a string, so to compare them you need to convert one of them.
Either
x = int(input())
or
if int(x) in mylist

Related

How to give user input in python3

n=input("enter the no:")
check(test_list,n)
def check(test_list,n):
for i in test_list:
if(i==n):
print("yes in a list")
continue
else:
continue
I had written the simple code to check if a no. exists in a list or not, but while taking user input I"m not getting any results after providing input value n.
Why is so?
In your code the first line should be corrected as n=int(input("enter the no:")).
In python it takes the inputs as strings. Think if you are giving the input as 3. Then the variable n stores the value "3"( not the value 3 ). You should need to know 3 == "3" is False.
Therefore, when you are taking the input you should convert that string input to the int. To do that we use int() method. The int() method converts the specified value into an integer number
n=int(input("enter the no:"))
check(test_list,n)
def check(test_list,n):
for i in test_list:
if(i==n):
print("yes in a list")
continue
else:
continue
You were not getting any results because the input() function always returns a string. For this reason, we need to convert it to an Integer before passing it on into the function, and I did with n=int(input()).
n=int(input("enter the no:"))
def check(test_list,n):
for i in test_list:
if(i==n):
print("yes in a list")
continue
else:
continue
check((1,2,3),n)

Loops through a whole list

I have a pretty simple function where the user is asked to input a list of numbers, then a second input for a second number. If any single number in the first argument is larger than the second argument, then it will return True, and if none of the numbers in the first argument in larger, it should return false. Seems simple enough but I'm struggling to get it to loop through the entire list before it returns the boolean value. A new problem I'm having throws up an error and says I'm trying to compare int's to lists with the > operator.
def num_gt(list_num, single_num):
#breakpoint()
for i in list_num :
if i > single_num :
return True
else:
return False
list_num = (input("Please enter list numbers: "))
single_num = (input("Please enter single number: "))
list_num = list(map(int, list_num))
single_num = list(map(int, single_num))
Not sure where I'm goinging wrong here. The inputs get converted to lists of integers, and stepping through it shows its return lists as it should. Any help appreciated
You need to not cast your single num to a list as it is a single value.
Remove the line.
single_num = list(map(int, single_num))
And replace with:
single_num = int(single_num)
Your function is also slightly wrong as it will only check one value then always return. It should instead check all the values and only if all of them are smaller then return false.
def num_gt(list_num, single_num):
#breakpoint()
for i in list_num :
if i > single_num :
return True
return False
Now your function will check all the values and then if none of them return True, it will return False at the end.

How can I check input is integer, while using FOR for RAW_INPUT ..in Python?

I have a task
Print the minimal value from list you entered. First entered value
defines the length of the list. Each next value should be placed in
list one by one. Use operator for.
n is defined before, by input and start_n = 1
def list2_func():
global list2
list2 = []
for i in xrange(start_n, n + 1):
list2.append(raw_input('Enter the %s number: ' % i))
list2_check()
def list2_check():
global start_n
try:
value = int(list2[-1])
except ValueError:
print "Please use only 0-9 keys. Re enter %s number" % len(list2)
start_n = len(list2)
list2_func()
else:
start_n = start_n + 1
Everytime I enter any key which is not passing the try it asks for same value again - which is great. But when I enter my last value (for example n = 4, so 4th value) program asks me again to input. At the end I got 2*n - 1 amount of values - which is not what i want.
Could you please suggest me any another way to check if entered value is a number? Or point the mistake in my code!
I'm using python 2.7.
There are possible errors in your code. You are appending the number multiple times if the check fails. Try the following code which would make sure you are appending single valid value to the list.
def get_value(i):
while True:
number = raw_input('Enter the %s number: ' % i)
try:
value = int(number)
except:
continue
return value
def list2_func():
list2 = []
for i in xrange(start_n, n + 1):
number = get_value(i)
list2.append(number)
you don't need to use the list2_check function :
def list2_func():
list2 = []
i=start_n
while i<n+1:
try:
list2.append(int(raw_input('Enter the %s number: ' % i)))
i+=1
except ValueError:
print "Please use only 0-9 keys. Re enter %s number" % len(list2)
return list2
I also deleted your global variable, as it is preferable to use a return than having global variables. (they may cause issues if you try to have another variable with the same name)
Just played with the code a litle and found the problem. Program was finishing first FOR loop and starting new for loop for every value which didnt passed the try test.
def list2_func():
global list2
list2 = []
for i in xrange(1, n+1):
list2.append(raw_input('Enter the %s number: ' % i))
list2_check()
def list2_check():
try:
value = int(list2[-1])
except ValueError:
list2[-1]= raw_input("Please, use only 0-9 keys" % len(list2))
list2_check()
else:
pass
Now it just asking to replace the wrong value instead of starting for loop again :)
This because you have a recursive function. Each function call the other.
Also, strart_n is modified in each loop (remove else case of try).
Your problem is in the logic used : you add the wrong entered value (via list2.append), then check the list and never delete the last entered value if value is wrong.
So, if you want to keep your code, you juste have to delete the last item in the list when ValueError is raised.
BUT, your code also have many other problems you should resolve :
you use recursion, and it will be easy to crash your program : only enter bad values : each time, you do a new call to "list2_func" inside "list2_func". So with 5 consecutive wrong values we have :
call to list2_func:
call to list2_func:
call to list2_func:
call to list2_func:
call to list2_func:
Of course, python will crash when its max recursion will be reached :)
Another problem is the use of a global variable. It's bad. Only do that if you really need a global var.
Here is one of many solutions existing to your exercise :
def get_list():
"""
Returns an user's entered list.
First entered value defines the length of the list.
Each next value should be placed in list one by one.
"""
wanted_length = None
my_list = []
while wanted_length < 1:
try:
wanted_length = int(raw_input('Please enter the wanted length of the list (int > 0) : '))
except ValueError:
pass
i = 1
while i <= wanted_length:
try:
my_list.append(int(raw_input('Please enther the number %d (int only) : ' % i)))
except ValueError:
pass
else:
i += 1
return my_list
def print_min_with_for(l):
"""
Prints the minimal value from list you entered using operator `for`.
"""
if not l:
print 'List is empty'
return
min_value = None
for i in l:
if min_value is None or i < min_value:
min_value = i
print 'min value in the list is : %d' % min_value
my_list = get_list()
print 'Printed min value in the list should be : %d' % min(my_list)
print_min_with_for(my_list)
Welcome to python BTW ;-)

Multiple IF and ELIF conditionals [Python]

name="admin"
passw="aaa"
itemone="01"
itemtwo="02"
a=input("Enter your username:")
b=input("Enter your password:")
if(a==name)and(b==passw):
print("Welcome.")
c=int(input("Enter Item Code:"))
if(c==itemone):
print("Name: ID")
elif(c==itemtwo):
print("Name: Mirror")
else:
print("Item not found. Try again.")
else:
print("Username/Password is incorrect.")
exit()
when "01" or "02" is entered, the program ignores all the other codes and directs to "item not found. try again."
I finally got it to work! Thank you!!!
You are taking the input and casting it to an integer, then checking if it is equal to a string. This will return false. Example:
01=="01"
=> False
"01"=="01"
=> True
You don't need to cast the input to an integer.
As robert_x44 said, you are comparing an integer with a string.
Try:
itemone=01
itemtwo=02
Also, in your post the if blocks are not indented. It is probably just a formatting error, but python if statements must be indented.
Either change itemone and itemtwo to ints, or don't convert your input to an int. Right now you're comparing ints to strs, which won't work.
Pick one of the following two changes - don't make both or you'll just reverse the situation you're in now (comparing strs to ints instead of ints to strs.)
How to use just ints
Change:
itemone="01"
itemtwo="02"
to:
itemone=1
itemtwo=2
How to use just strs
Change:
c=int(input("Enter Item Code:"))
to:
c = input("Enter Item Code:")

Extract element from a shuffled list (based off of user's input)

I have something like this:
s=[7777,5454,75000,4545,787,16000,1000,9888,7854,12223]
random.shuffle(s)
ans=input('Press a number from 0 to 9')
I want to associate the input number ans with the s[ans] element. I can do it with 10 if loops, is this the only chance? //SOLVED this
Done that, I want to repeat the random extraction until user digits something like "stop" (here I am) and then sum all the value extracted until "stop" string. How can I do this last point?
Thanks all!
from random import choice
elem = choice (some_list)
If you are only trying to select a random number (and asking for input is only a means to achieve that goal), then you should really look into random.choice. It does exactly what you need, and you won't have to spend time shuffling your list
You can directly access values of an array like so:
s[ans]
But first you may have to convert ans to an integer (and handle cases where a user sends something that's not a number!)
try:
i = int(s)
except ValueError:
i = 0
You've edited your question to declare the original version "solved" and then added a second one. In the future, don't do that; accept the answer that solved the problem for you, then create a new question. (And you should still accept the answer that solved your original problem!) But this time only, here's a second answer:
Done that, I want to repeat the random extraction until user digits something like "stop" (here I am) and then sum all the value extracted until "stop" string. How can I do this last point?
I'm assuming you're on Python 2, and using the input function so the user can just type 2 and you get the number 2 instead of the string "2". (If you're using Python 3, input works like Python 2's raw_input, so see the second version.)
So:
s=[7777,5454,75000,4545,787,16000,1000,9888,7854,12223]
random.shuffle(s)
values = []
while True:
ans=input('Press a number from 0 to 9')
if ans == 'stop':
break
values.append(s[ans])
print sum(values)
Note that the user will have to type "stop" with the quotes this way. If the user instead types stop (or 10, for that matter), the program will quit with an exception. It would be much better to use raw_input instead, and do something like this:
s=[7777,5454,75000,4545,787,16000,1000,9888,7854,12223]
random.shuffle(s)
values = []
while True:
ans=raw_input('Press a number from 0 to 9, or stop when done')
if ans == 'stop':
break
try:
index = int(ans)
values.append(s[ans])
except ValueError:
print '{} is not a number or the word stop'.format(ans)
except IndexError:
print '{} is not between 0 and 9.'.format(ans)
print sum(values)
You may recognize that this values = [], while, values.append pattern is exactly what list comprehensions and iterators are for. And you can easily factor out all the user input into a generator function that just yields each s[ans], and then just print sum(userChoices()), without having to build up a list at all. But I'll leave that as an exercise for the reader.
ans = 0
s = [7777,5454,75000,4545,787,16000,1000,9888,7854,12223]
ans_sums = []
while ans != 'stop': # while the input is not 'stop'
random.shuffle(s)
ans = raw_input('Press a number from 0 to 9: ') # this returns the input as a string
if ans == 'stop':
break
else:
ans_sums.append(int(s[ans])) # adds s[ans] to ans_sums.
# it must be converted to an integer first because raw_input returns it as a string
return sum(s[ans])
Alternatively, you can do something like:
ans = 0
s = [7777,5454,75000,4545,787,16000,1000,9888,7854,12223]
ans_sums = 0
while ans != 'stop': # while the input is not 'stop'
random.shuffle(s)
ans = input('Press a number from 0 to 9: ')
if ans == 'stop':
break
else:
ans_sums += s[ans] # adds s[ans] to ans_sums
return ans_sums
This avoids creating a list and accomplishes the same job: finds the sum of all the input.

Categories