2014-09-11 176 views
1

我正在嘗試編寫一個決定閏年的程序。我的問題是我不能將年份變量轉換爲整數。我試圖解析try語句中的變量。我收到的錯誤是將字符串轉換爲整數

line 19, in divide_by_4 
if (year%4) == 0: 
TypeError: not all arguments converted during string formatting 

我的代碼如下:我進口的文件,只有在它

def is_year(year): 
    '''determine if the input year can be converted into an integer''' 
    try: 
     int(year) 
     return year 
    except ValueError: 
     print("current year is not a year") 

def divide_by_4(year): 
    if (year%4) == 0: 
     return True 

def divide_by_100(year): 
    if (year % 100) == 0: 
     return True 

def divide_by_400(year): 
    if (year % 400) == 0: 
     return True 


def leap_year(year): 
    if is_year(year): 
     if divide_by_4(year): 
      if divide_by_100(year): 
       if divide_by_400(year): 
        return True 
      else: 
       if divide_by_400(year): 
        return True 


def main(): 

    input_file = input("Enter the file input file name: ") 
    output_file = input("Enter the output file name: ") 

    try: 
     file_in = open(input_file, 'r') 
    except IOError: 
     print("The input file could not be opened. The program is ending") 

    try: 
     file_out = open(output_file, 'w') 
    except IOError: 
     print("The output file could not be opened. The program is ending") 

    for years in file_in: 
     if leap_year(years): 
      file_out.write(years) 
    file_in.close() 
    file_out.close() 

main()  

回答

1

有1804怎麼樣:

​​

理由: 在is_year函數你實際上並沒有將String轉換爲int。相反,您只需檢查是否可以將其轉換。這就是爲什麼在使用year作爲整數之前,您需要進行實際轉換(int(year))

在divide_by_100中會出現同樣的問題。

0

當你從文件中讀取數據,數據的類型爲字符串,所以你不能用一年%4. 你可以做這樣的:

def leap_year(year): 
    if is_year(year): 
     year = int(year) 
     ...... 

然後去做