0

I trying to use a try statement in Python to check in 4 variables are numbers, if a variable contains something other than a number I have got it to ask the user to input try again, but then I want to have it call a function with those 4 variables (which could include a variable which the user has a entered a number for). The issue I am having is that I can't get the output of the for statement to order itself in a 1, 2, 3, 4 pattern. Any help would be greatly appreciated.

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

Thanks

Tom Cooper
  • 15
  • 3
  • 1
    I recommend to check one variable at a time in a loop, as explained in https://stackoverflow.com/questions/5424716/how-to-check-if-string-input-is-a-number – DYZ Aug 06 '17 at 01:52
  • Possible duplicate of [How to check if string input is a number?](https://stackoverflow.com/questions/5424716/how-to-check-if-string-input-is-a-number) – DYZ Aug 06 '17 at 01:52

2 Answers2

1

Your problem is that v is not a list, yet you index it like v[1] (also note that Python lists are indexed starting from 0, not 1).

You want something more like this:

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
John Zwinck
  • 239,568
  • 38
  • 324
  • 436
0

We will solve this by using array item replacement techniques.

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

Test this code at the following link: https://repl.it/JyaT/0