我如何将它分成两个不同的功能,仍然可以使它工作?

时间:2018-02-15 05:51:25

标签: python list function

如何让一个函数打开文件并读取它,另一个函数做数学计算闰年和工作?

我知道如何让它读取文件仍然是一个功能,但我不知道如何使它与数学一起工作。

def open_txt():
with open("all_years.txt","r") as f:
    f_contents = f.read()
    print(f_contents)
open_txt()

我的代码应该采用一个列表并计算变量/数字是否是4位数的闰年。 这是我应该使用的列表。 https://pastebin.com/bENBWSyB

File_leapyears = open(input("What file do you want to use?: "), "r")
for line in File_leapyears:
    year_str = line[:4]
    if year_str.isdigit():
        Leap_year = int(year_str)
        if Leap_year % 4 == 0 and Leap_year % 100 != 0:
            print(Leap_year)
        if Leap_year % 100 == 0 and Leap_year % 400 == 0:
            print(Leap_year)

1 个答案:

答案 0 :(得分:0)

您是否正在尝试执行以下操作:

def process(line):
    year_str = line[:4]
    if year_str.isdigit():
        Leap_year = int(year_str)
        if Leap_year % 4 == 0 and Leap_year % 100 != 0:
            return(Leap_year)
        if Leap_year % 100 == 0 and Leap_year % 400 == 0:
            return(Leap_year)
    return None

def read_file():
    File_leapyears = open(input("What file do you want to use?: "), "r")
    for line in File_leapyears:
        yes = process(line)
        if yes:
            print(yes)