finding an element in an array based on user input [duplicate] - python

This question already has answers here:
Finding the index of an item in a list
(43 answers)
How can I read inputs as numbers?
(10 answers)
Closed 2 years ago.
Hi new to python and programming in general
I'm trying to find an element in an array based on user input
here's what i've done
a =[31,41,59,26,41,58]
input = input("Enter number : ")
for i in range(1,len(a),1) :
if input == a[i] :
print(i)
problem is that it doesn't print out anything.
what am I doing wrong here?

input returns a string. To make them integers wrap them in int.
inp=int(input('enter :'))
for i in range(0,len(a)-1):
if inp==a[i]:
print(i)
Indices in list start from 0 to len(list)-1.
Instead of using range(0,len(a)-1) it's preferred to use enumerate.
for idx,val in enumerate(a):
if inp==val:
print(idx)
To check if a inp is in a you can this.
>>> inp in a
True #if it exists or else False
You can use try-except also.
try:
print(a.index(inp))
except ValueError:
print('Element not Found')

input returns a string; a contains integers.
Your loop starts at 1, so it will never test against a[0] (in this case, 31).
And you shouldn't re-define the name input.

Please don't declare a variable input is not a good practise and Space is very important in Python
a =[31,41,59,26,41,58]
b = input("Enter number : ")
for i in range(1,len(a),1):
if int(b) == a[i] :
print(i)
I think you want to check a value from your list so your input need to be a Int. But input takes it as String. That's you need to convert it into int.

input is providing you a str but you are comparing a list of ints. That and your loop starts at 1 but your index starts at 0

Related

joining sequences together using the + operator

Does anyone know how to write this out in code using the + operator?
I've been trying for a while but I don't know how to get the output to be in the format:
Data: [1, 2, 3, 4]
This is my first time answering so I apologize in advance if my answer is unnecessarily complicated. First question I have is, do you have to use the '+' operator? If not, you could just append the numbers into a list (we can call the list 'ls') and then if you do print(ls) python should automatically print out the list like you want.
If you do have to use the '+' operator, you could have a string with an opening bracket, so just '[' and then every number they type in, you could add each number to the string using a loop.
Try this, not sure why do need + operator here, unless you want to write result += [int(value)]:
def main():
result = []
while True:
value = input("Enter an integer number (blank to exit): ")
if value == "":
return f'Data: {result}'
result.append(int(value))
print(main())

How to add numbers that begins with 1 to a list? [duplicate]

This question already has answers here:
Comparing digits in an integer in Python
(3 answers)
Closed 3 years ago.
How to add numbers that begin with 1 to a list?
def digit1x(lx):
list = []
for num in lx:
temp = str(num)
if temp[0]== '1':
list.append(int(temp))
return list
print(digit1x(lx))
updated code, and It works, thank you for your help!
You're thinking of numbers as starting with 1 in their base 10 representation? In that case, you should coerce to a string first before checking the digit:
>>> num = 12345
>>> str(num)
'12345'
>>> str(num)[0]
'1'
you cannot do num[0] if num is an int, for example you can write str(num)[0] == '1'. Don't forget to deal with special cases if any.
The error is occuring because you cannot get the [0] index value of an integer. It is only posible to get an index value of an array or string. Create a variable ('temp'↓) that is the string variable of the [0] index of that integer and then use that in the conditional statement:
This works:
def digit1x(lx):
list = []
for num in lx:
temp = str(lx[num])
if temp[0] == '1':
list.append(temp)
return list
print(digit1x(lx))
The value of temp is the string value of the current item.
'temp[0]' is the first character in temp, and therefore the first character in the current item.
Therefore, if temp[0] equals '1' then the first number in the current item is 1.

Linear Search - Matching integer with list

Hi am new to python here is what am trying to do , i have this below list.
x= [1,2,3,4,5,6,7,8,9]
and here is my python code:
length = len(x)
c = input("Enter a no\n")
for i in range (length):
if x[i] == c:
print ("Found at position ", i)
else:
print("not found")
and the output am receiving.
Enter a no
2
not found
not found
not found
not found
not found
not found
not found
not found
not found
Now with my very few little knowledge what i figured out is this multiple not found is happening because every time loop takes a no checks with the list and if its not available its moving to else part due to lack no proper beak statement but what am not able to figure out that when it takes to in x[i] its matching then output should be Found at position 1 . i read somewhere need to use if c in x[i] but it didn't work. on the hand i re-wrote the code.
def ls():
t = int(input("Enter your search no \n"))
for i in x:
if i!= t:
continue
print("Your value is present in ")
break
else:
print ("parrrrrrrrrrr")
ls()
which is working all good. It will be of help if i can get to know:
with 1st program why its showing not found even the input is present in the list
the part where c in x[i] was entered same issue happened as per my knowing (which now makes no-sense) it should also work
if it is the case of integer vs list then how my 2nd code is working
-is it the rigt way to do linear search.
Because input returns you a str object and then compared with int object without implicit conversion, so the expression always be False.
c in x where x is a list works, but x[i] is an integer in your case
2nd code is working because you convert the input into int implicitly
The most elegant way in my opinion is:
c = input("Enter a no\n")
items = [1,2,3]
print(items.index(int(c)) if int(c) in items else 'Not found')
And of course dont forget to catch ValueError if input is not convertable into integer

