I am newbie to the python. I am sure this is a very basic question, but still I don’t get it in python.
I have two 1D-arrays, A and B of length 50.
I want to find for a given user input, A[0], I must return B[0], A[1]——> B[1] and so forth..
I have created a function to this task.
A = [10, 20,.... 500]
B = [1, 4,.... 2500]
def func():
x = input("enter a value from the array A: ") #user input
for i in range(50):
if A[i] == x:
print(B[i])
else:
print("do nothing")
func()
But if I call the function, I get nothing. I would appreciate if someone could help me. Thanks.
4 Answers 4
try this
A = [10, 20,.... 500]
B = [1, 4,.... 2500]
def func():
x = int(input("enter a value from the array A: ")) #user input
for i in range(50):
if A[i] == x:
print(B[i])
else:
print("do nothing")
func()
Comments
Maybe you can do it like this:
def func():
x=int(input("enter a value from the array A: "))
if x in A:
idx = A.index(x)
print(B[idx])
else:
print("do nothing")
Comments
This is a little better, you don't need to use range() and will not print a lot of do anything it will print do nothing if the value wasn't in A try this:
A = [10, 20,.... 500]
B = [1, 4,.... 2500]
def func():
x = int(input("enter a value from the array A: ")) #user input
for i,v in enumerate(A):
if v == x:
print(B[i])
break
else:
print("do nothing")
func()
read here to learn about for else.
1 Comment
Try this:
A = [10, 20,.... 500]
B = [1, 4,.... 2500]
def func():
print('A = ' + str(A))
x = int( input("Enter a value from the array A: ") )
# enter code here
# range(min_included, max_NOT_included) -> so range is [0, 1, 2 ... 49]
for i in range(0, 50):
if A[i] == x:
print(B[i])
else:
pass #equals 'do nothing', so you can even remove the 'else'
func()
inputcommand is different on Python 2 and 3, so I'm not 100% sure, but I have a feeling you need to convert it to an integer. You're basically doing something likeif 2 == "2", which isFalse.func(x).print((dict(zip(A, B))).get(int(x), None)). In a real program you would construct the dictionary once and reuse it. If you really want the "do nothing":print('\n'.join(b if int(x) == a else 'do nothing' for (a, b) in zip(A, B)))