如果条件在python中的for循环内

时间:2018-09-25 13:53:01

标签: python python-3.x

我是python的新手。我确信这是一个非常基本的问题,但我仍然无法在python中得到它。

我有两个1D-arrays,A和B的长度为50。 我想找到给定的用户输入A [0],我必须返回B [0],A [1]-> B [1]等等。

我已经为此任务创建了一个函数。

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

但是,如果我调用该函数,我将一无所获。 如果有人可以帮助我,我将不胜感激。 谢谢。

4 个答案:

答案 0 :(得分:5)

尝试

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

答案 1 :(得分:1)

也许您可以这样:

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

答案 2 :(得分:0)

这会好一点,您不需要使用range()并且不会打印很多do anything,如果值不在{{ 1}}试试:

do nothing

阅读here,以了解A

答案 3 :(得分:0)

尝试一下:

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()
相关问题