How do print the odd letters of an input in python [duplicate]

This question already has answers here:
Extract elements of list at odd positions
(5 answers)
Closed 7 years ago.
I have to do this for school, but I can't work it out. I have to get an input and print ONLY the odd characters. So far I've put the input in a list and I have a while loop (which was a clue on the task sheet), but I can't work it out. Please help:
inp = input('What is your name? ')
name = []
name.append(inp)
n=1
while n<len(name):
print inp[1::2]
I guess thats all you need
You don't need to put the string in a list, a string is already essentially a list of characters (more formally, it is a "sequence").
You can use indexing and the modulus operator (%) for this
inp = input('What is your name? ')
n = 0 # index variable
while n < len(inp):
if n % 2 == 1: # check if it is an odd letter
print(inp[n]) # print out that letter
n += 1

number/numbers to list by using input() [duplicate]

This question already has answers here:
Get a list of numbers as input from the user
(11 answers)
Closed 6 years ago.
Maybe this is a very basic question but i am a beginner in python and couldnt find any solution. i was writing a python script and got stuck because i cant use python lists effective. i want user to input (number or numbers) and store them in a python list as integers. for example user can input single number 1 or multiple numbers seperated by comma 1,2,3 and i want to save them to a list in integers.
i tried this ;
def inputnumber():
number =[]
num = input();
number.append(num)
number = map(int,number)
return (number)
def main():
x = inputnumber()
print x
for a single number there is no problem but if the the input is like 1,2,3 it gives an error:
Traceback (most recent call last):
File "test.py", line 26, in <module>
main()
File "test.py", line 21, in main
x = inputnumber()
File "test.py", line 16, in inputnumber
number = map(int,number)
TypeError: int() argument must be a string or a number, not 'tuple'
Also i have to take into account that user may input characters instead of numbers too. i have to filter this. if the user input a word a single char. i know that i must use try: except. but couldn't handle. i searched the stackoverflow and the internet but in the examples that i found the input wanted from user was like;
>>>[1,2,3]
i found something this Mark Byers's answer in stackoverflow but couldn't make it work
i use python 2.5 in windows.
Sorry for my English. Thank you so much for your helps.
In your function, you can directly convert num into a list by calling split(','), which will split on a comma - in the case a comma doesn't exist, you just get a single-element list. For example:
In [1]: num = '1'
In [2]: num.split(',')
Out[2]: ['1']
In [3]: num = '1,2,3,4'
In [4]: num.split(',')
Out[4]: ['1', '2', '3', '4']
You can then use your function as you have it:
def inputnumber():
num = raw_input('Enter number(s): ').split(',')
number = map(int,num)
return number
x = inputnumber()
print x
However you can take it a step further if you want - map here can be replaced by a list comprehension, and you can also get rid of the intermediate variable number and return the result of the comprehension (same would work for map as well, if you want to keep that):
def inputnumber():
num = raw_input('Enter number(s): ').split(',')
return [int(n) for n in num]
x = inputnumber()
print x
If you want to handle other types of input without error, you can use a try/except block (and handle the ValueError exception), or use one of the fun methods on strings to check if the number is a digit:
def inputnumber():
num = raw_input('Enter number(s): ').split(',')
return [int(n) for n in num if n.isdigit()]
x = inputnumber()
print x
This shows some of the power of a list comprehension - here we say 'cast this value as an integer, but only if it is a digit (that is the if n.isdigit() part).
And as you may have guessed, you can collapse it even more by getting rid of the function entirely and just making it a one-liner (this is an awesome/tricky feature of Python - condensing to one-liners is surprisingly easy, but can lead to less readable code in some case, so I vote for your approach above :) ):
print [int(n) for n in raw_input('Number(s): ').split(',') if n.isdigit()]
input is not the way to go here - it evaluates the input as python code. Use raw_input instead, which returns a string. So what you want is this:
def inputnumber():
num = raw_input()
for i, j in enumerate(num):
if j not in ', ':
try:
int(num[i])
except ValueError:
#error handling goes here
return num
def main():
x = inputnumber()
print x
I guess all it is is a long-winded version of RocketDonkey's answer.

Categories