2017-05-12 13 views
-1

私のコードは以下の通りです:のpython3: "とValueError:int型のための無効なリテラル()ベース10と: '2.0'"

def MonthID(month): 
    """INPUT: 
    'month' is the amount of months after the beginning of the computed rotation. 

    OUTPUT: 
    Returns the month ID composed by the 3 first letters of the month 
    name and the amount of years after the beginning of the rotation. 
    """ 

    year = str((month//12)+1) 

    if month % 12 == 0: 
     return "dec"+ str(int(year) - 1) 
    elif month % 12 == 1: 
     return "jan"+year 
    elif month % 12 == 2: 
     return "feb"+year 

... など...ランダム

、ときyearが1を超えると、私はこのエラーを受け取ります:ValueError: invalid literal for int() with base 10: '2.0'。まあ、数字ではありません... ...

私はこれまで何の問題もなく、機能は正常に機能していました... 私の "12月のライン"を以下のように分解しようとしました。

year = int(year) - 1 
return "dec"+ str(year) 

他にこの種のエラーがありましたか? 関数が呼び出されたフレームから問題が発生することがありますが、私はそれを理解できません...私はprintでこの関数を使用して、コードがどこにあるのかを簡単に知ることができます。

答えて

0

monthfloatであれば、month//12floatです。これにより、month//12 + 1floatにもなります。それを文字列に変換すると、​​になります。通訳者は、​​が本当に無効なのリテラルの整数であるため、不平を言うのは正しいです。

これは、あなたのコードのどこかに浮動小数点の引数を持つMonthIDの呼び出しがあり、データのロード方法と関係がある可能性があることを意味します。したがって、簡単です

year = str(int(month//12)+1) 

トリックを行う必要があります。それにかかわらず、コードを読みやすく、エラーを起こしやすいように再構成することを検討する必要があります。関数外のタプルとして、月の名前を宣言考えてみましょう:

month_names = ('dec', 'jan', 'feb', 'mar', <other months here...>) 

その後:

def MonthID(month): 
    month = int(month) 
    year = month//12 + 1 
    if month % 12 == 0: 
     year -= 1 
    return month_names[month % 12] + str(year) 

または:

def MonthID(month): 
    year = int(month-1)//12 + 1 
    return month_names[int(month) % 12] + str(year) 
0

をうーん...私は回避策に資金を提供。今のところうまくいくようです:

year = (month//12)+1 

if month % 12 == 0: 
    year = year - 1 
    return "dec" + str(year) 
elif month % 12 == 1: 
    return "jan"+ str(year) 
elif month % 12 == 2: 
    return "fev"+ str(year) 
... 
etc 
... 
関連する問題