使用for语句的变量调用函数

时间:2017-08-06 01:43:45

标签: python function for-loop

我试图在Python中使用一个try语句来检查4个变量是数字,如果一个变量包含的数字不是一个我已经得到它的东西要求用户输入再试一次,但是我想让它调用具有这4个变量的函数(可以包括用户输入数字的变量)。我遇到的问题是我无法获得for语句的输出以1,2,3,4模式排序。任何帮助将不胜感激。

def checkNumbersCompound(p, r, n, t):
    valuesDictionary = [p, r, n, t]
    for v in valuesDictionary:
        try:
            v = int(v)
        except:
            v = input(v + " is not a number, please enter a number to replace " + v + " (Don't include any symbols): ")
            print (v)
            checkNumbersCompound(v[1], v[2], v[3], v[4])

由于

2 个答案:

答案 0 :(得分:1)

您的问题是v不是列表,但您将其编入索引v[1](另请注意,Python列表从0开始编号,而不是1)。

你想要更像这样的东西:

def checkNumbersCompound(p, r, n, t):
    vd = {'p':p, 'r':r, 'n':n, 't':t}
    for name, v in vd.items():
        try:
            vd[name] = int(v)
        except:
            vd[name] = input(v + " is not a number, please enter a new value for " + name + " (Don't include any symbols): ")
            return checkNumbersCompound(vd['p'], vd['r'], vd['n'], vd['t'])
    return vd

答案 1 :(得分:0)

我们将通过使用数组项替换技术来解决这个问题。

def checkNumbersCompound(p, r, n, t):
  valuesDictionary = [p, r, n, t]
  position = 0 # this serves as an index
  for v in valuesDictionary:
    # print(position)
    position+=1
    try:
      v = int(v)
    except:
      v = input(v + " is not a number, please enter a number to replace " + v + " (Don't include any symbols): ")
      valuesDictionary[position-1] = v # replace the invalid item
      checkNumbersCompound(valuesDictionary[0], valuesDictionary[1], valuesDictionary[2], valuesDictionary[3])
      return 1
  #this will iterate over the dictionary and output items   
  for v in valuesDictionary:
      print(v)

checkNumbersCompound(1,2,'n',4) # This is a test line

在以下链接测试此代码:https://repl.it/JyaT/0