Mass17
Mass17

Reputation: 1605

If condition inside for loop in python

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.

Upvotes: 1

Views: 1937

Answers (4)

Damiano Tagliaferri
Damiano Tagliaferri

Reputation: 11

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()

Upvotes: 0

Sociopath
Sociopath

Reputation: 13401

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")

Upvotes: 1

Mehrdad Pedramfar
Mehrdad Pedramfar

Reputation: 11073

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.

Upvotes: 0

EMKAY
EMKAY

Reputation: 369

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()

Upvotes: 5

Related Questions