2017-08-06 10 views
0

Pythonでtry文を使用してチェックインしようとしています。変数に数値以外の値が含まれている場合は4つの変数があります。再び、しかし、私は4つの変数(ユーザーが入力した変数を含む可能性があります)を持つ関数を呼び出させたいと考えています。私が抱えている問題は、for文の出力を1、2、3、4パターンで順序付けることができないということです。どんな助けでも大歓迎です。for文の変数を持つ関数を呼び出す

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

おかげ

+1

https://stackoverflow.com/questions/5424716/how-to -check-if-string-string-input-a-number – DyZ

+0

[文字列入力が数字であるかどうかを確認する方法]の複製がありますか?(https://stackoverflow.com/questions/5424716/how-to-check-if) -string-input-is-a-number) – DyZ

答えて

1

あなたの問題はvがリストではないということです、まだあなたのインデックスそれv[1]のように(また、Pythonのリストは、1、0から始まるインデックスが作成されていないことに注意してください)。私たちは、配列項目の代替技術を使用することによってこの問題を解決します

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

関連する問題